blob: 08f0f099352198f712dcad6b312b0e1731da1494 [file] [log] [blame]
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
Xiaohui Chen594f2082015-08-18 11:04:20 -070019import android.annotation.NonNull;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070020import android.app.Activity;
Amith Yamasani2a003292012-08-14 18:25:45 -070021import android.app.ActivityManager;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070022import android.app.ActivityManagerNative;
23import android.app.IStopUserCallback;
Xiaohui Chen203243a2015-07-16 11:55:47 -070024import android.app.admin.DevicePolicyManager;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070025import android.content.BroadcastReceiver;
Amith Yamasani258848d2012-08-10 17:06:33 -070026import android.content.Context;
27import android.content.Intent;
Amith Yamasani1a7472e2013-07-02 11:17:30 -070028import android.content.pm.ApplicationInfo;
Amith Yamasani0b285492011-04-14 17:35:23 -070029import android.content.pm.PackageManager;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -080030import android.content.pm.PackageManager.NameNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070031import android.content.pm.UserInfo;
Amith Yamasanie928d7d2012-09-17 21:46:51 -070032import android.graphics.Bitmap;
Amith Yamasani258848d2012-08-10 17:06:33 -070033import android.os.Binder;
Amith Yamasanie4cf7342012-12-17 11:12:09 -080034import android.os.Bundle;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070035import android.os.Environment;
36import android.os.FileUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080037import android.os.Handler;
Amith Yamasani258848d2012-08-10 17:06:33 -070038import android.os.IUserManager;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -080039import android.os.Message;
Adrian Roos1bdff912015-02-17 15:51:35 +010040import android.os.ParcelFileDescriptor;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070041import android.os.Parcelable;
Amith Yamasani258848d2012-08-10 17:06:33 -070042import android.os.Process;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070043import android.os.RemoteException;
Jason Monk62062992014-05-06 09:55:28 -040044import android.os.ServiceManager;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070045import android.os.UserHandle;
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070046import android.os.UserManager;
Paul Crowley85e4e812015-05-19 12:42:00 +010047import android.os.storage.StorageManager;
Jeff Sharkey6dce4962015-07-03 18:08:41 -070048import android.os.storage.VolumeInfo;
49import android.system.ErrnoException;
50import android.system.Os;
51import android.system.OsConstants;
Amith Yamasani2a003292012-08-14 18:25:45 -070052import android.util.AtomicFile;
Amith Yamasani655d0e22013-06-12 14:19:10 -070053import android.util.Log;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070054import android.util.Slog;
55import android.util.SparseArray;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080056import android.util.SparseBooleanArray;
Amith Yamasani920ace02012-09-20 22:15:37 -070057import android.util.TimeUtils;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070058import android.util.Xml;
59
Fyodor Kupolovb5013302015-04-17 17:59:14 -070060import com.google.android.collect.Sets;
61
Fyodor Kupolov262f9952015-03-23 18:55:11 -070062import com.android.internal.annotations.VisibleForTesting;
Jason Monk62062992014-05-06 09:55:28 -040063import com.android.internal.app.IAppOpsService;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080064import com.android.internal.util.ArrayUtils;
65import com.android.internal.util.FastXmlSerializer;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070066import com.android.internal.util.XmlUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080067
68import org.xmlpull.v1.XmlPullParser;
69import org.xmlpull.v1.XmlPullParserException;
70import org.xmlpull.v1.XmlSerializer;
71
Amith Yamasani4b2e9342011-03-31 12:38:53 -070072import java.io.BufferedOutputStream;
73import java.io.File;
Amith Yamasani920ace02012-09-20 22:15:37 -070074import java.io.FileDescriptor;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070075import java.io.FileInputStream;
Amith Yamasanib8151ec2012-04-18 18:02:48 -070076import java.io.FileNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070077import java.io.FileOutputStream;
78import java.io.IOException;
Amith Yamasani920ace02012-09-20 22:15:37 -070079import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +010080import java.nio.charset.StandardCharsets;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070081import java.util.ArrayList;
82import java.util.List;
Fyodor Kupolovb5013302015-04-17 17:59:14 -070083import java.util.Set;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070084
Fyodor Kupolov262f9952015-03-23 18:55:11 -070085import libcore.io.IoUtils;
86
Amith Yamasani258848d2012-08-10 17:06:33 -070087public class UserManagerService extends IUserManager.Stub {
Amith Yamasanib8151ec2012-04-18 18:02:48 -070088
Amith Yamasani2a003292012-08-14 18:25:45 -070089 private static final String LOG_TAG = "UserManagerService";
Amith Yamasanib8151ec2012-04-18 18:02:48 -070090
Amith Yamasani16389312012-10-17 21:20:14 -070091 private static final boolean DBG = false;
92
Amith Yamasani4b2e9342011-03-31 12:38:53 -070093 private static final String TAG_NAME = "name";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070094 private static final String ATTR_FLAGS = "flags";
Amith Yamasanib8151ec2012-04-18 18:02:48 -070095 private static final String ATTR_ICON_PATH = "icon";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070096 private static final String ATTR_ID = "id";
Amith Yamasani920ace02012-09-20 22:15:37 -070097 private static final String ATTR_CREATION_TIME = "created";
98 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
Amith Yamasani2a003292012-08-14 18:25:45 -070099 private static final String ATTR_SERIAL_NO = "serialNumber";
100 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700101 private static final String ATTR_PARTIAL = "partial";
Adam Lesinskieddeb492014-09-08 17:50:03 -0700102 private static final String ATTR_GUEST_TO_REMOVE = "guestToRemove";
Amith Yamasani6f34b412012-10-22 18:19:27 -0700103 private static final String ATTR_USER_VERSION = "version";
Kenny Guy2a764942014-04-02 13:29:20 +0100104 private static final String ATTR_PROFILE_GROUP_ID = "profileGroupId";
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530105 private static final String TAG_GUEST_RESTRICTIONS = "guestRestrictions";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700106 private static final String TAG_USERS = "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700107 private static final String TAG_USER = "user";
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800108 private static final String TAG_RESTRICTIONS = "restrictions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800109 private static final String TAG_ENTRY = "entry";
110 private static final String TAG_VALUE = "value";
111 private static final String ATTR_KEY = "key";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700112 private static final String ATTR_VALUE_TYPE = "type";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800113 private static final String ATTR_MULTIPLE = "m";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700114
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700115 private static final String ATTR_TYPE_STRING_ARRAY = "sa";
116 private static final String ATTR_TYPE_STRING = "s";
117 private static final String ATTR_TYPE_BOOLEAN = "b";
Amith Yamasani5b5aa402014-06-01 20:10:14 -0700118 private static final String ATTR_TYPE_INTEGER = "i";
Fyodor Kupolov262f9952015-03-23 18:55:11 -0700119 private static final String ATTR_TYPE_BUNDLE = "B";
120 private static final String ATTR_TYPE_BUNDLE_ARRAY = "BA";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700121
Amith Yamasani0b285492011-04-14 17:35:23 -0700122 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700123 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700124 private static final String USER_PHOTO_FILENAME = "photo.png";
Adrian Roos1bdff912015-02-17 15:51:35 +0100125 private static final String USER_PHOTO_FILENAME_TMP = USER_PHOTO_FILENAME + ".tmp";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700126
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800127 private static final String RESTRICTIONS_FILE_PREFIX = "res_";
Amith Yamasanifc95e702013-09-26 13:20:17 -0700128 private static final String XML_SUFFIX = ".xml";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800129
Amith Yamasani634cf312012-10-04 17:34:21 -0700130 private static final int MIN_USER_ID = 10;
131
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700132 private static final int USER_VERSION = 5;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700133
Amith Yamasani920ace02012-09-20 22:15:37 -0700134 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
135
Amith Yamasani95ab7842014-08-11 17:09:26 -0700136 // Maximum number of managed profiles permitted is 1. This cannot be increased
137 // without first making sure that the rest of the framework is prepared for it.
138 private static final int MAX_MANAGED_PROFILES = 1;
139
Andres Moralesc5548c02015-08-05 10:23:12 -0700140 /**
141 * Flag indicating whether device credentials are shared among same-user profiles.
142 */
143 private static final boolean CONFIG_PROFILES_SHARE_CREDENTIAL = true;
144
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700145 // Set of user restrictions, which can only be enforced by the system
146 private static final Set<String> SYSTEM_CONTROLLED_RESTRICTIONS = Sets.newArraySet(
147 UserManager.DISALLOW_RECORD_AUDIO);
148
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800149 static final int WRITE_USER_MSG = 1;
150 static final int WRITE_USER_DELAY = 2*1000; // 2 seconds
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530151
Jeff Sharkey6dce4962015-07-03 18:08:41 -0700152 private static final String XATTR_SERIAL = "user.serial";
153
Dianne Hackborn4428e172012-08-24 17:43:05 -0700154 private final Context mContext;
155 private final PackageManagerService mPm;
156 private final Object mInstallLock;
157 private final Object mPackagesLock;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700158
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800159 private final Handler mHandler;
160
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700161 private final File mUsersDir;
162 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700163
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800164 private final SparseArray<UserInfo> mUsers = new SparseArray<UserInfo>();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800165 private final SparseArray<Bundle> mUserRestrictions = new SparseArray<Bundle>();
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530166 private final Bundle mGuestRestrictions = new Bundle();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800167
168 /**
169 * Set of user IDs being actively removed. Removed IDs linger in this set
170 * for several seconds to work around a VFS caching issue.
171 */
172 // @GuardedBy("mPackagesLock")
173 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700174
Amith Yamasani0b285492011-04-14 17:35:23 -0700175 private int[] mUserIds;
Amith Yamasani2a003292012-08-14 18:25:45 -0700176 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700177 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700178
Jason Monk62062992014-05-06 09:55:28 -0400179 private IAppOpsService mAppOpsService;
180
Amith Yamasani258848d2012-08-10 17:06:33 -0700181 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700182
Dianne Hackborn4428e172012-08-24 17:43:05 -0700183 public static UserManagerService getInstance() {
184 synchronized (UserManagerService.class) {
185 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700186 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700187 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700188
189 /**
190 * Available for testing purposes.
191 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700192 UserManagerService(File dataDir, File baseUserPath) {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700193 this(null, null, new Object(), new Object(), dataDir, baseUserPath);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700194 }
195
Dianne Hackborn4428e172012-08-24 17:43:05 -0700196 /**
197 * Called by package manager to create the service. This is closely
198 * associated with the package manager, and the given lock is the
199 * package manager's own lock.
200 */
201 UserManagerService(Context context, PackageManagerService pm,
202 Object installLock, Object packagesLock) {
203 this(context, pm, installLock, packagesLock,
204 Environment.getDataDirectory(),
205 new File(Environment.getDataDirectory(), "user"));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700206 }
207
Dianne Hackborn4428e172012-08-24 17:43:05 -0700208 /**
209 * Available for testing purposes.
210 */
211 private UserManagerService(Context context, PackageManagerService pm,
212 Object installLock, Object packagesLock,
213 File dataDir, File baseUserPath) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700214 mContext = context;
215 mPm = pm;
216 mInstallLock = installLock;
217 mPackagesLock = packagesLock;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800218 mHandler = new MainHandler();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700219 synchronized (mInstallLock) {
220 synchronized (mPackagesLock) {
221 mUsersDir = new File(dataDir, USER_INFO_DIR);
222 mUsersDir.mkdirs();
223 // Make zeroth user directory, for services to migrate their files to that location
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700224 File userZeroDir = new File(mUsersDir, String.valueOf(UserHandle.USER_SYSTEM));
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700225 userZeroDir.mkdirs();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700226 FileUtils.setPermissions(mUsersDir.toString(),
227 FileUtils.S_IRWXU|FileUtils.S_IRWXG
228 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
229 -1, -1);
230 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
Amith Yamasanida0b1682014-11-21 12:58:17 -0800231 initDefaultGuestRestrictions();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700232 readUserListLocked();
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700233 sInstance = this;
234 }
235 }
236 }
237
238 void systemReady() {
239 synchronized (mInstallLock) {
240 synchronized (mPackagesLock) {
Amith Yamasani756901d2012-10-12 12:30:07 -0700241 // Prune out any partially created/partially removed users.
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700242 ArrayList<UserInfo> partials = new ArrayList<UserInfo>();
243 for (int i = 0; i < mUsers.size(); i++) {
244 UserInfo ui = mUsers.valueAt(i);
Adam Lesinskieddeb492014-09-08 17:50:03 -0700245 if ((ui.partial || ui.guestToRemove) && i != 0) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700246 partials.add(ui);
247 }
248 }
249 for (int i = 0; i < partials.size(); i++) {
250 UserInfo ui = partials.get(i);
Amith Yamasania7892482015-08-07 11:09:05 -0700251 Slog.w(LOG_TAG, "Removing partially created user " + ui.id
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700252 + " (name=" + ui.name + ")");
253 removeUserStateLocked(ui.id);
254 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700255 }
Dianne Hackborn4428e172012-08-24 17:43:05 -0700256 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700257 onUserForeground(UserHandle.USER_SYSTEM);
Jason Monk62062992014-05-06 09:55:28 -0400258 mAppOpsService = IAppOpsService.Stub.asInterface(
259 ServiceManager.getService(Context.APP_OPS_SERVICE));
260 for (int i = 0; i < mUserIds.length; ++i) {
261 try {
262 mAppOpsService.setUserRestrictions(mUserRestrictions.get(mUserIds[i]), mUserIds[i]);
263 } catch (RemoteException e) {
264 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
265 }
266 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700267 }
268
269 @Override
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700270 public UserInfo getPrimaryUser() {
271 checkManageUsersPermission("query users");
272 synchronized (mPackagesLock) {
273 for (int i = 0; i < mUsers.size(); i++) {
274 UserInfo ui = mUsers.valueAt(i);
275 if (ui.isPrimary()) {
276 return ui;
277 }
278 }
279 }
280 return null;
281 }
282
283 @Override
Xiaohui Chen594f2082015-08-18 11:04:20 -0700284 public @NonNull List<UserInfo> getUsers(boolean excludeDying) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700285 checkManageUsersPermission("query users");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700286 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700287 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
288 for (int i = 0; i < mUsers.size(); i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700289 UserInfo ui = mUsers.valueAt(i);
290 if (ui.partial) {
291 continue;
292 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800293 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700294 users.add(ui);
Amith Yamasani920ace02012-09-20 22:15:37 -0700295 }
Amith Yamasani13593602012-03-22 16:16:17 -0700296 }
297 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700298 }
Amith Yamasani13593602012-03-22 16:16:17 -0700299 }
300
Amith Yamasani258848d2012-08-10 17:06:33 -0700301 @Override
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100302 public List<UserInfo> getProfiles(int userId, boolean enabledOnly) {
Amith Yamasani4f582632014-02-19 14:31:52 -0800303 if (userId != UserHandle.getCallingUserId()) {
304 checkManageUsersPermission("getting profiles related to user " + userId);
305 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700306 final long ident = Binder.clearCallingIdentity();
307 try {
308 synchronized (mPackagesLock) {
309 return getProfilesLocked(userId, enabledOnly);
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100310 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700311 } finally {
312 Binder.restoreCallingIdentity(ident);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000313 }
314 }
315
Amith Yamasanibe465322014-04-24 13:45:17 -0700316 /** Assume permissions already checked and caller's identity cleared */
317 private List<UserInfo> getProfilesLocked(int userId, boolean enabledOnly) {
Amith Yamasanibe465322014-04-24 13:45:17 -0700318 UserInfo user = getUserInfoLocked(userId);
319 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasanidda003f2014-08-28 18:06:51 -0700320 if (user == null) {
321 // Probably a dying user
322 return users;
323 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700324 for (int i = 0; i < mUsers.size(); i++) {
325 UserInfo profile = mUsers.valueAt(i);
326 if (!isProfileOf(user, profile)) {
327 continue;
328 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100329 if (enabledOnly && !profile.isEnabled()) {
330 continue;
Amith Yamasanibe465322014-04-24 13:45:17 -0700331 }
Amith Yamasani70fcf0c2014-07-11 08:40:19 -0700332 if (mRemovingUserIds.get(profile.id)) {
333 continue;
334 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700335 users.add(profile);
336 }
337 return users;
338 }
339
Jessica Hummelbe81c802014-04-22 15:49:22 +0100340 @Override
Andres Moralesc5548c02015-08-05 10:23:12 -0700341 public int getCredentialOwnerProfile(int userHandle) {
342 checkManageUsersPermission("get the credential owner");
343 if (CONFIG_PROFILES_SHARE_CREDENTIAL) {
344 synchronized (mPackagesLock) {
345 UserInfo profileParent = getProfileParentLocked(userHandle);
346 if (profileParent != null) {
347 return profileParent.id;
348 }
349 }
350 }
351
352 return userHandle;
353 }
354
355 @Override
Jessica Hummelbe81c802014-04-22 15:49:22 +0100356 public UserInfo getProfileParent(int userHandle) {
357 checkManageUsersPermission("get the profile parent");
358 synchronized (mPackagesLock) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700359 return getProfileParentLocked(userHandle);
360 }
361 }
362
363 private UserInfo getProfileParentLocked(int userHandle) {
364 UserInfo profile = getUserInfoLocked(userHandle);
365 if (profile == null) {
366 return null;
367 }
368 int parentUserId = profile.profileGroupId;
369 if (parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
370 return null;
371 } else {
372 return getUserInfoLocked(parentUserId);
Jessica Hummelbe81c802014-04-22 15:49:22 +0100373 }
374 }
375
Kenny Guy2a764942014-04-02 13:29:20 +0100376 private boolean isProfileOf(UserInfo user, UserInfo profile) {
377 return user.id == profile.id ||
378 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
379 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000380 }
381
382 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100383 public void setUserEnabled(int userId) {
384 checkManageUsersPermission("enable user");
385 synchronized (mPackagesLock) {
386 UserInfo info = getUserInfoLocked(userId);
387 if (info != null && !info.isEnabled()) {
388 info.flags ^= UserInfo.FLAG_DISABLED;
389 writeUserLocked(info);
390 }
391 }
392 }
393
394 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700395 public UserInfo getUserInfo(int userId) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700396 checkManageUsersPermission("query user");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700397 synchronized (mPackagesLock) {
Amith Yamasani195263742012-08-21 15:40:12 -0700398 return getUserInfoLocked(userId);
Amith Yamasani13593602012-03-22 16:16:17 -0700399 }
400 }
401
Amith Yamasani71e6c692013-03-24 17:39:28 -0700402 @Override
403 public boolean isRestricted() {
404 synchronized (mPackagesLock) {
405 return getUserInfoLocked(UserHandle.getCallingUserId()).isRestricted();
406 }
407 }
408
Amith Yamasani195263742012-08-21 15:40:12 -0700409 /*
410 * Should be locked on mUsers before calling this.
411 */
412 private UserInfo getUserInfoLocked(int userId) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700413 UserInfo ui = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -0700414 // If it is partial and not in the process of being removed, return as unknown user.
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800415 if (ui != null && ui.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700416 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
417 return null;
418 }
419 return ui;
Amith Yamasani195263742012-08-21 15:40:12 -0700420 }
421
Amith Yamasani13593602012-03-22 16:16:17 -0700422 public boolean exists(int userId) {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700423 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700424 return ArrayUtils.contains(mUserIds, userId);
425 }
426 }
427
Amith Yamasani258848d2012-08-10 17:06:33 -0700428 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700429 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700430 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700431 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700432 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700433 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700434 if (info == null || info.partial) {
435 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
436 return;
437 }
Amith Yamasani13593602012-03-22 16:16:17 -0700438 if (name != null && !name.equals(info.name)) {
439 info.name = name;
440 writeUserLocked(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700441 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -0700442 }
443 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700444 if (changed) {
445 sendUserInfoChangedBroadcast(userId);
446 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700447 }
448
Amith Yamasani258848d2012-08-10 17:06:33 -0700449 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700450 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700451 checkManageUsersPermission("update users");
Jason Monk9a944532014-07-08 09:31:21 -0400452 long ident = Binder.clearCallingIdentity();
453 try {
454 synchronized (mPackagesLock) {
455 UserInfo info = mUsers.get(userId);
456 if (info == null || info.partial) {
457 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
458 return;
459 }
460 writeBitmapLocked(info, bitmap);
461 writeUserLocked(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700462 }
Jason Monk9a944532014-07-08 09:31:21 -0400463 sendUserInfoChangedBroadcast(userId);
464 } finally {
465 Binder.restoreCallingIdentity(ident);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700466 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700467 }
468
469 private void sendUserInfoChangedBroadcast(int userId) {
470 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
471 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
472 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -0700473 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700474 }
475
Amith Yamasani258848d2012-08-10 17:06:33 -0700476 @Override
Adrian Roos1bdff912015-02-17 15:51:35 +0100477 public ParcelFileDescriptor getUserIcon(int userId) {
478 String iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700479 synchronized (mPackagesLock) {
480 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700481 if (info == null || info.partial) {
482 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + userId);
483 return null;
484 }
Nicolas Prevot88cc3462014-05-14 14:51:48 +0100485 int callingGroupId = mUsers.get(UserHandle.getCallingUserId()).profileGroupId;
486 if (callingGroupId == UserInfo.NO_PROFILE_GROUP_ID
487 || callingGroupId != info.profileGroupId) {
488 checkManageUsersPermission("get the icon of a user who is not related");
489 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700490 if (info.iconPath == null) {
491 return null;
492 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100493 iconPath = info.iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700494 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100495
496 try {
497 return ParcelFileDescriptor.open(
498 new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
499 } catch (FileNotFoundException e) {
500 Log.e(LOG_TAG, "Couldn't find icon file", e);
501 }
502 return null;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700503 }
504
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700505 public void makeInitialized(int userId) {
506 checkManageUsersPermission("makeInitialized");
507 synchronized (mPackagesLock) {
508 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700509 if (info == null || info.partial) {
510 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
511 }
512 if ((info.flags&UserInfo.FLAG_INITIALIZED) == 0) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700513 info.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800514 scheduleWriteUserLocked(info);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700515 }
516 }
517 }
518
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700519 /**
520 * If default guest restrictions haven't been initialized yet, add the basic
521 * restrictions.
522 */
523 private void initDefaultGuestRestrictions() {
524 if (mGuestRestrictions.isEmpty()) {
525 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
Amith Yamasanida0b1682014-11-21 12:58:17 -0800526 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700527 }
528 }
529
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800530 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530531 public Bundle getDefaultGuestRestrictions() {
532 checkManageUsersPermission("getDefaultGuestRestrictions");
533 synchronized (mPackagesLock) {
534 return new Bundle(mGuestRestrictions);
535 }
536 }
537
538 @Override
539 public void setDefaultGuestRestrictions(Bundle restrictions) {
540 checkManageUsersPermission("setDefaultGuestRestrictions");
541 synchronized (mPackagesLock) {
542 mGuestRestrictions.clear();
543 mGuestRestrictions.putAll(restrictions);
544 writeUserListLocked();
545 }
546 }
547
548 @Override
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700549 public boolean hasUserRestriction(String restrictionKey, int userId) {
550 synchronized (mPackagesLock) {
551 Bundle restrictions = mUserRestrictions.get(userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700552 return restrictions != null && restrictions.getBoolean(restrictionKey);
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700553 }
554 }
555
556 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800557 public Bundle getUserRestrictions(int userId) {
558 // checkManageUsersPermission("getUserRestrictions");
559
560 synchronized (mPackagesLock) {
561 Bundle restrictions = mUserRestrictions.get(userId);
Amith Yamasanibe465322014-04-24 13:45:17 -0700562 return restrictions != null ? new Bundle(restrictions) : new Bundle();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800563 }
564 }
565
566 @Override
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700567 public void setUserRestriction(String key, boolean value, int userId) {
Fyodor Kupolovd4b26042015-07-27 14:30:59 -0700568 checkManageUsersPermission("setUserRestriction");
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700569 synchronized (mPackagesLock) {
570 if (!SYSTEM_CONTROLLED_RESTRICTIONS.contains(key)) {
571 Bundle restrictions = getUserRestrictions(userId);
572 restrictions.putBoolean(key, value);
573 setUserRestrictionsInternalLocked(restrictions, userId);
574 }
575 }
576 }
577
578 @Override
579 public void setSystemControlledUserRestriction(String key, boolean value, int userId) {
580 checkSystemOrRoot("setSystemControlledUserRestriction");
581 synchronized (mPackagesLock) {
582 Bundle restrictions = getUserRestrictions(userId);
583 restrictions.putBoolean(key, value);
584 setUserRestrictionsInternalLocked(restrictions, userId);
585 }
586 }
587
588 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800589 public void setUserRestrictions(Bundle restrictions, int userId) {
Amith Yamasanibe465322014-04-24 13:45:17 -0700590 checkManageUsersPermission("setUserRestrictions");
Amith Yamasani0343ec32013-07-22 14:52:06 -0700591 if (restrictions == null) return;
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800592
593 synchronized (mPackagesLock) {
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700594 final Bundle oldUserRestrictions = mUserRestrictions.get(userId);
595 // Restore the original state of system controlled restrictions from oldUserRestrictions
596 for (String key : SYSTEM_CONTROLLED_RESTRICTIONS) {
597 restrictions.remove(key);
598 if (oldUserRestrictions.containsKey(key)) {
599 restrictions.putBoolean(key, oldUserRestrictions.getBoolean(key));
600 }
Jason Monk62062992014-05-06 09:55:28 -0400601 }
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700602 setUserRestrictionsInternalLocked(restrictions, userId);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800603 }
604 }
605
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700606 private void setUserRestrictionsInternalLocked(Bundle restrictions, int userId) {
607 final Bundle userRestrictions = mUserRestrictions.get(userId);
608 userRestrictions.clear();
609 userRestrictions.putAll(restrictions);
610 long token = Binder.clearCallingIdentity();
611 try {
612 mAppOpsService.setUserRestrictions(userRestrictions, userId);
613 } catch (RemoteException e) {
614 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
615 } finally {
616 Binder.restoreCallingIdentity(token);
617 }
618 scheduleWriteUserLocked(mUsers.get(userId));
619 }
620
Amith Yamasani258848d2012-08-10 17:06:33 -0700621 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700622 * Check if we've hit the limit of how many users can be created.
623 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700624 private boolean isUserLimitReachedLocked() {
Nicolas Prevot12678a92015-05-13 12:15:03 -0700625 return getAliveUsersExcludingGuestsCountLocked() >= UserManager.getMaxSupportedUsers();
626 }
627
628 @Override
629 public boolean canAddMoreManagedProfiles() {
630 checkManageUsersPermission("check if more managed profiles can be added.");
631 if (ActivityManager.isLowRamDeviceStatic()) {
632 return false;
633 }
Fyodor Kupolovb6157992015-06-05 15:32:28 -0700634 if (!mContext.getPackageManager().hasSystemFeature(
635 PackageManager.FEATURE_MANAGED_USERS)) {
636 return false;
637 }
Nicolas Prevot12678a92015-05-13 12:15:03 -0700638 synchronized(mPackagesLock) {
639 // Limit number of managed profiles that can be created
640 if (numberOfUsersOfTypeLocked(UserInfo.FLAG_MANAGED_PROFILE, true)
641 >= MAX_MANAGED_PROFILES) {
642 return false;
643 }
644 int usersCount = getAliveUsersExcludingGuestsCountLocked();
645 // We allow creating a managed profile in the special case where there is only one user.
646 return usersCount == 1 || usersCount < UserManager.getMaxSupportedUsers();
647 }
648 }
649
650 private int getAliveUsersExcludingGuestsCountLocked() {
Amith Yamasanif584f012014-05-19 17:57:25 -0700651 int aliveUserCount = 0;
652 final int totalUserCount = mUsers.size();
653 // Skip over users being removed
654 for (int i = 0; i < totalUserCount; i++) {
655 UserInfo user = mUsers.valueAt(i);
Amith Yamasani95ab7842014-08-11 17:09:26 -0700656 if (!mRemovingUserIds.get(user.id)
Amith Yamasani1df14732014-08-29 21:37:27 -0700657 && !user.isGuest() && !user.partial) {
Amith Yamasanif584f012014-05-19 17:57:25 -0700658 aliveUserCount++;
659 }
660 }
Nicolas Prevot12678a92015-05-13 12:15:03 -0700661 return aliveUserCount;
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700662 }
663
664 /**
Amith Yamasani195263742012-08-21 15:40:12 -0700665 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -0700666 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -0700667 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -0700668 *
669 * @param message used as message if SecurityException is thrown
670 * @throws SecurityException if the caller is not system or root
671 */
Amith Yamasanibe465322014-04-24 13:45:17 -0700672 private static final void checkManageUsersPermission(String message) {
Amith Yamasani258848d2012-08-10 17:06:33 -0700673 final int uid = Binder.getCallingUid();
Amith Yamasanibe465322014-04-24 13:45:17 -0700674 if (uid != Process.SYSTEM_UID && uid != 0
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400675 && ActivityManager.checkComponentPermission(
676 android.Manifest.permission.MANAGE_USERS,
Amith Yamasanibe465322014-04-24 13:45:17 -0700677 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
678 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
679 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400680 }
681
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700682 private static void checkSystemOrRoot(String message) {
683 final int uid = Binder.getCallingUid();
684 if (uid != Process.SYSTEM_UID && uid != 0) {
685 throw new SecurityException("Only system may call: " + message);
686 }
687 }
688
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700689 private void writeBitmapLocked(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700690 try {
691 File dir = new File(mUsersDir, Integer.toString(info.id));
692 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +0100693 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700694 if (!dir.exists()) {
695 dir.mkdir();
696 FileUtils.setPermissions(
697 dir.getPath(),
698 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
699 -1, -1);
700 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700701 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +0100702 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
703 && tmp.renameTo(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -0700704 info.iconPath = file.getAbsolutePath();
705 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700706 try {
707 os.close();
708 } catch (IOException ioe) {
709 // What the ... !
710 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100711 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700712 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700713 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700714 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700715 }
716
Amith Yamasani0b285492011-04-14 17:35:23 -0700717 /**
718 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
719 * cache it elsewhere.
720 * @return the array of user ids.
721 */
Dianne Hackborn1676c852012-09-10 14:52:30 -0700722 public int[] getUserIds() {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700723 synchronized (mPackagesLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700724 return mUserIds;
725 }
Amith Yamasani0b285492011-04-14 17:35:23 -0700726 }
727
Dianne Hackborn4428e172012-08-24 17:43:05 -0700728 int[] getUserIdsLPr() {
729 return mUserIds;
730 }
731
Amith Yamasani13593602012-03-22 16:16:17 -0700732 private void readUserListLocked() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700733 if (!mUserListFile.exists()) {
Amith Yamasani13593602012-03-22 16:16:17 -0700734 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700735 return;
736 }
737 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700738 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700739 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700740 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700741 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100742 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700743 int type;
744 while ((type = parser.next()) != XmlPullParser.START_TAG
745 && type != XmlPullParser.END_DOCUMENT) {
746 ;
747 }
748
749 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700750 Slog.e(LOG_TAG, "Unable to read user list");
Amith Yamasani13593602012-03-22 16:16:17 -0700751 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700752 return;
753 }
754
Amith Yamasani2a003292012-08-14 18:25:45 -0700755 mNextSerialNumber = -1;
756 if (parser.getName().equals(TAG_USERS)) {
757 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
758 if (lastSerialNumber != null) {
759 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
760 }
Amith Yamasani6f34b412012-10-22 18:19:27 -0700761 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
762 if (versionNumber != null) {
763 mUserVersion = Integer.parseInt(versionNumber);
764 }
Amith Yamasani2a003292012-08-14 18:25:45 -0700765 }
766
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700767 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530768 if (type == XmlPullParser.START_TAG) {
769 final String name = parser.getName();
770 if (name.equals(TAG_USER)) {
771 String id = parser.getAttributeValue(null, ATTR_ID);
772 UserInfo user = readUserLocked(Integer.parseInt(id));
Amith Yamasani6f34b412012-10-22 18:19:27 -0700773
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530774 if (user != null) {
775 mUsers.put(user.id, user);
776 if (mNextSerialNumber < 0 || mNextSerialNumber <= user.id) {
777 mNextSerialNumber = user.id + 1;
778 }
Amith Yamasani2a003292012-08-14 18:25:45 -0700779 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530780 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -0800781 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
782 && type != XmlPullParser.END_TAG) {
783 if (type == XmlPullParser.START_TAG) {
784 if (parser.getName().equals(TAG_RESTRICTIONS)) {
785 readRestrictionsLocked(parser, mGuestRestrictions);
786 }
787 break;
788 }
789 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700790 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700791 }
792 }
Amith Yamasani13593602012-03-22 16:16:17 -0700793 updateUserIdsLocked();
Amith Yamasani350962c2013-08-06 11:18:53 -0700794 upgradeIfNecessaryLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700795 } catch (IOException ioe) {
Amith Yamasani13593602012-03-22 16:16:17 -0700796 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700797 } catch (XmlPullParserException pe) {
Amith Yamasani13593602012-03-22 16:16:17 -0700798 fallbackToSingleUserLocked();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -0800799 } finally {
800 if (fis != null) {
801 try {
802 fis.close();
803 } catch (IOException e) {
804 }
805 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700806 }
807 }
808
Amith Yamasani6f34b412012-10-22 18:19:27 -0700809 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -0800810 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -0700811 */
Amith Yamasani350962c2013-08-06 11:18:53 -0700812 private void upgradeIfNecessaryLocked() {
Amith Yamasani6f34b412012-10-22 18:19:27 -0700813 int userVersion = mUserVersion;
814 if (userVersion < 1) {
815 // Assign a proper name for the owner, if not initialized correctly before
816 UserInfo user = mUsers.get(UserHandle.USER_OWNER);
817 if ("Primary".equals(user.name)) {
818 user.name = mContext.getResources().getString(com.android.internal.R.string.owner_name);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800819 scheduleWriteUserLocked(user);
Amith Yamasani6f34b412012-10-22 18:19:27 -0700820 }
821 userVersion = 1;
822 }
823
Amith Yamasanibc9625052012-11-15 14:39:18 -0800824 if (userVersion < 2) {
825 // Owner should be marked as initialized
826 UserInfo user = mUsers.get(UserHandle.USER_OWNER);
827 if ((user.flags & UserInfo.FLAG_INITIALIZED) == 0) {
828 user.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800829 scheduleWriteUserLocked(user);
Amith Yamasanibc9625052012-11-15 14:39:18 -0800830 }
831 userVersion = 2;
832 }
833
Amith Yamasani350962c2013-08-06 11:18:53 -0700834
Amith Yamasani5e486f52013-08-07 11:06:44 -0700835 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -0700836 userVersion = 4;
837 }
838
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700839 if (userVersion < 5) {
840 initDefaultGuestRestrictions();
841 userVersion = 5;
842 }
843
Amith Yamasani6f34b412012-10-22 18:19:27 -0700844 if (userVersion < USER_VERSION) {
845 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
846 + USER_VERSION);
847 } else {
848 mUserVersion = userVersion;
849 writeUserListLocked();
850 }
851 }
852
Amith Yamasani13593602012-03-22 16:16:17 -0700853 private void fallbackToSingleUserLocked() {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -0700854 int flags = UserInfo.FLAG_INITIALIZED;
855 // In split system user mode, the admin and primary flags are assigned to the first human
856 // user.
857 if (!UserManager.isSplitSystemUser()) {
858 flags |= UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY;
859 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700860 // Create the system user
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700861 UserInfo system = new UserInfo(UserHandle.USER_SYSTEM,
Amith Yamasani6f34b412012-10-22 18:19:27 -0700862 mContext.getResources().getString(com.android.internal.R.string.owner_name), null,
Xiaohui Chenb31e14a2015-07-13 16:04:55 -0700863 flags);
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700864 mUsers.put(system.id, system);
Amith Yamasani634cf312012-10-04 17:34:21 -0700865 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -0400866 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -0800867
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -0500868 Bundle restrictions = new Bundle();
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700869 mUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions);
Amith Yamasani67df64b2012-12-14 12:09:36 -0800870
Amith Yamasani13593602012-03-22 16:16:17 -0700871 updateUserIdsLocked();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700872 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700873
Amith Yamasani13593602012-03-22 16:16:17 -0700874 writeUserListLocked();
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700875 writeUserLocked(system);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700876 }
877
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800878 private void scheduleWriteUserLocked(UserInfo userInfo) {
879 if (!mHandler.hasMessages(WRITE_USER_MSG, userInfo)) {
880 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, userInfo);
881 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
882 }
883 }
884
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700885 /*
886 * Writes the user file in this format:
887 *
888 * <user flags="20039023" id="0">
889 * <name>Primary</name>
890 * </user>
891 */
Amith Yamasani13593602012-03-22 16:16:17 -0700892 private void writeUserLocked(UserInfo userInfo) {
Amith Yamasani742a6712011-05-04 14:49:28 -0700893 FileOutputStream fos = null;
Amith Yamasanifc95e702013-09-26 13:20:17 -0700894 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userInfo.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700895 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700896 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700897 final BufferedOutputStream bos = new BufferedOutputStream(fos);
898
899 // XmlSerializer serializer = XmlUtils.serializerInstance();
900 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100901 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700902 serializer.startDocument(null, true);
903 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
904
905 serializer.startTag(null, TAG_USER);
906 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
Amith Yamasani2a003292012-08-14 18:25:45 -0700907 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700908 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Amith Yamasani920ace02012-09-20 22:15:37 -0700909 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
910 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
911 Long.toString(userInfo.lastLoggedInTime));
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700912 if (userInfo.iconPath != null) {
913 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
914 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700915 if (userInfo.partial) {
916 serializer.attribute(null, ATTR_PARTIAL, "true");
917 }
Adam Lesinskieddeb492014-09-08 17:50:03 -0700918 if (userInfo.guestToRemove) {
919 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
920 }
Kenny Guy2a764942014-04-02 13:29:20 +0100921 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
922 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
923 Integer.toString(userInfo.profileGroupId));
Kenny Guya52dc3e2014-02-11 15:33:14 +0000924 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700925
926 serializer.startTag(null, TAG_NAME);
927 serializer.text(userInfo.name);
928 serializer.endTag(null, TAG_NAME);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800929 Bundle restrictions = mUserRestrictions.get(userInfo.id);
930 if (restrictions != null) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530931 writeRestrictionsLocked(serializer, restrictions);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800932 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700933 serializer.endTag(null, TAG_USER);
934
935 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -0700936 userFile.finishWrite(fos);
937 } catch (Exception ioe) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700938 Slog.e(LOG_TAG, "Error writing user info " + userInfo.id + "\n" + ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -0700939 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700940 }
941 }
942
943 /*
944 * Writes the user list file in this format:
945 *
Amith Yamasani2a003292012-08-14 18:25:45 -0700946 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700947 * <user id="0"></user>
948 * <user id="2"></user>
949 * </users>
950 */
Amith Yamasani13593602012-03-22 16:16:17 -0700951 private void writeUserListLocked() {
Amith Yamasani742a6712011-05-04 14:49:28 -0700952 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700953 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700954 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700955 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700956 final BufferedOutputStream bos = new BufferedOutputStream(fos);
957
958 // XmlSerializer serializer = XmlUtils.serializerInstance();
959 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100960 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700961 serializer.startDocument(null, true);
962 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
963
964 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -0700965 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -0700966 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700967
Adam Lesinskieddeb492014-09-08 17:50:03 -0700968 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530969 writeRestrictionsLocked(serializer, mGuestRestrictions);
970 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700971 for (int i = 0; i < mUsers.size(); i++) {
972 UserInfo user = mUsers.valueAt(i);
973 serializer.startTag(null, TAG_USER);
974 serializer.attribute(null, ATTR_ID, Integer.toString(user.id));
975 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700976 }
977
978 serializer.endTag(null, TAG_USERS);
979
980 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -0700981 userListFile.finishWrite(fos);
982 } catch (Exception e) {
983 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -0700984 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700985 }
986 }
987
Andres Moralesc5548c02015-08-05 10:23:12 -0700988 private void writeRestrictionsLocked(XmlSerializer serializer, Bundle restrictions)
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530989 throws IOException {
990 serializer.startTag(null, TAG_RESTRICTIONS);
991 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_WIFI);
992 writeBoolean(serializer, restrictions, UserManager.DISALLOW_MODIFY_ACCOUNTS);
993 writeBoolean(serializer, restrictions, UserManager.DISALLOW_INSTALL_APPS);
994 writeBoolean(serializer, restrictions, UserManager.DISALLOW_UNINSTALL_APPS);
995 writeBoolean(serializer, restrictions, UserManager.DISALLOW_SHARE_LOCATION);
996 writeBoolean(serializer, restrictions,
997 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
998 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_BLUETOOTH);
999 writeBoolean(serializer, restrictions, UserManager.DISALLOW_USB_FILE_TRANSFER);
1000 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_CREDENTIALS);
1001 writeBoolean(serializer, restrictions, UserManager.DISALLOW_REMOVE_USER);
1002 writeBoolean(serializer, restrictions, UserManager.DISALLOW_DEBUGGING_FEATURES);
1003 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_VPN);
1004 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_TETHERING);
Stuart Scott94b038b2015-04-20 14:07:45 -07001005 writeBoolean(serializer, restrictions, UserManager.DISALLOW_NETWORK_RESET);
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301006 writeBoolean(serializer, restrictions, UserManager.DISALLOW_FACTORY_RESET);
1007 writeBoolean(serializer, restrictions, UserManager.DISALLOW_ADD_USER);
1008 writeBoolean(serializer, restrictions, UserManager.ENSURE_VERIFY_APPS);
1009 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_CELL_BROADCASTS);
1010 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS);
1011 writeBoolean(serializer, restrictions, UserManager.DISALLOW_APPS_CONTROL);
1012 writeBoolean(serializer, restrictions, UserManager.DISALLOW_MOUNT_PHYSICAL_MEDIA);
1013 writeBoolean(serializer, restrictions, UserManager.DISALLOW_UNMUTE_MICROPHONE);
1014 writeBoolean(serializer, restrictions, UserManager.DISALLOW_ADJUST_VOLUME);
Amith Yamasani390989d2014-07-17 10:52:03 -07001015 writeBoolean(serializer, restrictions, UserManager.DISALLOW_OUTGOING_CALLS);
1016 writeBoolean(serializer, restrictions, UserManager.DISALLOW_SMS);
Jeff Sharkey2cc03e52015-03-20 11:24:04 -07001017 writeBoolean(serializer, restrictions, UserManager.DISALLOW_FUN);
Jason Monk1c7c3192014-06-26 12:52:18 -04001018 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CREATE_WINDOWS);
Amith Yamasani26af8292014-09-09 09:57:27 -07001019 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CROSS_PROFILE_COPY_PASTE);
1020 writeBoolean(serializer, restrictions, UserManager.DISALLOW_OUTGOING_BEAM);
Benjamin Franzf3ece362015-02-11 10:51:10 +00001021 writeBoolean(serializer, restrictions, UserManager.DISALLOW_WALLPAPER);
Benjamin Franzbff46ba2015-03-05 18:33:51 +00001022 writeBoolean(serializer, restrictions, UserManager.DISALLOW_SAFE_BOOT);
Nicolas Prevotf0029c12015-06-25 14:25:41 -07001023 writeBoolean(serializer, restrictions, UserManager.ALLOW_PARENT_PROFILE_APP_LINKING);
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301024 serializer.endTag(null, TAG_RESTRICTIONS);
1025 }
1026
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001027 private UserInfo readUserLocked(int id) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001028 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -07001029 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001030 String name = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001031 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -07001032 long creationTime = 0L;
1033 long lastLoggedInTime = 0L;
Kenny Guy2a764942014-04-02 13:29:20 +01001034 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001035 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001036 boolean guestToRemove = false;
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001037 Bundle restrictions = new Bundle();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001038
1039 FileInputStream fis = null;
1040 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001041 AtomicFile userFile =
Amith Yamasanifc95e702013-09-26 13:20:17 -07001042 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
Amith Yamasani2a003292012-08-14 18:25:45 -07001043 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001044 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001045 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001046 int type;
1047 while ((type = parser.next()) != XmlPullParser.START_TAG
1048 && type != XmlPullParser.END_DOCUMENT) {
1049 ;
1050 }
1051
1052 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001053 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001054 return null;
1055 }
1056
1057 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001058 int storedId = readIntAttribute(parser, ATTR_ID, -1);
1059 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001060 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001061 return null;
1062 }
Amith Yamasani920ace02012-09-20 22:15:37 -07001063 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
1064 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001065 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -07001066 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
1067 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Kenny Guy2a764942014-04-02 13:29:20 +01001068 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
1069 UserInfo.NO_PROFILE_GROUP_ID);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001070 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
1071 if ("true".equals(valueString)) {
1072 partial = true;
1073 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001074 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
1075 if ("true".equals(valueString)) {
1076 guestToRemove = true;
1077 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001078
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001079 int outerDepth = parser.getDepth();
1080 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1081 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1082 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1083 continue;
1084 }
1085 String tag = parser.getName();
1086 if (TAG_NAME.equals(tag)) {
1087 type = parser.next();
1088 if (type == XmlPullParser.TEXT) {
1089 name = parser.getText();
1090 }
1091 } else if (TAG_RESTRICTIONS.equals(tag)) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301092 readRestrictionsLocked(parser, restrictions);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001093 }
1094 }
1095 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001096
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001097 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -07001098 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -07001099 userInfo.creationTime = creationTime;
1100 userInfo.lastLoggedInTime = lastLoggedInTime;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001101 userInfo.partial = partial;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001102 userInfo.guestToRemove = guestToRemove;
Kenny Guy2a764942014-04-02 13:29:20 +01001103 userInfo.profileGroupId = profileGroupId;
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001104 mUserRestrictions.append(id, restrictions);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001105 return userInfo;
1106
1107 } catch (IOException ioe) {
1108 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001109 } finally {
1110 if (fis != null) {
1111 try {
1112 fis.close();
1113 } catch (IOException e) {
1114 }
1115 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001116 }
1117 return null;
1118 }
1119
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301120 private void readRestrictionsLocked(XmlPullParser parser, Bundle restrictions)
1121 throws IOException {
1122 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_WIFI);
1123 readBoolean(parser, restrictions, UserManager.DISALLOW_MODIFY_ACCOUNTS);
1124 readBoolean(parser, restrictions, UserManager.DISALLOW_INSTALL_APPS);
1125 readBoolean(parser, restrictions, UserManager.DISALLOW_UNINSTALL_APPS);
1126 readBoolean(parser, restrictions, UserManager.DISALLOW_SHARE_LOCATION);
1127 readBoolean(parser, restrictions,
1128 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
1129 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_BLUETOOTH);
1130 readBoolean(parser, restrictions, UserManager.DISALLOW_USB_FILE_TRANSFER);
1131 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_CREDENTIALS);
1132 readBoolean(parser, restrictions, UserManager.DISALLOW_REMOVE_USER);
1133 readBoolean(parser, restrictions, UserManager.DISALLOW_DEBUGGING_FEATURES);
1134 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_VPN);
1135 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_TETHERING);
Stuart Scott94b038b2015-04-20 14:07:45 -07001136 readBoolean(parser, restrictions, UserManager.DISALLOW_NETWORK_RESET);
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301137 readBoolean(parser, restrictions, UserManager.DISALLOW_FACTORY_RESET);
1138 readBoolean(parser, restrictions, UserManager.DISALLOW_ADD_USER);
1139 readBoolean(parser, restrictions, UserManager.ENSURE_VERIFY_APPS);
1140 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_CELL_BROADCASTS);
1141 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS);
1142 readBoolean(parser, restrictions, UserManager.DISALLOW_APPS_CONTROL);
1143 readBoolean(parser, restrictions,
1144 UserManager.DISALLOW_MOUNT_PHYSICAL_MEDIA);
1145 readBoolean(parser, restrictions, UserManager.DISALLOW_UNMUTE_MICROPHONE);
1146 readBoolean(parser, restrictions, UserManager.DISALLOW_ADJUST_VOLUME);
Amith Yamasani390989d2014-07-17 10:52:03 -07001147 readBoolean(parser, restrictions, UserManager.DISALLOW_OUTGOING_CALLS);
1148 readBoolean(parser, restrictions, UserManager.DISALLOW_SMS);
Jeff Sharkey2cc03e52015-03-20 11:24:04 -07001149 readBoolean(parser, restrictions, UserManager.DISALLOW_FUN);
Jason Monk1c7c3192014-06-26 12:52:18 -04001150 readBoolean(parser, restrictions, UserManager.DISALLOW_CREATE_WINDOWS);
Amith Yamasani26af8292014-09-09 09:57:27 -07001151 readBoolean(parser, restrictions, UserManager.DISALLOW_CROSS_PROFILE_COPY_PASTE);
1152 readBoolean(parser, restrictions, UserManager.DISALLOW_OUTGOING_BEAM);
Benjamin Franzf3ece362015-02-11 10:51:10 +00001153 readBoolean(parser, restrictions, UserManager.DISALLOW_WALLPAPER);
Benjamin Franzbff46ba2015-03-05 18:33:51 +00001154 readBoolean(parser, restrictions, UserManager.DISALLOW_SAFE_BOOT);
Nicolas Prevotf0029c12015-06-25 14:25:41 -07001155 readBoolean(parser, restrictions, UserManager.ALLOW_PARENT_PROFILE_APP_LINKING);
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301156 }
1157
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001158 private void readBoolean(XmlPullParser parser, Bundle restrictions,
1159 String restrictionKey) {
1160 String value = parser.getAttributeValue(null, restrictionKey);
Amith Yamasani71e6c692013-03-24 17:39:28 -07001161 if (value != null) {
1162 restrictions.putBoolean(restrictionKey, Boolean.parseBoolean(value));
1163 }
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001164 }
1165
1166 private void writeBoolean(XmlSerializer xml, Bundle restrictions, String restrictionKey)
1167 throws IOException {
1168 if (restrictions.containsKey(restrictionKey)) {
1169 xml.attribute(null, restrictionKey,
1170 Boolean.toString(restrictions.getBoolean(restrictionKey)));
1171 }
1172 }
1173
Amith Yamasani920ace02012-09-20 22:15:37 -07001174 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
1175 String valueString = parser.getAttributeValue(null, attr);
1176 if (valueString == null) return defaultValue;
1177 try {
1178 return Integer.parseInt(valueString);
1179 } catch (NumberFormatException nfe) {
1180 return defaultValue;
1181 }
1182 }
1183
1184 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
1185 String valueString = parser.getAttributeValue(null, attr);
1186 if (valueString == null) return defaultValue;
1187 try {
1188 return Long.parseLong(valueString);
1189 } catch (NumberFormatException nfe) {
1190 return defaultValue;
1191 }
1192 }
1193
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001194 private boolean isPackageInstalled(String pkg, int userId) {
1195 final ApplicationInfo info = mPm.getApplicationInfo(pkg,
1196 PackageManager.GET_UNINSTALLED_PACKAGES,
1197 userId);
1198 if (info == null || (info.flags&ApplicationInfo.FLAG_INSTALLED) == 0) {
1199 return false;
1200 }
1201 return true;
1202 }
1203
Amith Yamasanib82add22013-07-09 11:24:44 -07001204 /**
Kenny Guyd21b2182014-07-17 16:38:55 +01001205 * Removes all the restrictions files (res_<packagename>) for a given user.
Amith Yamasanib82add22013-07-09 11:24:44 -07001206 * Does not do any permissions checking.
1207 */
Kenny Guyd21b2182014-07-17 16:38:55 +01001208 private void cleanAppRestrictions(int userId) {
Amith Yamasanib82add22013-07-09 11:24:44 -07001209 synchronized (mPackagesLock) {
1210 File dir = Environment.getUserSystemDirectory(userId);
1211 String[] files = dir.list();
1212 if (files == null) return;
1213 for (String fileName : files) {
1214 if (fileName.startsWith(RESTRICTIONS_FILE_PREFIX)) {
1215 File resFile = new File(dir, fileName);
1216 if (resFile.exists()) {
Kenny Guyd21b2182014-07-17 16:38:55 +01001217 resFile.delete();
Amith Yamasanib82add22013-07-09 11:24:44 -07001218 }
1219 }
1220 }
1221 }
1222 }
1223
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001224 /**
1225 * Removes the app restrictions file for a specific package and user id, if it exists.
1226 */
1227 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
1228 synchronized (mPackagesLock) {
1229 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07001230 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001231 if (resFile.exists()) {
1232 resFile.delete();
1233 }
1234 }
1235 }
1236
Kenny Guya52dc3e2014-02-11 15:33:14 +00001237 @Override
Kenny Guy2a764942014-04-02 13:29:20 +01001238 public UserInfo createProfileForUser(String name, int flags, int userId) {
Kenny Guya52dc3e2014-02-11 15:33:14 +00001239 checkManageUsersPermission("Only the system can create users");
Kenny Guy2a764942014-04-02 13:29:20 +01001240 if (userId != UserHandle.USER_OWNER) {
1241 Slog.w(LOG_TAG, "Only user owner can have profiles");
Kenny Guya52dc3e2014-02-11 15:33:14 +00001242 return null;
1243 }
Kenny Guy2a764942014-04-02 13:29:20 +01001244 return createUserInternal(name, flags, userId);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001245 }
1246
Amith Yamasani258848d2012-08-10 17:06:33 -07001247 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07001248 public UserInfo createUser(String name, int flags) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001249 checkManageUsersPermission("Only the system can create users");
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001250 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001251 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001252
Jessica Hummelbe81c802014-04-22 15:49:22 +01001253 private UserInfo createUserInternal(String name, int flags, int parentId) {
Julia Reynolds75175022014-06-26 16:35:00 -04001254 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1255 UserManager.DISALLOW_ADD_USER, false)) {
1256 Log.w(LOG_TAG, "Cannot add user. DISALLOW_ADD_USER is enabled.");
1257 return null;
1258 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001259 if (ActivityManager.isLowRamDeviceStatic()) {
1260 return null;
1261 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07001262 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001263 final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001264 final long ident = Binder.clearCallingIdentity();
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001265 UserInfo userInfo = null;
Amith Yamasanibb054c92015-07-09 14:16:27 -07001266 final int userId;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001267 try {
1268 synchronized (mInstallLock) {
1269 synchronized (mPackagesLock) {
Jessica Hummelbe81c802014-04-22 15:49:22 +01001270 UserInfo parent = null;
1271 if (parentId != UserHandle.USER_NULL) {
1272 parent = getUserInfoLocked(parentId);
1273 if (parent == null) return null;
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001274 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001275 if (isManagedProfile && !canAddMoreManagedProfiles()) {
1276 return null;
1277 }
1278 if (!isGuest && !isManagedProfile && isUserLimitReachedLocked()) {
1279 // If we're not adding a guest user or a managed profile and the limit has
1280 // been reached, cannot add a user.
Amith Yamasani95ab7842014-08-11 17:09:26 -07001281 return null;
1282 }
1283 // If we're adding a guest and there already exists one, bail.
Adam Lesinskieddeb492014-09-08 17:50:03 -07001284 if (isGuest && findCurrentGuestUserLocked() != null) {
Amith Yamasani95ab7842014-08-11 17:09:26 -07001285 return null;
1286 }
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001287 // In split system user mode, we assign the first human user the primary flag.
Xiaohui Chen203243a2015-07-16 11:55:47 -07001288 // And if there is no device owner, we also assign the admin flag to primary
1289 // user.
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001290 if (UserManager.isSplitSystemUser()
Xiaohui Chen203243a2015-07-16 11:55:47 -07001291 && !isGuest && !isManagedProfile && getPrimaryUser() == null) {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001292 flags |= UserInfo.FLAG_PRIMARY;
Xiaohui Chen203243a2015-07-16 11:55:47 -07001293 DevicePolicyManager devicePolicyManager = (DevicePolicyManager)
1294 mContext.getSystemService(Context.DEVICE_POLICY_SERVICE);
1295 if (devicePolicyManager == null
1296 || devicePolicyManager.getDeviceOwner() == null) {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001297 flags |= UserInfo.FLAG_ADMIN;
1298 }
1299 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07001300 userId = getNextAvailableIdLocked();
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001301 userInfo = new UserInfo(userId, name, null, flags);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001302 userInfo.serialNumber = mNextSerialNumber++;
Amith Yamasani920ace02012-09-20 22:15:37 -07001303 long now = System.currentTimeMillis();
1304 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001305 userInfo.partial = true;
Amith Yamasani16389312012-10-17 21:20:14 -07001306 Environment.getUserSystemDirectory(userInfo.id).mkdirs();
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001307 mUsers.put(userId, userInfo);
1308 writeUserListLocked();
Jessica Hummelbe81c802014-04-22 15:49:22 +01001309 if (parent != null) {
1310 if (parent.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
1311 parent.profileGroupId = parent.id;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001312 scheduleWriteUserLocked(parent);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001313 }
Jessica Hummelbe81c802014-04-22 15:49:22 +01001314 userInfo.profileGroupId = parent.profileGroupId;
Kenny Guya52dc3e2014-02-11 15:33:14 +00001315 }
Jeff Sharkey6dce4962015-07-03 18:08:41 -07001316 final StorageManager storage = mContext.getSystemService(StorageManager.class);
1317 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
1318 final String volumeUuid = vol.getFsUuid();
1319 try {
1320 final File userDir = Environment.getDataUserDirectory(volumeUuid,
1321 userId);
Jeff Sharkey3bb8c852015-07-06 16:44:23 -07001322 prepareUserDirectory(mContext, volumeUuid, userId);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07001323 enforceSerialNumber(userDir, userInfo.serialNumber);
1324 } catch (IOException e) {
1325 Log.wtf(LOG_TAG, "Failed to create user directory on " + volumeUuid, e);
1326 }
1327 }
1328 mPm.createNewUserLILPw(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001329 userInfo.partial = false;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001330 scheduleWriteUserLocked(userInfo);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001331 updateUserIdsLocked();
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001332 Bundle restrictions = new Bundle();
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001333 mUserRestrictions.append(userId, restrictions);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001334 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07001335 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07001336 mPm.newUserCreated(userId);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001337 if (userInfo != null) {
1338 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
1339 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userInfo.id);
1340 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
1341 android.Manifest.permission.MANAGE_USERS);
1342 }
1343 } finally {
1344 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07001345 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001346 return userInfo;
1347 }
1348
Amith Yamasani95ab7842014-08-11 17:09:26 -07001349 private int numberOfUsersOfTypeLocked(int flags, boolean excludeDying) {
1350 int count = 0;
1351 for (int i = mUsers.size() - 1; i >= 0; i--) {
1352 UserInfo user = mUsers.valueAt(i);
1353 if (!excludeDying || !mRemovingUserIds.get(user.id)) {
1354 if ((user.flags & flags) != 0) {
1355 count++;
1356 }
1357 }
1358 }
1359 return count;
1360 }
1361
Amith Yamasani0b285492011-04-14 17:35:23 -07001362 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07001363 * Find the current guest user. If the Guest user is partial,
1364 * then do not include it in the results as it is about to die.
1365 * This is different than {@link #numberOfUsersOfTypeLocked(int, boolean)} due to
1366 * the special handling of Guests being removed.
1367 */
1368 private UserInfo findCurrentGuestUserLocked() {
1369 final int size = mUsers.size();
1370 for (int i = 0; i < size; i++) {
1371 final UserInfo user = mUsers.valueAt(i);
1372 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
1373 return user;
1374 }
1375 }
1376 return null;
1377 }
1378
1379 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07001380 * Mark this guest user for deletion to allow us to create another guest
1381 * and switch to that user before actually removing this guest.
1382 * @param userHandle the userid of the current guest
1383 * @return whether the user could be marked for deletion
1384 */
1385 public boolean markGuestForDeletion(int userHandle) {
1386 checkManageUsersPermission("Only the system can remove users");
1387 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1388 UserManager.DISALLOW_REMOVE_USER, false)) {
1389 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1390 return false;
1391 }
1392
1393 long ident = Binder.clearCallingIdentity();
1394 try {
1395 final UserInfo user;
1396 synchronized (mPackagesLock) {
1397 user = mUsers.get(userHandle);
1398 if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
1399 return false;
1400 }
1401 if (!user.isGuest()) {
1402 return false;
1403 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001404 // We set this to a guest user that is to be removed. This is a temporary state
1405 // where we are allowed to add new Guest users, even if this one is still not
1406 // removed. This user will still show up in getUserInfo() calls.
1407 // If we don't get around to removing this Guest user, it will be purged on next
1408 // startup.
1409 user.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07001410 // Mark it as disabled, so that it isn't returned any more when
1411 // profiles are queried.
1412 user.flags |= UserInfo.FLAG_DISABLED;
Amith Yamasani1df14732014-08-29 21:37:27 -07001413 writeUserLocked(user);
1414 }
1415 } finally {
1416 Binder.restoreCallingIdentity(ident);
1417 }
1418 return true;
1419 }
1420
1421 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07001422 * Removes a user and all data directories created for that user. This method should be called
1423 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001424 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07001425 */
Amith Yamasani258848d2012-08-10 17:06:33 -07001426 public boolean removeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001427 checkManageUsersPermission("Only the system can remove users");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04001428 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1429 UserManager.DISALLOW_REMOVE_USER, false)) {
1430 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1431 return false;
1432 }
1433
Kenny Guyee58b4f2014-05-23 15:19:53 +01001434 long ident = Binder.clearCallingIdentity();
1435 try {
1436 final UserInfo user;
1437 synchronized (mPackagesLock) {
1438 user = mUsers.get(userHandle);
Kenny Guy17c9d692014-06-13 13:51:42 +01001439 if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01001440 return false;
1441 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08001442
1443 // We remember deleted user IDs to prevent them from being
1444 // reused during the current boot; they can still be reused
1445 // after a reboot.
Kenny Guyee58b4f2014-05-23 15:19:53 +01001446 mRemovingUserIds.put(userHandle, true);
Jeff Sharkey6eb09392014-11-14 15:57:59 -08001447
Kenny Guyee58b4f2014-05-23 15:19:53 +01001448 try {
1449 mAppOpsService.removeUser(userHandle);
1450 } catch (RemoteException e) {
1451 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
1452 }
1453 // Set this to a partially created user, so that the user will be purged
1454 // on next startup, in case the runtime stops now before stopping and
1455 // removing the user completely.
1456 user.partial = true;
1457 // Mark it as disabled, so that it isn't returned any more when
1458 // profiles are queried.
1459 user.flags |= UserInfo.FLAG_DISABLED;
1460 writeUserLocked(user);
1461 }
1462
1463 if (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
1464 && user.isManagedProfile()) {
1465 // Send broadcast to notify system that the user removed was a
1466 // managed user.
1467 sendProfileRemovedBroadcast(user.profileGroupId, user.id);
1468 }
1469
1470 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
1471 int res;
1472 try {
1473 res = ActivityManagerNative.getDefault().stopUser(userHandle,
1474 new IStopUserCallback.Stub() {
1475 @Override
1476 public void userStopped(int userId) {
1477 finishRemoveUser(userId);
1478 }
1479 @Override
1480 public void userStopAborted(int userId) {
1481 }
1482 });
1483 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001484 return false;
1485 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01001486 return res == ActivityManager.USER_OP_SUCCESS;
1487 } finally {
1488 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001489 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001490 }
1491
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001492 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07001493 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001494 // Let other services shutdown any activity and clean up their state before completely
1495 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001496 long ident = Binder.clearCallingIdentity();
1497 try {
1498 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
1499 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001500 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
1501 android.Manifest.permission.MANAGE_USERS,
1502
1503 new BroadcastReceiver() {
1504 @Override
1505 public void onReceive(Context context, Intent intent) {
1506 if (DBG) {
1507 Slog.i(LOG_TAG,
1508 "USER_REMOVED broadcast sent, cleaning up user data "
1509 + userHandle);
1510 }
1511 new Thread() {
1512 public void run() {
1513 synchronized (mInstallLock) {
1514 synchronized (mPackagesLock) {
1515 removeUserStateLocked(userHandle);
1516 }
1517 }
1518 }
1519 }.start();
1520 }
1521 },
1522
1523 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001524 } finally {
1525 Binder.restoreCallingIdentity(ident);
1526 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001527 }
1528
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001529 private void removeUserStateLocked(final int userHandle) {
Paul Crowley85e4e812015-05-19 12:42:00 +01001530 mContext.getSystemService(StorageManager.class)
1531 .deleteUserKey(userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001532 // Cleanup package manager settings
Amith Yamasanidda003f2014-08-28 18:06:51 -07001533 mPm.cleanUpUserLILPw(this, userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001534
1535 // Remove this user from the list
1536 mUsers.remove(userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001537 // Remove user file
Amith Yamasanifc95e702013-09-26 13:20:17 -07001538 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001539 userFile.delete();
1540 // Update the user list
1541 writeUserListLocked();
1542 updateUserIdsLocked();
1543 removeDirectoryRecursive(Environment.getUserSystemDirectory(userHandle));
1544 }
1545
Amith Yamasani61f57372012-08-31 12:12:28 -07001546 private void removeDirectoryRecursive(File parent) {
1547 if (parent.isDirectory()) {
1548 String[] files = parent.list();
1549 for (String filename : files) {
1550 File child = new File(parent, filename);
1551 removeDirectoryRecursive(child);
1552 }
1553 }
1554 parent.delete();
1555 }
1556
Kenny Guyf8d3a232014-05-15 16:09:52 +01001557 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01001558 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01001559 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
1560 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01001561 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
1562 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01001563 }
1564
Amith Yamasani2a003292012-08-14 18:25:45 -07001565 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001566 public Bundle getApplicationRestrictions(String packageName) {
1567 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
1568 }
1569
1570 @Override
1571 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001572 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07001573 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001574 checkManageUsersPermission("Only system can get restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001575 }
1576 synchronized (mPackagesLock) {
1577 // Read the restrictions from XML
1578 return readApplicationRestrictionsLocked(packageName, userId);
1579 }
1580 }
1581
1582 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001583 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001584 int userId) {
1585 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07001586 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001587 checkManageUsersPermission("Only system can set restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001588 }
1589 synchronized (mPackagesLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01001590 if (restrictions == null || restrictions.isEmpty()) {
1591 cleanAppRestrictionsForPackage(packageName, userId);
1592 } else {
1593 // Write the restrictions to XML
1594 writeApplicationRestrictionsLocked(packageName, restrictions, userId);
1595 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001596 }
Robin Lee66e5d962014-04-09 16:44:21 +01001597
Kenny Guyd21b2182014-07-17 16:38:55 +01001598 if (isPackageInstalled(packageName, userId)) {
1599 // Notify package of changes via an intent - only sent to explicitly registered receivers.
1600 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
1601 changeIntent.setPackage(packageName);
1602 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
1603 mContext.sendBroadcastAsUser(changeIntent, new UserHandle(userId));
1604 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001605 }
1606
Amith Yamasani655d0e22013-06-12 14:19:10 -07001607 @Override
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001608 public void removeRestrictions() {
Amith Yamasanibe465322014-04-24 13:45:17 -07001609 checkManageUsersPermission("Only system can remove restrictions");
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001610 final int userHandle = UserHandle.getCallingUserId();
Amith Yamasani5e486f52013-08-07 11:06:44 -07001611 removeRestrictionsForUser(userHandle, true);
Amith Yamasani350962c2013-08-06 11:18:53 -07001612 }
1613
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001614 private void removeRestrictionsForUser(final int userHandle, boolean unhideApps) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001615 synchronized (mPackagesLock) {
1616 // Remove all user restrictions
1617 setUserRestrictions(new Bundle(), userHandle);
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001618 // Remove any app restrictions
Kenny Guyd21b2182014-07-17 16:38:55 +01001619 cleanAppRestrictions(userHandle);
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001620 }
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001621 if (unhideApps) {
1622 unhideAllInstalledAppsForUser(userHandle);
Amith Yamasani5e486f52013-08-07 11:06:44 -07001623 }
1624 }
1625
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001626 private void unhideAllInstalledAppsForUser(final int userHandle) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001627 mHandler.post(new Runnable() {
1628 @Override
1629 public void run() {
1630 List<ApplicationInfo> apps =
1631 mPm.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES,
1632 userHandle).getList();
1633 final long ident = Binder.clearCallingIdentity();
1634 try {
1635 for (ApplicationInfo appInfo : apps) {
1636 if ((appInfo.flags & ApplicationInfo.FLAG_INSTALLED) != 0
Alex Klyubinb9f8a522015-02-03 11:12:59 -08001637 && (appInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HIDDEN)
1638 != 0) {
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001639 mPm.setApplicationHiddenSettingAsUser(appInfo.packageName, false,
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001640 userHandle);
1641 }
1642 }
1643 } finally {
1644 Binder.restoreCallingIdentity(ident);
1645 }
1646 }
1647 });
1648 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001649 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07001650 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001651 try {
1652 return mContext.getPackageManager().getApplicationInfo(packageName,
1653 PackageManager.GET_UNINSTALLED_PACKAGES).uid;
1654 } catch (NameNotFoundException nnfe) {
1655 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07001656 } finally {
1657 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001658 }
1659 }
1660
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001661 private Bundle readApplicationRestrictionsLocked(String packageName,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001662 int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001663 AtomicFile restrictionsFile =
1664 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
1665 packageToRestrictionsFileName(packageName)));
1666 return readApplicationRestrictionsLocked(restrictionsFile);
1667 }
1668
1669 @VisibleForTesting
1670 static Bundle readApplicationRestrictionsLocked(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001671 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001672 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07001673 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07001674 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07001675 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001676
1677 FileInputStream fis = null;
1678 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001679 fis = restrictionsFile.openRead();
1680 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001681 parser.setInput(fis, StandardCharsets.UTF_8.name());
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001682 XmlUtils.nextElement(parser);
1683 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001684 Slog.e(LOG_TAG, "Unable to read restrictions file "
1685 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001686 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001687 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001688 while (parser.next() != XmlPullParser.END_DOCUMENT) {
1689 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001690 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001691 } catch (IOException|XmlPullParserException e) {
1692 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001693 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001694 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001695 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001696 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001697 }
1698
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001699 private static void readEntry(Bundle restrictions, ArrayList<String> values,
1700 XmlPullParser parser) throws XmlPullParserException, IOException {
1701 int type = parser.getEventType();
1702 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
1703 String key = parser.getAttributeValue(null, ATTR_KEY);
1704 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
1705 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
1706 if (multiple != null) {
1707 values.clear();
1708 int count = Integer.parseInt(multiple);
1709 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1710 if (type == XmlPullParser.START_TAG
1711 && parser.getName().equals(TAG_VALUE)) {
1712 values.add(parser.nextText().trim());
1713 count--;
1714 }
1715 }
1716 String [] valueStrings = new String[values.size()];
1717 values.toArray(valueStrings);
1718 restrictions.putStringArray(key, valueStrings);
1719 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
1720 restrictions.putBundle(key, readBundleEntry(parser, values));
1721 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
1722 final int outerDepth = parser.getDepth();
1723 ArrayList<Bundle> bundleList = new ArrayList<>();
1724 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
1725 Bundle childBundle = readBundleEntry(parser, values);
1726 bundleList.add(childBundle);
1727 }
1728 restrictions.putParcelableArray(key,
1729 bundleList.toArray(new Bundle[bundleList.size()]));
1730 } else {
1731 String value = parser.nextText().trim();
1732 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
1733 restrictions.putBoolean(key, Boolean.parseBoolean(value));
1734 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
1735 restrictions.putInt(key, Integer.parseInt(value));
1736 } else {
1737 restrictions.putString(key, value);
1738 }
1739 }
1740 }
1741 }
1742
1743 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
1744 throws IOException, XmlPullParserException {
1745 Bundle childBundle = new Bundle();
1746 final int outerDepth = parser.getDepth();
1747 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
1748 readEntry(childBundle, values, parser);
1749 }
1750 return childBundle;
1751 }
1752
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001753 private void writeApplicationRestrictionsLocked(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001754 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001755 AtomicFile restrictionsFile = new AtomicFile(
1756 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07001757 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001758 writeApplicationRestrictionsLocked(restrictions, restrictionsFile);
1759 }
1760
1761 @VisibleForTesting
1762 static void writeApplicationRestrictionsLocked(Bundle restrictions,
1763 AtomicFile restrictionsFile) {
1764 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001765 try {
1766 fos = restrictionsFile.startWrite();
1767 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1768
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001769 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001770 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001771 serializer.startDocument(null, true);
1772 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1773
1774 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001775 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001776 serializer.endTag(null, TAG_RESTRICTIONS);
1777
1778 serializer.endDocument();
1779 restrictionsFile.finishWrite(fos);
1780 } catch (Exception e) {
1781 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001782 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
1783 }
1784 }
1785
1786 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
1787 throws IOException {
1788 for (String key : restrictions.keySet()) {
1789 Object value = restrictions.get(key);
1790 serializer.startTag(null, TAG_ENTRY);
1791 serializer.attribute(null, ATTR_KEY, key);
1792
1793 if (value instanceof Boolean) {
1794 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
1795 serializer.text(value.toString());
1796 } else if (value instanceof Integer) {
1797 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
1798 serializer.text(value.toString());
1799 } else if (value == null || value instanceof String) {
1800 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
1801 serializer.text(value != null ? (String) value : "");
1802 } else if (value instanceof Bundle) {
1803 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
1804 writeBundle((Bundle) value, serializer);
1805 } else if (value instanceof Parcelable[]) {
1806 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
1807 Parcelable[] array = (Parcelable[]) value;
1808 for (Parcelable parcelable : array) {
1809 if (!(parcelable instanceof Bundle)) {
1810 throw new IllegalArgumentException("bundle-array can only hold Bundles");
1811 }
1812 serializer.startTag(null, TAG_ENTRY);
1813 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
1814 writeBundle((Bundle) parcelable, serializer);
1815 serializer.endTag(null, TAG_ENTRY);
1816 }
1817 } else {
1818 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
1819 String[] values = (String[]) value;
1820 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
1821 for (String choice : values) {
1822 serializer.startTag(null, TAG_VALUE);
1823 serializer.text(choice != null ? choice : "");
1824 serializer.endTag(null, TAG_VALUE);
1825 }
1826 }
1827 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001828 }
1829 }
1830
1831 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07001832 public int getUserSerialNumber(int userHandle) {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001833 synchronized (mPackagesLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001834 if (!exists(userHandle)) return -1;
Amith Yamasani195263742012-08-21 15:40:12 -07001835 return getUserInfoLocked(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07001836 }
1837 }
1838
1839 @Override
1840 public int getUserHandle(int userSerialNumber) {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001841 synchronized (mPackagesLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001842 for (int userId : mUserIds) {
Kenny Guy945f8832015-02-10 15:17:26 +00001843 UserInfo info = getUserInfoLocked(userId);
1844 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07001845 }
1846 // Not found
1847 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07001848 }
1849 }
1850
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07001851 @Override
1852 public long getUserCreationTime(int userHandle) {
1853 int callingUserId = UserHandle.getCallingUserId();
1854 UserInfo userInfo = null;
1855 synchronized (mPackagesLock) {
1856 if (callingUserId == userHandle) {
1857 userInfo = getUserInfoLocked(userHandle);
1858 } else {
1859 UserInfo parent = getProfileParentLocked(userHandle);
1860 if (parent != null && parent.id == callingUserId) {
1861 userInfo = getUserInfoLocked(userHandle);
1862 }
1863 }
1864 }
1865 if (userInfo == null) {
1866 throw new SecurityException("userHandle can only be the calling user or a managed "
1867 + "profile associated with this user");
1868 }
1869 return userInfo.creationTime;
1870 }
1871
Amith Yamasani0b285492011-04-14 17:35:23 -07001872 /**
1873 * Caches the list of user ids in an array, adjusting the array size when necessary.
1874 */
Amith Yamasani13593602012-03-22 16:16:17 -07001875 private void updateUserIdsLocked() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001876 int num = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -07001877 for (int i = 0; i < mUsers.size(); i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001878 if (!mUsers.valueAt(i).partial) {
1879 num++;
1880 }
1881 }
Amith Yamasani16389312012-10-17 21:20:14 -07001882 final int[] newUsers = new int[num];
1883 int n = 0;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001884 for (int i = 0; i < mUsers.size(); i++) {
1885 if (!mUsers.valueAt(i).partial) {
Amith Yamasani16389312012-10-17 21:20:14 -07001886 newUsers[n++] = mUsers.keyAt(i);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001887 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001888 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001889 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07001890 }
1891
1892 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001893 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasani920ace02012-09-20 22:15:37 -07001894 * @param userId the user that was just foregrounded
1895 */
Amith Yamasani06bf8242015-05-08 16:36:21 -07001896 public void onUserForeground(int userId) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001897 synchronized (mPackagesLock) {
1898 UserInfo user = mUsers.get(userId);
1899 long now = System.currentTimeMillis();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001900 if (user == null || user.partial) {
1901 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
1902 return;
1903 }
1904 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001905 user.lastLoggedInTime = now;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001906 scheduleWriteUserLocked(user);
Amith Yamasani920ace02012-09-20 22:15:37 -07001907 }
1908 }
1909 }
1910
1911 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07001912 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani742a6712011-05-04 14:49:28 -07001913 * TODO: May not be a good idea to recycle ids, in case it results in confusion
1914 * for data and battery stats collection, or unexpected cross-talk.
Amith Yamasani0b285492011-04-14 17:35:23 -07001915 * @return
1916 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001917 private int getNextAvailableIdLocked() {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001918 synchronized (mPackagesLock) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001919 int i = MIN_USER_ID;
Amith Yamasani195263742012-08-21 15:40:12 -07001920 while (i < Integer.MAX_VALUE) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001921 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
Amith Yamasani195263742012-08-21 15:40:12 -07001922 break;
1923 }
1924 i++;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001925 }
Amith Yamasani195263742012-08-21 15:40:12 -07001926 return i;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001927 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001928 }
Amith Yamasani920ace02012-09-20 22:15:37 -07001929
Amith Yamasanifc95e702013-09-26 13:20:17 -07001930 private String packageToRestrictionsFileName(String packageName) {
1931 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
1932 }
1933
Jeff Sharkey6dce4962015-07-03 18:08:41 -07001934 /**
1935 * Create new {@code /data/user/[id]} directory and sets default
1936 * permissions.
1937 */
Jeff Sharkey3bb8c852015-07-06 16:44:23 -07001938 public static void prepareUserDirectory(Context context, String volumeUuid, int userId) {
1939 final StorageManager storage = context.getSystemService(StorageManager.class);
1940 final File userDir = Environment.getDataUserDirectory(volumeUuid, userId);
1941 storage.createNewUserDir(userId, userDir);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07001942 }
1943
1944 /**
1945 * Enforce that serial number stored in user directory inode matches the
1946 * given expected value. Gracefully sets the serial number if currently
1947 * undefined.
1948 *
1949 * @throws IOException when problem extracting serial number, or serial
1950 * number is mismatched.
1951 */
1952 public static void enforceSerialNumber(File file, int serialNumber) throws IOException {
1953 final int foundSerial = getSerialNumber(file);
1954 Slog.v(LOG_TAG, "Found " + file + " with serial number " + foundSerial);
1955
1956 if (foundSerial == -1) {
1957 Slog.d(LOG_TAG, "Serial number missing on " + file + "; assuming current is valid");
1958 try {
1959 setSerialNumber(file, serialNumber);
1960 } catch (IOException e) {
1961 Slog.w(LOG_TAG, "Failed to set serial number on " + file, e);
1962 }
1963
1964 } else if (foundSerial != serialNumber) {
1965 throw new IOException("Found serial number " + foundSerial
1966 + " doesn't match expected " + serialNumber);
1967 }
1968 }
1969
1970 /**
1971 * Set serial number stored in user directory inode.
1972 *
1973 * @throws IOException if serial number was already set
1974 */
1975 private static void setSerialNumber(File file, int serialNumber)
1976 throws IOException {
1977 try {
1978 final byte[] buf = Integer.toString(serialNumber).getBytes(StandardCharsets.UTF_8);
1979 Os.setxattr(file.getAbsolutePath(), XATTR_SERIAL, buf, OsConstants.XATTR_CREATE);
1980 } catch (ErrnoException e) {
1981 throw e.rethrowAsIOException();
1982 }
1983 }
1984
1985 /**
1986 * Return serial number stored in user directory inode.
1987 *
1988 * @return parsed serial number, or -1 if not set
1989 */
1990 private static int getSerialNumber(File file) throws IOException {
1991 try {
1992 final byte[] buf = new byte[256];
1993 final int len = Os.getxattr(file.getAbsolutePath(), XATTR_SERIAL, buf);
1994 final String serial = new String(buf, 0, len);
1995 try {
1996 return Integer.parseInt(serial);
1997 } catch (NumberFormatException e) {
1998 throw new IOException("Bad serial number: " + serial);
1999 }
2000 } catch (ErrnoException e) {
2001 if (e.errno == OsConstants.ENODATA) {
2002 return -1;
2003 } else {
2004 throw e.rethrowAsIOException();
2005 }
2006 }
2007 }
2008
Amith Yamasani920ace02012-09-20 22:15:37 -07002009 @Override
2010 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2011 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2012 != PackageManager.PERMISSION_GRANTED) {
2013 pw.println("Permission Denial: can't dump UserManager from from pid="
2014 + Binder.getCallingPid()
2015 + ", uid=" + Binder.getCallingUid()
2016 + " without permission "
2017 + android.Manifest.permission.DUMP);
2018 return;
2019 }
2020
2021 long now = System.currentTimeMillis();
2022 StringBuilder sb = new StringBuilder();
2023 synchronized (mPackagesLock) {
2024 pw.println("Users:");
2025 for (int i = 0; i < mUsers.size(); i++) {
2026 UserInfo user = mUsers.valueAt(i);
2027 if (user == null) continue;
Amith Yamasani634cf312012-10-04 17:34:21 -07002028 pw.print(" "); pw.print(user); pw.print(" serialNo="); pw.print(user.serialNumber);
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002029 if (mRemovingUserIds.get(mUsers.keyAt(i))) pw.print(" <removing> ");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002030 if (user.partial) pw.print(" <partial>");
2031 pw.println();
Amith Yamasani920ace02012-09-20 22:15:37 -07002032 pw.print(" Created: ");
2033 if (user.creationTime == 0) {
2034 pw.println("<unknown>");
2035 } else {
2036 sb.setLength(0);
2037 TimeUtils.formatDuration(now - user.creationTime, sb);
2038 sb.append(" ago");
2039 pw.println(sb);
2040 }
2041 pw.print(" Last logged in: ");
2042 if (user.lastLoggedInTime == 0) {
2043 pw.println("<unknown>");
2044 } else {
2045 sb.setLength(0);
2046 TimeUtils.formatDuration(now - user.lastLoggedInTime, sb);
2047 sb.append(" ago");
2048 pw.println(sb);
2049 }
2050 }
2051 }
2052 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002053
2054 final class MainHandler extends Handler {
2055
2056 @Override
2057 public void handleMessage(Message msg) {
2058 switch (msg.what) {
2059 case WRITE_USER_MSG:
2060 removeMessages(WRITE_USER_MSG, msg.obj);
2061 synchronized (mPackagesLock) {
2062 int userId = ((UserInfo) msg.obj).id;
2063 UserInfo userInfo = mUsers.get(userId);
2064 if (userInfo != null) {
2065 writeUserLocked(userInfo);
2066 }
2067 }
2068 }
2069 }
2070 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07002071
2072 /**
2073 * @param userId
2074 * @return whether the user has been initialized yet
2075 */
2076 boolean isInitialized(int userId) {
2077 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
2078 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002079}