blob: 0f33544b5925ab347f21ea55ca57668a12a4ce76 [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
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070019import android.app.Activity;
Amith Yamasani2a003292012-08-14 18:25:45 -070020import android.app.ActivityManager;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070021import android.app.ActivityManagerNative;
22import android.app.IStopUserCallback;
Xiaohui Chen203243a2015-07-16 11:55:47 -070023import android.app.admin.DevicePolicyManager;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070024import android.content.BroadcastReceiver;
Amith Yamasani258848d2012-08-10 17:06:33 -070025import android.content.Context;
26import android.content.Intent;
Amith Yamasani1a7472e2013-07-02 11:17:30 -070027import android.content.pm.ApplicationInfo;
Amith Yamasani0b285492011-04-14 17:35:23 -070028import android.content.pm.PackageManager;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -080029import android.content.pm.PackageManager.NameNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070030import android.content.pm.UserInfo;
Amith Yamasanie928d7d2012-09-17 21:46:51 -070031import android.graphics.Bitmap;
Amith Yamasani258848d2012-08-10 17:06:33 -070032import android.os.Binder;
Amith Yamasanie4cf7342012-12-17 11:12:09 -080033import android.os.Bundle;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070034import android.os.Environment;
35import android.os.FileUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080036import android.os.Handler;
Amith Yamasani258848d2012-08-10 17:06:33 -070037import android.os.IUserManager;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -080038import android.os.Message;
Adrian Roos1bdff912015-02-17 15:51:35 +010039import android.os.ParcelFileDescriptor;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070040import android.os.Parcelable;
Amith Yamasani258848d2012-08-10 17:06:33 -070041import android.os.Process;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070042import android.os.RemoteException;
Jason Monk62062992014-05-06 09:55:28 -040043import android.os.ServiceManager;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070044import android.os.UserHandle;
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070045import android.os.UserManager;
Paul Crowley85e4e812015-05-19 12:42:00 +010046import android.os.storage.StorageManager;
Jeff Sharkey6dce4962015-07-03 18:08:41 -070047import android.os.storage.VolumeInfo;
48import android.system.ErrnoException;
49import android.system.Os;
50import android.system.OsConstants;
Amith Yamasani2a003292012-08-14 18:25:45 -070051import android.util.AtomicFile;
Amith Yamasani655d0e22013-06-12 14:19:10 -070052import android.util.Log;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070053import android.util.Slog;
54import android.util.SparseArray;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080055import android.util.SparseBooleanArray;
Amith Yamasani920ace02012-09-20 22:15:37 -070056import android.util.TimeUtils;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070057import android.util.Xml;
58
Fyodor Kupolovb5013302015-04-17 17:59:14 -070059import com.google.android.collect.Sets;
60
Fyodor Kupolov262f9952015-03-23 18:55:11 -070061import com.android.internal.annotations.VisibleForTesting;
Jason Monk62062992014-05-06 09:55:28 -040062import com.android.internal.app.IAppOpsService;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080063import com.android.internal.util.ArrayUtils;
64import com.android.internal.util.FastXmlSerializer;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070065import com.android.internal.util.XmlUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080066
67import org.xmlpull.v1.XmlPullParser;
68import org.xmlpull.v1.XmlPullParserException;
69import org.xmlpull.v1.XmlSerializer;
70
Amith Yamasani4b2e9342011-03-31 12:38:53 -070071import java.io.BufferedOutputStream;
72import java.io.File;
Amith Yamasani920ace02012-09-20 22:15:37 -070073import java.io.FileDescriptor;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070074import java.io.FileInputStream;
Amith Yamasanib8151ec2012-04-18 18:02:48 -070075import java.io.FileNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070076import java.io.FileOutputStream;
77import java.io.IOException;
Amith Yamasani920ace02012-09-20 22:15:37 -070078import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +010079import java.nio.charset.StandardCharsets;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070080import java.util.ArrayList;
81import java.util.List;
Fyodor Kupolovb5013302015-04-17 17:59:14 -070082import java.util.Set;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070083
Fyodor Kupolov262f9952015-03-23 18:55:11 -070084import libcore.io.IoUtils;
85
Amith Yamasani258848d2012-08-10 17:06:33 -070086public class UserManagerService extends IUserManager.Stub {
Amith Yamasanib8151ec2012-04-18 18:02:48 -070087
Amith Yamasani2a003292012-08-14 18:25:45 -070088 private static final String LOG_TAG = "UserManagerService";
Amith Yamasanib8151ec2012-04-18 18:02:48 -070089
Amith Yamasani16389312012-10-17 21:20:14 -070090 private static final boolean DBG = false;
91
Amith Yamasani4b2e9342011-03-31 12:38:53 -070092 private static final String TAG_NAME = "name";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070093 private static final String ATTR_FLAGS = "flags";
Amith Yamasanib8151ec2012-04-18 18:02:48 -070094 private static final String ATTR_ICON_PATH = "icon";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070095 private static final String ATTR_ID = "id";
Amith Yamasani920ace02012-09-20 22:15:37 -070096 private static final String ATTR_CREATION_TIME = "created";
97 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
Amith Yamasani2a003292012-08-14 18:25:45 -070098 private static final String ATTR_SERIAL_NO = "serialNumber";
99 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700100 private static final String ATTR_PARTIAL = "partial";
Adam Lesinskieddeb492014-09-08 17:50:03 -0700101 private static final String ATTR_GUEST_TO_REMOVE = "guestToRemove";
Amith Yamasani6f34b412012-10-22 18:19:27 -0700102 private static final String ATTR_USER_VERSION = "version";
Kenny Guy2a764942014-04-02 13:29:20 +0100103 private static final String ATTR_PROFILE_GROUP_ID = "profileGroupId";
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530104 private static final String TAG_GUEST_RESTRICTIONS = "guestRestrictions";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700105 private static final String TAG_USERS = "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700106 private static final String TAG_USER = "user";
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800107 private static final String TAG_RESTRICTIONS = "restrictions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800108 private static final String TAG_ENTRY = "entry";
109 private static final String TAG_VALUE = "value";
110 private static final String ATTR_KEY = "key";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700111 private static final String ATTR_VALUE_TYPE = "type";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800112 private static final String ATTR_MULTIPLE = "m";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700113
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700114 private static final String ATTR_TYPE_STRING_ARRAY = "sa";
115 private static final String ATTR_TYPE_STRING = "s";
116 private static final String ATTR_TYPE_BOOLEAN = "b";
Amith Yamasani5b5aa402014-06-01 20:10:14 -0700117 private static final String ATTR_TYPE_INTEGER = "i";
Fyodor Kupolov262f9952015-03-23 18:55:11 -0700118 private static final String ATTR_TYPE_BUNDLE = "B";
119 private static final String ATTR_TYPE_BUNDLE_ARRAY = "BA";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700120
Amith Yamasani0b285492011-04-14 17:35:23 -0700121 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700122 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700123 private static final String USER_PHOTO_FILENAME = "photo.png";
Adrian Roos1bdff912015-02-17 15:51:35 +0100124 private static final String USER_PHOTO_FILENAME_TMP = USER_PHOTO_FILENAME + ".tmp";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700125
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800126 private static final String RESTRICTIONS_FILE_PREFIX = "res_";
Amith Yamasanifc95e702013-09-26 13:20:17 -0700127 private static final String XML_SUFFIX = ".xml";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800128
Amith Yamasani634cf312012-10-04 17:34:21 -0700129 private static final int MIN_USER_ID = 10;
130
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700131 private static final int USER_VERSION = 5;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700132
Amith Yamasani920ace02012-09-20 22:15:37 -0700133 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
134
Nicolas Prevotb8186812015-08-06 15:00:03 +0100135 // Maximum number of managed profiles permitted per user is 1. This cannot be increased
Amith Yamasani95ab7842014-08-11 17:09:26 -0700136 // without first making sure that the rest of the framework is prepared for it.
137 private static final int MAX_MANAGED_PROFILES = 1;
138
Andres Moralesc5548c02015-08-05 10:23:12 -0700139 /**
140 * Flag indicating whether device credentials are shared among same-user profiles.
141 */
142 private static final boolean CONFIG_PROFILES_SHARE_CREDENTIAL = true;
143
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700144 // Set of user restrictions, which can only be enforced by the system
145 private static final Set<String> SYSTEM_CONTROLLED_RESTRICTIONS = Sets.newArraySet(
146 UserManager.DISALLOW_RECORD_AUDIO);
147
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800148 static final int WRITE_USER_MSG = 1;
149 static final int WRITE_USER_DELAY = 2*1000; // 2 seconds
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530150
Jeff Sharkey6dce4962015-07-03 18:08:41 -0700151 private static final String XATTR_SERIAL = "user.serial";
152
Dianne Hackborn4428e172012-08-24 17:43:05 -0700153 private final Context mContext;
154 private final PackageManagerService mPm;
155 private final Object mInstallLock;
156 private final Object mPackagesLock;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700157
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800158 private final Handler mHandler;
159
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700160 private final File mUsersDir;
161 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700162
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800163 private final SparseArray<UserInfo> mUsers = new SparseArray<UserInfo>();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800164 private final SparseArray<Bundle> mUserRestrictions = new SparseArray<Bundle>();
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530165 private final Bundle mGuestRestrictions = new Bundle();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800166
167 /**
168 * Set of user IDs being actively removed. Removed IDs linger in this set
169 * for several seconds to work around a VFS caching issue.
170 */
171 // @GuardedBy("mPackagesLock")
172 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700173
Amith Yamasani0b285492011-04-14 17:35:23 -0700174 private int[] mUserIds;
Amith Yamasani2a003292012-08-14 18:25:45 -0700175 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700176 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700177
Jason Monk62062992014-05-06 09:55:28 -0400178 private IAppOpsService mAppOpsService;
179
Amith Yamasani258848d2012-08-10 17:06:33 -0700180 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700181
Dianne Hackborn4428e172012-08-24 17:43:05 -0700182 public static UserManagerService getInstance() {
183 synchronized (UserManagerService.class) {
184 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700185 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700186 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700187
188 /**
189 * Available for testing purposes.
190 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700191 UserManagerService(File dataDir, File baseUserPath) {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700192 this(null, null, new Object(), new Object(), dataDir, baseUserPath);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700193 }
194
Dianne Hackborn4428e172012-08-24 17:43:05 -0700195 /**
196 * Called by package manager to create the service. This is closely
197 * associated with the package manager, and the given lock is the
198 * package manager's own lock.
199 */
200 UserManagerService(Context context, PackageManagerService pm,
201 Object installLock, Object packagesLock) {
202 this(context, pm, installLock, packagesLock,
203 Environment.getDataDirectory(),
204 new File(Environment.getDataDirectory(), "user"));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700205 }
206
Dianne Hackborn4428e172012-08-24 17:43:05 -0700207 /**
208 * Available for testing purposes.
209 */
210 private UserManagerService(Context context, PackageManagerService pm,
211 Object installLock, Object packagesLock,
212 File dataDir, File baseUserPath) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700213 mContext = context;
214 mPm = pm;
215 mInstallLock = installLock;
216 mPackagesLock = packagesLock;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800217 mHandler = new MainHandler();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700218 synchronized (mInstallLock) {
219 synchronized (mPackagesLock) {
220 mUsersDir = new File(dataDir, USER_INFO_DIR);
221 mUsersDir.mkdirs();
222 // Make zeroth user directory, for services to migrate their files to that location
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700223 File userZeroDir = new File(mUsersDir, String.valueOf(UserHandle.USER_SYSTEM));
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700224 userZeroDir.mkdirs();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700225 FileUtils.setPermissions(mUsersDir.toString(),
226 FileUtils.S_IRWXU|FileUtils.S_IRWXG
227 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
228 -1, -1);
229 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
Amith Yamasanida0b1682014-11-21 12:58:17 -0800230 initDefaultGuestRestrictions();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700231 readUserListLocked();
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700232 sInstance = this;
233 }
234 }
235 }
236
237 void systemReady() {
238 synchronized (mInstallLock) {
239 synchronized (mPackagesLock) {
Amith Yamasani756901d2012-10-12 12:30:07 -0700240 // Prune out any partially created/partially removed users.
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700241 ArrayList<UserInfo> partials = new ArrayList<UserInfo>();
242 for (int i = 0; i < mUsers.size(); i++) {
243 UserInfo ui = mUsers.valueAt(i);
Adam Lesinskieddeb492014-09-08 17:50:03 -0700244 if ((ui.partial || ui.guestToRemove) && i != 0) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700245 partials.add(ui);
246 }
247 }
248 for (int i = 0; i < partials.size(); i++) {
249 UserInfo ui = partials.get(i);
Amith Yamasania7892482015-08-07 11:09:05 -0700250 Slog.w(LOG_TAG, "Removing partially created user " + ui.id
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700251 + " (name=" + ui.name + ")");
252 removeUserStateLocked(ui.id);
253 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700254 }
Dianne Hackborn4428e172012-08-24 17:43:05 -0700255 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700256 onUserForeground(UserHandle.USER_SYSTEM);
Jason Monk62062992014-05-06 09:55:28 -0400257 mAppOpsService = IAppOpsService.Stub.asInterface(
258 ServiceManager.getService(Context.APP_OPS_SERVICE));
259 for (int i = 0; i < mUserIds.length; ++i) {
260 try {
261 mAppOpsService.setUserRestrictions(mUserRestrictions.get(mUserIds[i]), mUserIds[i]);
262 } catch (RemoteException e) {
263 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
264 }
265 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700266 }
267
268 @Override
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700269 public UserInfo getPrimaryUser() {
270 checkManageUsersPermission("query users");
271 synchronized (mPackagesLock) {
272 for (int i = 0; i < mUsers.size(); i++) {
273 UserInfo ui = mUsers.valueAt(i);
274 if (ui.isPrimary()) {
275 return ui;
276 }
277 }
278 }
279 return null;
280 }
281
282 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -0700283 public List<UserInfo> getUsers(boolean excludeDying) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700284 checkManageUsersPermission("query users");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700285 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700286 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
287 for (int i = 0; i < mUsers.size(); i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700288 UserInfo ui = mUsers.valueAt(i);
289 if (ui.partial) {
290 continue;
291 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800292 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700293 users.add(ui);
Amith Yamasani920ace02012-09-20 22:15:37 -0700294 }
Amith Yamasani13593602012-03-22 16:16:17 -0700295 }
296 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700297 }
Amith Yamasani13593602012-03-22 16:16:17 -0700298 }
299
Amith Yamasani258848d2012-08-10 17:06:33 -0700300 @Override
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100301 public List<UserInfo> getProfiles(int userId, boolean enabledOnly) {
Amith Yamasani4f582632014-02-19 14:31:52 -0800302 if (userId != UserHandle.getCallingUserId()) {
303 checkManageUsersPermission("getting profiles related to user " + userId);
304 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700305 final long ident = Binder.clearCallingIdentity();
306 try {
307 synchronized (mPackagesLock) {
308 return getProfilesLocked(userId, enabledOnly);
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100309 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700310 } finally {
311 Binder.restoreCallingIdentity(ident);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000312 }
313 }
314
Amith Yamasanibe465322014-04-24 13:45:17 -0700315 /** Assume permissions already checked and caller's identity cleared */
316 private List<UserInfo> getProfilesLocked(int userId, boolean enabledOnly) {
Amith Yamasanibe465322014-04-24 13:45:17 -0700317 UserInfo user = getUserInfoLocked(userId);
318 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasanidda003f2014-08-28 18:06:51 -0700319 if (user == null) {
320 // Probably a dying user
321 return users;
322 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700323 for (int i = 0; i < mUsers.size(); i++) {
324 UserInfo profile = mUsers.valueAt(i);
325 if (!isProfileOf(user, profile)) {
326 continue;
327 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100328 if (enabledOnly && !profile.isEnabled()) {
329 continue;
Amith Yamasanibe465322014-04-24 13:45:17 -0700330 }
Amith Yamasani70fcf0c2014-07-11 08:40:19 -0700331 if (mRemovingUserIds.get(profile.id)) {
332 continue;
333 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700334 users.add(profile);
335 }
336 return users;
337 }
338
Jessica Hummelbe81c802014-04-22 15:49:22 +0100339 @Override
Andres Moralesc5548c02015-08-05 10:23:12 -0700340 public int getCredentialOwnerProfile(int userHandle) {
341 checkManageUsersPermission("get the credential owner");
342 if (CONFIG_PROFILES_SHARE_CREDENTIAL) {
343 synchronized (mPackagesLock) {
344 UserInfo profileParent = getProfileParentLocked(userHandle);
345 if (profileParent != null) {
346 return profileParent.id;
347 }
348 }
349 }
350
351 return userHandle;
352 }
353
354 @Override
Jessica Hummelbe81c802014-04-22 15:49:22 +0100355 public UserInfo getProfileParent(int userHandle) {
356 checkManageUsersPermission("get the profile parent");
357 synchronized (mPackagesLock) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700358 return getProfileParentLocked(userHandle);
359 }
360 }
361
362 private UserInfo getProfileParentLocked(int userHandle) {
363 UserInfo profile = getUserInfoLocked(userHandle);
364 if (profile == null) {
365 return null;
366 }
367 int parentUserId = profile.profileGroupId;
368 if (parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
369 return null;
370 } else {
371 return getUserInfoLocked(parentUserId);
Jessica Hummelbe81c802014-04-22 15:49:22 +0100372 }
373 }
374
Kenny Guy2a764942014-04-02 13:29:20 +0100375 private boolean isProfileOf(UserInfo user, UserInfo profile) {
376 return user.id == profile.id ||
377 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
378 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000379 }
380
381 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100382 public void setUserEnabled(int userId) {
383 checkManageUsersPermission("enable user");
384 synchronized (mPackagesLock) {
385 UserInfo info = getUserInfoLocked(userId);
386 if (info != null && !info.isEnabled()) {
387 info.flags ^= UserInfo.FLAG_DISABLED;
388 writeUserLocked(info);
389 }
390 }
391 }
392
393 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700394 public UserInfo getUserInfo(int userId) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700395 checkManageUsersPermission("query user");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700396 synchronized (mPackagesLock) {
Amith Yamasani195263742012-08-21 15:40:12 -0700397 return getUserInfoLocked(userId);
Amith Yamasani13593602012-03-22 16:16:17 -0700398 }
399 }
400
Amith Yamasani71e6c692013-03-24 17:39:28 -0700401 @Override
402 public boolean isRestricted() {
403 synchronized (mPackagesLock) {
404 return getUserInfoLocked(UserHandle.getCallingUserId()).isRestricted();
405 }
406 }
407
Amith Yamasani195263742012-08-21 15:40:12 -0700408 /*
409 * Should be locked on mUsers before calling this.
410 */
411 private UserInfo getUserInfoLocked(int userId) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700412 UserInfo ui = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -0700413 // If it is partial and not in the process of being removed, return as unknown user.
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800414 if (ui != null && ui.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700415 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
416 return null;
417 }
418 return ui;
Amith Yamasani195263742012-08-21 15:40:12 -0700419 }
420
Amith Yamasani13593602012-03-22 16:16:17 -0700421 public boolean exists(int userId) {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700422 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700423 return ArrayUtils.contains(mUserIds, userId);
424 }
425 }
426
Amith Yamasani258848d2012-08-10 17:06:33 -0700427 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700428 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700429 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700430 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700431 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700432 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700433 if (info == null || info.partial) {
434 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
435 return;
436 }
Amith Yamasani13593602012-03-22 16:16:17 -0700437 if (name != null && !name.equals(info.name)) {
438 info.name = name;
439 writeUserLocked(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700440 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -0700441 }
442 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700443 if (changed) {
444 sendUserInfoChangedBroadcast(userId);
445 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700446 }
447
Amith Yamasani258848d2012-08-10 17:06:33 -0700448 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700449 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700450 checkManageUsersPermission("update users");
Jason Monk9a944532014-07-08 09:31:21 -0400451 long ident = Binder.clearCallingIdentity();
452 try {
453 synchronized (mPackagesLock) {
454 UserInfo info = mUsers.get(userId);
455 if (info == null || info.partial) {
456 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
457 return;
458 }
459 writeBitmapLocked(info, bitmap);
460 writeUserLocked(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700461 }
Jason Monk9a944532014-07-08 09:31:21 -0400462 sendUserInfoChangedBroadcast(userId);
463 } finally {
464 Binder.restoreCallingIdentity(ident);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700465 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700466 }
467
468 private void sendUserInfoChangedBroadcast(int userId) {
469 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
470 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
471 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -0700472 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700473 }
474
Amith Yamasani258848d2012-08-10 17:06:33 -0700475 @Override
Adrian Roos1bdff912015-02-17 15:51:35 +0100476 public ParcelFileDescriptor getUserIcon(int userId) {
477 String iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700478 synchronized (mPackagesLock) {
479 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700480 if (info == null || info.partial) {
481 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + userId);
482 return null;
483 }
Nicolas Prevot88cc3462014-05-14 14:51:48 +0100484 int callingGroupId = mUsers.get(UserHandle.getCallingUserId()).profileGroupId;
485 if (callingGroupId == UserInfo.NO_PROFILE_GROUP_ID
486 || callingGroupId != info.profileGroupId) {
487 checkManageUsersPermission("get the icon of a user who is not related");
488 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700489 if (info.iconPath == null) {
490 return null;
491 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100492 iconPath = info.iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700493 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100494
495 try {
496 return ParcelFileDescriptor.open(
497 new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
498 } catch (FileNotFoundException e) {
499 Log.e(LOG_TAG, "Couldn't find icon file", e);
500 }
501 return null;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700502 }
503
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700504 public void makeInitialized(int userId) {
505 checkManageUsersPermission("makeInitialized");
506 synchronized (mPackagesLock) {
507 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700508 if (info == null || info.partial) {
509 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
510 }
511 if ((info.flags&UserInfo.FLAG_INITIALIZED) == 0) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700512 info.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800513 scheduleWriteUserLocked(info);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700514 }
515 }
516 }
517
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700518 /**
519 * If default guest restrictions haven't been initialized yet, add the basic
520 * restrictions.
521 */
522 private void initDefaultGuestRestrictions() {
523 if (mGuestRestrictions.isEmpty()) {
524 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
Amith Yamasanida0b1682014-11-21 12:58:17 -0800525 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700526 }
527 }
528
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800529 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530530 public Bundle getDefaultGuestRestrictions() {
531 checkManageUsersPermission("getDefaultGuestRestrictions");
532 synchronized (mPackagesLock) {
533 return new Bundle(mGuestRestrictions);
534 }
535 }
536
537 @Override
538 public void setDefaultGuestRestrictions(Bundle restrictions) {
539 checkManageUsersPermission("setDefaultGuestRestrictions");
540 synchronized (mPackagesLock) {
541 mGuestRestrictions.clear();
542 mGuestRestrictions.putAll(restrictions);
543 writeUserListLocked();
544 }
545 }
546
547 @Override
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700548 public boolean hasUserRestriction(String restrictionKey, int userId) {
549 synchronized (mPackagesLock) {
550 Bundle restrictions = mUserRestrictions.get(userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700551 return restrictions != null && restrictions.getBoolean(restrictionKey);
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700552 }
553 }
554
555 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800556 public Bundle getUserRestrictions(int userId) {
557 // checkManageUsersPermission("getUserRestrictions");
558
559 synchronized (mPackagesLock) {
560 Bundle restrictions = mUserRestrictions.get(userId);
Amith Yamasanibe465322014-04-24 13:45:17 -0700561 return restrictions != null ? new Bundle(restrictions) : new Bundle();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800562 }
563 }
564
565 @Override
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700566 public void setUserRestriction(String key, boolean value, int userId) {
Fyodor Kupolovd4b26042015-07-27 14:30:59 -0700567 checkManageUsersPermission("setUserRestriction");
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700568 synchronized (mPackagesLock) {
569 if (!SYSTEM_CONTROLLED_RESTRICTIONS.contains(key)) {
570 Bundle restrictions = getUserRestrictions(userId);
571 restrictions.putBoolean(key, value);
572 setUserRestrictionsInternalLocked(restrictions, userId);
573 }
574 }
575 }
576
577 @Override
578 public void setSystemControlledUserRestriction(String key, boolean value, int userId) {
579 checkSystemOrRoot("setSystemControlledUserRestriction");
580 synchronized (mPackagesLock) {
581 Bundle restrictions = getUserRestrictions(userId);
582 restrictions.putBoolean(key, value);
583 setUserRestrictionsInternalLocked(restrictions, userId);
584 }
585 }
586
587 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800588 public void setUserRestrictions(Bundle restrictions, int userId) {
Amith Yamasanibe465322014-04-24 13:45:17 -0700589 checkManageUsersPermission("setUserRestrictions");
Amith Yamasani0343ec32013-07-22 14:52:06 -0700590 if (restrictions == null) return;
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800591
592 synchronized (mPackagesLock) {
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700593 final Bundle oldUserRestrictions = mUserRestrictions.get(userId);
594 // Restore the original state of system controlled restrictions from oldUserRestrictions
595 for (String key : SYSTEM_CONTROLLED_RESTRICTIONS) {
596 restrictions.remove(key);
597 if (oldUserRestrictions.containsKey(key)) {
598 restrictions.putBoolean(key, oldUserRestrictions.getBoolean(key));
599 }
Jason Monk62062992014-05-06 09:55:28 -0400600 }
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700601 setUserRestrictionsInternalLocked(restrictions, userId);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800602 }
603 }
604
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700605 private void setUserRestrictionsInternalLocked(Bundle restrictions, int userId) {
606 final Bundle userRestrictions = mUserRestrictions.get(userId);
607 userRestrictions.clear();
608 userRestrictions.putAll(restrictions);
609 long token = Binder.clearCallingIdentity();
610 try {
611 mAppOpsService.setUserRestrictions(userRestrictions, userId);
612 } catch (RemoteException e) {
613 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
614 } finally {
615 Binder.restoreCallingIdentity(token);
616 }
617 scheduleWriteUserLocked(mUsers.get(userId));
618 }
619
Amith Yamasani258848d2012-08-10 17:06:33 -0700620 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700621 * Check if we've hit the limit of how many users can be created.
622 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700623 private boolean isUserLimitReachedLocked() {
Nicolas Prevot12678a92015-05-13 12:15:03 -0700624 return getAliveUsersExcludingGuestsCountLocked() >= UserManager.getMaxSupportedUsers();
625 }
626
627 @Override
Nicolas Prevotb8186812015-08-06 15:00:03 +0100628 public boolean canAddMoreManagedProfiles(int userId) {
Nicolas Prevot12678a92015-05-13 12:15:03 -0700629 checkManageUsersPermission("check if more managed profiles can be added.");
630 if (ActivityManager.isLowRamDeviceStatic()) {
631 return false;
632 }
Fyodor Kupolovb6157992015-06-05 15:32:28 -0700633 if (!mContext.getPackageManager().hasSystemFeature(
634 PackageManager.FEATURE_MANAGED_USERS)) {
635 return false;
636 }
Nicolas Prevotb8186812015-08-06 15:00:03 +0100637 // Limit number of managed profiles that can be created
638 int managedProfilesCount = getProfiles(userId, true).size() - 1;
639 if (managedProfilesCount >= MAX_MANAGED_PROFILES) {
640 return false;
641 }
Nicolas Prevot12678a92015-05-13 12:15:03 -0700642 synchronized(mPackagesLock) {
Nicolas Prevotb8186812015-08-06 15:00:03 +0100643 UserInfo userInfo = getUserInfoLocked(userId);
644 if (!userInfo.canHaveProfile()) {
Nicolas Prevot12678a92015-05-13 12:15:03 -0700645 return false;
646 }
647 int usersCount = getAliveUsersExcludingGuestsCountLocked();
648 // We allow creating a managed profile in the special case where there is only one user.
649 return usersCount == 1 || usersCount < UserManager.getMaxSupportedUsers();
650 }
651 }
652
653 private int getAliveUsersExcludingGuestsCountLocked() {
Amith Yamasanif584f012014-05-19 17:57:25 -0700654 int aliveUserCount = 0;
655 final int totalUserCount = mUsers.size();
656 // Skip over users being removed
657 for (int i = 0; i < totalUserCount; i++) {
658 UserInfo user = mUsers.valueAt(i);
Amith Yamasani95ab7842014-08-11 17:09:26 -0700659 if (!mRemovingUserIds.get(user.id)
Amith Yamasani1df14732014-08-29 21:37:27 -0700660 && !user.isGuest() && !user.partial) {
Amith Yamasanif584f012014-05-19 17:57:25 -0700661 aliveUserCount++;
662 }
663 }
Nicolas Prevot12678a92015-05-13 12:15:03 -0700664 return aliveUserCount;
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700665 }
666
667 /**
Amith Yamasani195263742012-08-21 15:40:12 -0700668 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -0700669 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -0700670 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -0700671 *
672 * @param message used as message if SecurityException is thrown
673 * @throws SecurityException if the caller is not system or root
674 */
Amith Yamasanibe465322014-04-24 13:45:17 -0700675 private static final void checkManageUsersPermission(String message) {
Amith Yamasani258848d2012-08-10 17:06:33 -0700676 final int uid = Binder.getCallingUid();
Amith Yamasanibe465322014-04-24 13:45:17 -0700677 if (uid != Process.SYSTEM_UID && uid != 0
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400678 && ActivityManager.checkComponentPermission(
679 android.Manifest.permission.MANAGE_USERS,
Amith Yamasanibe465322014-04-24 13:45:17 -0700680 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
681 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
682 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400683 }
684
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700685 private static void checkSystemOrRoot(String message) {
686 final int uid = Binder.getCallingUid();
687 if (uid != Process.SYSTEM_UID && uid != 0) {
688 throw new SecurityException("Only system may call: " + message);
689 }
690 }
691
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700692 private void writeBitmapLocked(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700693 try {
694 File dir = new File(mUsersDir, Integer.toString(info.id));
695 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +0100696 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700697 if (!dir.exists()) {
698 dir.mkdir();
699 FileUtils.setPermissions(
700 dir.getPath(),
701 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
702 -1, -1);
703 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700704 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +0100705 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
706 && tmp.renameTo(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -0700707 info.iconPath = file.getAbsolutePath();
708 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700709 try {
710 os.close();
711 } catch (IOException ioe) {
712 // What the ... !
713 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100714 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700715 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700716 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700717 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700718 }
719
Amith Yamasani0b285492011-04-14 17:35:23 -0700720 /**
721 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
722 * cache it elsewhere.
723 * @return the array of user ids.
724 */
Dianne Hackborn1676c852012-09-10 14:52:30 -0700725 public int[] getUserIds() {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700726 synchronized (mPackagesLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700727 return mUserIds;
728 }
Amith Yamasani0b285492011-04-14 17:35:23 -0700729 }
730
Dianne Hackborn4428e172012-08-24 17:43:05 -0700731 int[] getUserIdsLPr() {
732 return mUserIds;
733 }
734
Amith Yamasani13593602012-03-22 16:16:17 -0700735 private void readUserListLocked() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700736 if (!mUserListFile.exists()) {
Amith Yamasani13593602012-03-22 16:16:17 -0700737 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700738 return;
739 }
740 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700741 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700742 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700743 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700744 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100745 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700746 int type;
747 while ((type = parser.next()) != XmlPullParser.START_TAG
748 && type != XmlPullParser.END_DOCUMENT) {
749 ;
750 }
751
752 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700753 Slog.e(LOG_TAG, "Unable to read user list");
Amith Yamasani13593602012-03-22 16:16:17 -0700754 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700755 return;
756 }
757
Amith Yamasani2a003292012-08-14 18:25:45 -0700758 mNextSerialNumber = -1;
759 if (parser.getName().equals(TAG_USERS)) {
760 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
761 if (lastSerialNumber != null) {
762 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
763 }
Amith Yamasani6f34b412012-10-22 18:19:27 -0700764 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
765 if (versionNumber != null) {
766 mUserVersion = Integer.parseInt(versionNumber);
767 }
Amith Yamasani2a003292012-08-14 18:25:45 -0700768 }
769
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700770 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530771 if (type == XmlPullParser.START_TAG) {
772 final String name = parser.getName();
773 if (name.equals(TAG_USER)) {
774 String id = parser.getAttributeValue(null, ATTR_ID);
775 UserInfo user = readUserLocked(Integer.parseInt(id));
Amith Yamasani6f34b412012-10-22 18:19:27 -0700776
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530777 if (user != null) {
778 mUsers.put(user.id, user);
779 if (mNextSerialNumber < 0 || mNextSerialNumber <= user.id) {
780 mNextSerialNumber = user.id + 1;
781 }
Amith Yamasani2a003292012-08-14 18:25:45 -0700782 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530783 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -0800784 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
785 && type != XmlPullParser.END_TAG) {
786 if (type == XmlPullParser.START_TAG) {
787 if (parser.getName().equals(TAG_RESTRICTIONS)) {
788 readRestrictionsLocked(parser, mGuestRestrictions);
789 }
790 break;
791 }
792 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700793 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700794 }
795 }
Amith Yamasani13593602012-03-22 16:16:17 -0700796 updateUserIdsLocked();
Amith Yamasani350962c2013-08-06 11:18:53 -0700797 upgradeIfNecessaryLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700798 } catch (IOException ioe) {
Amith Yamasani13593602012-03-22 16:16:17 -0700799 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700800 } catch (XmlPullParserException pe) {
Amith Yamasani13593602012-03-22 16:16:17 -0700801 fallbackToSingleUserLocked();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -0800802 } finally {
803 if (fis != null) {
804 try {
805 fis.close();
806 } catch (IOException e) {
807 }
808 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700809 }
810 }
811
Amith Yamasani6f34b412012-10-22 18:19:27 -0700812 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -0800813 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -0700814 */
Amith Yamasani350962c2013-08-06 11:18:53 -0700815 private void upgradeIfNecessaryLocked() {
Amith Yamasani6f34b412012-10-22 18:19:27 -0700816 int userVersion = mUserVersion;
817 if (userVersion < 1) {
818 // Assign a proper name for the owner, if not initialized correctly before
819 UserInfo user = mUsers.get(UserHandle.USER_OWNER);
820 if ("Primary".equals(user.name)) {
821 user.name = mContext.getResources().getString(com.android.internal.R.string.owner_name);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800822 scheduleWriteUserLocked(user);
Amith Yamasani6f34b412012-10-22 18:19:27 -0700823 }
824 userVersion = 1;
825 }
826
Amith Yamasanibc9625052012-11-15 14:39:18 -0800827 if (userVersion < 2) {
828 // Owner should be marked as initialized
829 UserInfo user = mUsers.get(UserHandle.USER_OWNER);
830 if ((user.flags & UserInfo.FLAG_INITIALIZED) == 0) {
831 user.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800832 scheduleWriteUserLocked(user);
Amith Yamasanibc9625052012-11-15 14:39:18 -0800833 }
834 userVersion = 2;
835 }
836
Amith Yamasani350962c2013-08-06 11:18:53 -0700837
Amith Yamasani5e486f52013-08-07 11:06:44 -0700838 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -0700839 userVersion = 4;
840 }
841
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700842 if (userVersion < 5) {
843 initDefaultGuestRestrictions();
844 userVersion = 5;
845 }
846
Amith Yamasani6f34b412012-10-22 18:19:27 -0700847 if (userVersion < USER_VERSION) {
848 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
849 + USER_VERSION);
850 } else {
851 mUserVersion = userVersion;
852 writeUserListLocked();
853 }
854 }
855
Amith Yamasani13593602012-03-22 16:16:17 -0700856 private void fallbackToSingleUserLocked() {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -0700857 int flags = UserInfo.FLAG_INITIALIZED;
858 // In split system user mode, the admin and primary flags are assigned to the first human
859 // user.
860 if (!UserManager.isSplitSystemUser()) {
861 flags |= UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY;
862 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700863 // Create the system user
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700864 UserInfo system = new UserInfo(UserHandle.USER_SYSTEM,
Amith Yamasani6f34b412012-10-22 18:19:27 -0700865 mContext.getResources().getString(com.android.internal.R.string.owner_name), null,
Xiaohui Chenb31e14a2015-07-13 16:04:55 -0700866 flags);
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700867 mUsers.put(system.id, system);
Amith Yamasani634cf312012-10-04 17:34:21 -0700868 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -0400869 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -0800870
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -0500871 Bundle restrictions = new Bundle();
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700872 mUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions);
Amith Yamasani67df64b2012-12-14 12:09:36 -0800873
Amith Yamasani13593602012-03-22 16:16:17 -0700874 updateUserIdsLocked();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700875 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700876
Amith Yamasani13593602012-03-22 16:16:17 -0700877 writeUserListLocked();
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700878 writeUserLocked(system);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700879 }
880
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800881 private void scheduleWriteUserLocked(UserInfo userInfo) {
882 if (!mHandler.hasMessages(WRITE_USER_MSG, userInfo)) {
883 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, userInfo);
884 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
885 }
886 }
887
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700888 /*
889 * Writes the user file in this format:
890 *
891 * <user flags="20039023" id="0">
892 * <name>Primary</name>
893 * </user>
894 */
Amith Yamasani13593602012-03-22 16:16:17 -0700895 private void writeUserLocked(UserInfo userInfo) {
Amith Yamasani742a6712011-05-04 14:49:28 -0700896 FileOutputStream fos = null;
Amith Yamasanifc95e702013-09-26 13:20:17 -0700897 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userInfo.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700898 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700899 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700900 final BufferedOutputStream bos = new BufferedOutputStream(fos);
901
902 // XmlSerializer serializer = XmlUtils.serializerInstance();
903 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100904 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700905 serializer.startDocument(null, true);
906 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
907
908 serializer.startTag(null, TAG_USER);
909 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
Amith Yamasani2a003292012-08-14 18:25:45 -0700910 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700911 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Amith Yamasani920ace02012-09-20 22:15:37 -0700912 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
913 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
914 Long.toString(userInfo.lastLoggedInTime));
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700915 if (userInfo.iconPath != null) {
916 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
917 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700918 if (userInfo.partial) {
919 serializer.attribute(null, ATTR_PARTIAL, "true");
920 }
Adam Lesinskieddeb492014-09-08 17:50:03 -0700921 if (userInfo.guestToRemove) {
922 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
923 }
Kenny Guy2a764942014-04-02 13:29:20 +0100924 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
925 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
926 Integer.toString(userInfo.profileGroupId));
Kenny Guya52dc3e2014-02-11 15:33:14 +0000927 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700928
929 serializer.startTag(null, TAG_NAME);
930 serializer.text(userInfo.name);
931 serializer.endTag(null, TAG_NAME);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800932 Bundle restrictions = mUserRestrictions.get(userInfo.id);
933 if (restrictions != null) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530934 writeRestrictionsLocked(serializer, restrictions);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800935 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700936 serializer.endTag(null, TAG_USER);
937
938 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -0700939 userFile.finishWrite(fos);
940 } catch (Exception ioe) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700941 Slog.e(LOG_TAG, "Error writing user info " + userInfo.id + "\n" + ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -0700942 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700943 }
944 }
945
946 /*
947 * Writes the user list file in this format:
948 *
Amith Yamasani2a003292012-08-14 18:25:45 -0700949 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700950 * <user id="0"></user>
951 * <user id="2"></user>
952 * </users>
953 */
Amith Yamasani13593602012-03-22 16:16:17 -0700954 private void writeUserListLocked() {
Amith Yamasani742a6712011-05-04 14:49:28 -0700955 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700956 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700957 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700958 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700959 final BufferedOutputStream bos = new BufferedOutputStream(fos);
960
961 // XmlSerializer serializer = XmlUtils.serializerInstance();
962 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100963 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700964 serializer.startDocument(null, true);
965 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
966
967 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -0700968 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -0700969 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700970
Adam Lesinskieddeb492014-09-08 17:50:03 -0700971 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530972 writeRestrictionsLocked(serializer, mGuestRestrictions);
973 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700974 for (int i = 0; i < mUsers.size(); i++) {
975 UserInfo user = mUsers.valueAt(i);
976 serializer.startTag(null, TAG_USER);
977 serializer.attribute(null, ATTR_ID, Integer.toString(user.id));
978 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700979 }
980
981 serializer.endTag(null, TAG_USERS);
982
983 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -0700984 userListFile.finishWrite(fos);
985 } catch (Exception e) {
986 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -0700987 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700988 }
989 }
990
Andres Moralesc5548c02015-08-05 10:23:12 -0700991 private void writeRestrictionsLocked(XmlSerializer serializer, Bundle restrictions)
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530992 throws IOException {
993 serializer.startTag(null, TAG_RESTRICTIONS);
994 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_WIFI);
995 writeBoolean(serializer, restrictions, UserManager.DISALLOW_MODIFY_ACCOUNTS);
996 writeBoolean(serializer, restrictions, UserManager.DISALLOW_INSTALL_APPS);
997 writeBoolean(serializer, restrictions, UserManager.DISALLOW_UNINSTALL_APPS);
998 writeBoolean(serializer, restrictions, UserManager.DISALLOW_SHARE_LOCATION);
999 writeBoolean(serializer, restrictions,
1000 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
1001 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_BLUETOOTH);
1002 writeBoolean(serializer, restrictions, UserManager.DISALLOW_USB_FILE_TRANSFER);
1003 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_CREDENTIALS);
1004 writeBoolean(serializer, restrictions, UserManager.DISALLOW_REMOVE_USER);
1005 writeBoolean(serializer, restrictions, UserManager.DISALLOW_DEBUGGING_FEATURES);
1006 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_VPN);
1007 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_TETHERING);
Stuart Scott94b038b2015-04-20 14:07:45 -07001008 writeBoolean(serializer, restrictions, UserManager.DISALLOW_NETWORK_RESET);
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301009 writeBoolean(serializer, restrictions, UserManager.DISALLOW_FACTORY_RESET);
1010 writeBoolean(serializer, restrictions, UserManager.DISALLOW_ADD_USER);
1011 writeBoolean(serializer, restrictions, UserManager.ENSURE_VERIFY_APPS);
1012 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_CELL_BROADCASTS);
1013 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS);
1014 writeBoolean(serializer, restrictions, UserManager.DISALLOW_APPS_CONTROL);
1015 writeBoolean(serializer, restrictions, UserManager.DISALLOW_MOUNT_PHYSICAL_MEDIA);
1016 writeBoolean(serializer, restrictions, UserManager.DISALLOW_UNMUTE_MICROPHONE);
1017 writeBoolean(serializer, restrictions, UserManager.DISALLOW_ADJUST_VOLUME);
Amith Yamasani390989d2014-07-17 10:52:03 -07001018 writeBoolean(serializer, restrictions, UserManager.DISALLOW_OUTGOING_CALLS);
1019 writeBoolean(serializer, restrictions, UserManager.DISALLOW_SMS);
Jeff Sharkey2cc03e52015-03-20 11:24:04 -07001020 writeBoolean(serializer, restrictions, UserManager.DISALLOW_FUN);
Jason Monk1c7c3192014-06-26 12:52:18 -04001021 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CREATE_WINDOWS);
Amith Yamasani26af8292014-09-09 09:57:27 -07001022 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CROSS_PROFILE_COPY_PASTE);
1023 writeBoolean(serializer, restrictions, UserManager.DISALLOW_OUTGOING_BEAM);
Benjamin Franzf3ece362015-02-11 10:51:10 +00001024 writeBoolean(serializer, restrictions, UserManager.DISALLOW_WALLPAPER);
Benjamin Franzbff46ba2015-03-05 18:33:51 +00001025 writeBoolean(serializer, restrictions, UserManager.DISALLOW_SAFE_BOOT);
Nicolas Prevotf0029c12015-06-25 14:25:41 -07001026 writeBoolean(serializer, restrictions, UserManager.ALLOW_PARENT_PROFILE_APP_LINKING);
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301027 serializer.endTag(null, TAG_RESTRICTIONS);
1028 }
1029
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001030 private UserInfo readUserLocked(int id) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001031 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -07001032 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001033 String name = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001034 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -07001035 long creationTime = 0L;
1036 long lastLoggedInTime = 0L;
Kenny Guy2a764942014-04-02 13:29:20 +01001037 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001038 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001039 boolean guestToRemove = false;
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001040 Bundle restrictions = new Bundle();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001041
1042 FileInputStream fis = null;
1043 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001044 AtomicFile userFile =
Amith Yamasanifc95e702013-09-26 13:20:17 -07001045 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
Amith Yamasani2a003292012-08-14 18:25:45 -07001046 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001047 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001048 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001049 int type;
1050 while ((type = parser.next()) != XmlPullParser.START_TAG
1051 && type != XmlPullParser.END_DOCUMENT) {
1052 ;
1053 }
1054
1055 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001056 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001057 return null;
1058 }
1059
1060 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001061 int storedId = readIntAttribute(parser, ATTR_ID, -1);
1062 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001063 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001064 return null;
1065 }
Amith Yamasani920ace02012-09-20 22:15:37 -07001066 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
1067 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001068 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -07001069 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
1070 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Kenny Guy2a764942014-04-02 13:29:20 +01001071 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
1072 UserInfo.NO_PROFILE_GROUP_ID);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001073 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
1074 if ("true".equals(valueString)) {
1075 partial = true;
1076 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001077 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
1078 if ("true".equals(valueString)) {
1079 guestToRemove = true;
1080 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001081
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001082 int outerDepth = parser.getDepth();
1083 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1084 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1085 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1086 continue;
1087 }
1088 String tag = parser.getName();
1089 if (TAG_NAME.equals(tag)) {
1090 type = parser.next();
1091 if (type == XmlPullParser.TEXT) {
1092 name = parser.getText();
1093 }
1094 } else if (TAG_RESTRICTIONS.equals(tag)) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301095 readRestrictionsLocked(parser, restrictions);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001096 }
1097 }
1098 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001099
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001100 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -07001101 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -07001102 userInfo.creationTime = creationTime;
1103 userInfo.lastLoggedInTime = lastLoggedInTime;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001104 userInfo.partial = partial;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001105 userInfo.guestToRemove = guestToRemove;
Kenny Guy2a764942014-04-02 13:29:20 +01001106 userInfo.profileGroupId = profileGroupId;
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001107 mUserRestrictions.append(id, restrictions);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001108 return userInfo;
1109
1110 } catch (IOException ioe) {
1111 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001112 } finally {
1113 if (fis != null) {
1114 try {
1115 fis.close();
1116 } catch (IOException e) {
1117 }
1118 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001119 }
1120 return null;
1121 }
1122
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301123 private void readRestrictionsLocked(XmlPullParser parser, Bundle restrictions)
1124 throws IOException {
1125 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_WIFI);
1126 readBoolean(parser, restrictions, UserManager.DISALLOW_MODIFY_ACCOUNTS);
1127 readBoolean(parser, restrictions, UserManager.DISALLOW_INSTALL_APPS);
1128 readBoolean(parser, restrictions, UserManager.DISALLOW_UNINSTALL_APPS);
1129 readBoolean(parser, restrictions, UserManager.DISALLOW_SHARE_LOCATION);
1130 readBoolean(parser, restrictions,
1131 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
1132 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_BLUETOOTH);
1133 readBoolean(parser, restrictions, UserManager.DISALLOW_USB_FILE_TRANSFER);
1134 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_CREDENTIALS);
1135 readBoolean(parser, restrictions, UserManager.DISALLOW_REMOVE_USER);
1136 readBoolean(parser, restrictions, UserManager.DISALLOW_DEBUGGING_FEATURES);
1137 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_VPN);
1138 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_TETHERING);
Stuart Scott94b038b2015-04-20 14:07:45 -07001139 readBoolean(parser, restrictions, UserManager.DISALLOW_NETWORK_RESET);
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301140 readBoolean(parser, restrictions, UserManager.DISALLOW_FACTORY_RESET);
1141 readBoolean(parser, restrictions, UserManager.DISALLOW_ADD_USER);
1142 readBoolean(parser, restrictions, UserManager.ENSURE_VERIFY_APPS);
1143 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_CELL_BROADCASTS);
1144 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS);
1145 readBoolean(parser, restrictions, UserManager.DISALLOW_APPS_CONTROL);
1146 readBoolean(parser, restrictions,
1147 UserManager.DISALLOW_MOUNT_PHYSICAL_MEDIA);
1148 readBoolean(parser, restrictions, UserManager.DISALLOW_UNMUTE_MICROPHONE);
1149 readBoolean(parser, restrictions, UserManager.DISALLOW_ADJUST_VOLUME);
Amith Yamasani390989d2014-07-17 10:52:03 -07001150 readBoolean(parser, restrictions, UserManager.DISALLOW_OUTGOING_CALLS);
1151 readBoolean(parser, restrictions, UserManager.DISALLOW_SMS);
Jeff Sharkey2cc03e52015-03-20 11:24:04 -07001152 readBoolean(parser, restrictions, UserManager.DISALLOW_FUN);
Jason Monk1c7c3192014-06-26 12:52:18 -04001153 readBoolean(parser, restrictions, UserManager.DISALLOW_CREATE_WINDOWS);
Amith Yamasani26af8292014-09-09 09:57:27 -07001154 readBoolean(parser, restrictions, UserManager.DISALLOW_CROSS_PROFILE_COPY_PASTE);
1155 readBoolean(parser, restrictions, UserManager.DISALLOW_OUTGOING_BEAM);
Benjamin Franzf3ece362015-02-11 10:51:10 +00001156 readBoolean(parser, restrictions, UserManager.DISALLOW_WALLPAPER);
Benjamin Franzbff46ba2015-03-05 18:33:51 +00001157 readBoolean(parser, restrictions, UserManager.DISALLOW_SAFE_BOOT);
Nicolas Prevotf0029c12015-06-25 14:25:41 -07001158 readBoolean(parser, restrictions, UserManager.ALLOW_PARENT_PROFILE_APP_LINKING);
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301159 }
1160
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001161 private void readBoolean(XmlPullParser parser, Bundle restrictions,
1162 String restrictionKey) {
1163 String value = parser.getAttributeValue(null, restrictionKey);
Amith Yamasani71e6c692013-03-24 17:39:28 -07001164 if (value != null) {
1165 restrictions.putBoolean(restrictionKey, Boolean.parseBoolean(value));
1166 }
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001167 }
1168
1169 private void writeBoolean(XmlSerializer xml, Bundle restrictions, String restrictionKey)
1170 throws IOException {
1171 if (restrictions.containsKey(restrictionKey)) {
1172 xml.attribute(null, restrictionKey,
1173 Boolean.toString(restrictions.getBoolean(restrictionKey)));
1174 }
1175 }
1176
Amith Yamasani920ace02012-09-20 22:15:37 -07001177 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
1178 String valueString = parser.getAttributeValue(null, attr);
1179 if (valueString == null) return defaultValue;
1180 try {
1181 return Integer.parseInt(valueString);
1182 } catch (NumberFormatException nfe) {
1183 return defaultValue;
1184 }
1185 }
1186
1187 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
1188 String valueString = parser.getAttributeValue(null, attr);
1189 if (valueString == null) return defaultValue;
1190 try {
1191 return Long.parseLong(valueString);
1192 } catch (NumberFormatException nfe) {
1193 return defaultValue;
1194 }
1195 }
1196
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001197 private boolean isPackageInstalled(String pkg, int userId) {
1198 final ApplicationInfo info = mPm.getApplicationInfo(pkg,
1199 PackageManager.GET_UNINSTALLED_PACKAGES,
1200 userId);
1201 if (info == null || (info.flags&ApplicationInfo.FLAG_INSTALLED) == 0) {
1202 return false;
1203 }
1204 return true;
1205 }
1206
Amith Yamasanib82add22013-07-09 11:24:44 -07001207 /**
Kenny Guyd21b2182014-07-17 16:38:55 +01001208 * Removes all the restrictions files (res_<packagename>) for a given user.
Amith Yamasanib82add22013-07-09 11:24:44 -07001209 * Does not do any permissions checking.
1210 */
Kenny Guyd21b2182014-07-17 16:38:55 +01001211 private void cleanAppRestrictions(int userId) {
Amith Yamasanib82add22013-07-09 11:24:44 -07001212 synchronized (mPackagesLock) {
1213 File dir = Environment.getUserSystemDirectory(userId);
1214 String[] files = dir.list();
1215 if (files == null) return;
1216 for (String fileName : files) {
1217 if (fileName.startsWith(RESTRICTIONS_FILE_PREFIX)) {
1218 File resFile = new File(dir, fileName);
1219 if (resFile.exists()) {
Kenny Guyd21b2182014-07-17 16:38:55 +01001220 resFile.delete();
Amith Yamasanib82add22013-07-09 11:24:44 -07001221 }
1222 }
1223 }
1224 }
1225 }
1226
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001227 /**
1228 * Removes the app restrictions file for a specific package and user id, if it exists.
1229 */
1230 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
1231 synchronized (mPackagesLock) {
1232 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07001233 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001234 if (resFile.exists()) {
1235 resFile.delete();
1236 }
1237 }
1238 }
1239
Kenny Guya52dc3e2014-02-11 15:33:14 +00001240 @Override
Kenny Guy2a764942014-04-02 13:29:20 +01001241 public UserInfo createProfileForUser(String name, int flags, int userId) {
Kenny Guya52dc3e2014-02-11 15:33:14 +00001242 checkManageUsersPermission("Only the system can create users");
Kenny Guy2a764942014-04-02 13:29:20 +01001243 return createUserInternal(name, flags, userId);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001244 }
1245
Amith Yamasani258848d2012-08-10 17:06:33 -07001246 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07001247 public UserInfo createUser(String name, int flags) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001248 checkManageUsersPermission("Only the system can create users");
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001249 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001250 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001251
Jessica Hummelbe81c802014-04-22 15:49:22 +01001252 private UserInfo createUserInternal(String name, int flags, int parentId) {
Julia Reynolds75175022014-06-26 16:35:00 -04001253 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1254 UserManager.DISALLOW_ADD_USER, false)) {
1255 Log.w(LOG_TAG, "Cannot add user. DISALLOW_ADD_USER is enabled.");
1256 return null;
1257 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001258 if (ActivityManager.isLowRamDeviceStatic()) {
1259 return null;
1260 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07001261 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001262 final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001263 final long ident = Binder.clearCallingIdentity();
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001264 UserInfo userInfo = null;
Amith Yamasanibb054c92015-07-09 14:16:27 -07001265 final int userId;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001266 try {
1267 synchronized (mInstallLock) {
1268 synchronized (mPackagesLock) {
Jessica Hummelbe81c802014-04-22 15:49:22 +01001269 UserInfo parent = null;
1270 if (parentId != UserHandle.USER_NULL) {
1271 parent = getUserInfoLocked(parentId);
1272 if (parent == null) return null;
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001273 }
Nicolas Prevotb8186812015-08-06 15:00:03 +01001274 if (isManagedProfile && !canAddMoreManagedProfiles(parentId)) {
1275 Log.e(LOG_TAG, "Cannot add more managed profiles for user " + parentId);
Nicolas Prevot12678a92015-05-13 12:15:03 -07001276 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}