blob: 4bfcb902fb652904006bdc899b9c9d059f4b8c5e [file] [log] [blame]
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
Xiaohui Chen594f2082015-08-18 11:04:20 -070019import android.annotation.NonNull;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070020import android.app.Activity;
Amith Yamasani2a003292012-08-14 18:25:45 -070021import android.app.ActivityManager;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070022import android.app.ActivityManagerNative;
23import android.app.IStopUserCallback;
Xiaohui Chen203243a2015-07-16 11:55:47 -070024import android.app.admin.DevicePolicyManager;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070025import android.content.BroadcastReceiver;
Amith Yamasani258848d2012-08-10 17:06:33 -070026import android.content.Context;
27import android.content.Intent;
Amith Yamasani1a7472e2013-07-02 11:17:30 -070028import android.content.pm.ApplicationInfo;
Amith Yamasani0b285492011-04-14 17:35:23 -070029import android.content.pm.PackageManager;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -080030import android.content.pm.PackageManager.NameNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070031import android.content.pm.UserInfo;
Amith Yamasanie928d7d2012-09-17 21:46:51 -070032import android.graphics.Bitmap;
Amith Yamasani258848d2012-08-10 17:06:33 -070033import android.os.Binder;
Amith Yamasanie4cf7342012-12-17 11:12:09 -080034import android.os.Bundle;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070035import android.os.Environment;
36import android.os.FileUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080037import android.os.Handler;
Amith Yamasani258848d2012-08-10 17:06:33 -070038import android.os.IUserManager;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -080039import android.os.Message;
Adrian Roos1bdff912015-02-17 15:51:35 +010040import android.os.ParcelFileDescriptor;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070041import android.os.Parcelable;
Amith Yamasani258848d2012-08-10 17:06:33 -070042import android.os.Process;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070043import android.os.RemoteException;
Jason Monk62062992014-05-06 09:55:28 -040044import android.os.ServiceManager;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070045import android.os.UserHandle;
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070046import android.os.UserManager;
Paul Crowley85e4e812015-05-19 12:42:00 +010047import android.os.storage.StorageManager;
Jeff Sharkey6dce4962015-07-03 18:08:41 -070048import android.os.storage.VolumeInfo;
49import android.system.ErrnoException;
50import android.system.Os;
51import android.system.OsConstants;
Amith Yamasani2a003292012-08-14 18:25:45 -070052import android.util.AtomicFile;
Amith Yamasani655d0e22013-06-12 14:19:10 -070053import android.util.Log;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070054import android.util.Slog;
55import android.util.SparseArray;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080056import android.util.SparseBooleanArray;
Amith Yamasani920ace02012-09-20 22:15:37 -070057import android.util.TimeUtils;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070058import android.util.Xml;
59
Fyodor Kupolovb5013302015-04-17 17:59:14 -070060import com.google.android.collect.Sets;
61
Fyodor Kupolov262f9952015-03-23 18:55:11 -070062import com.android.internal.annotations.VisibleForTesting;
Jason Monk62062992014-05-06 09:55:28 -040063import com.android.internal.app.IAppOpsService;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080064import com.android.internal.util.ArrayUtils;
65import com.android.internal.util.FastXmlSerializer;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070066import com.android.internal.util.XmlUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080067
68import org.xmlpull.v1.XmlPullParser;
69import org.xmlpull.v1.XmlPullParserException;
70import org.xmlpull.v1.XmlSerializer;
71
Amith Yamasani4b2e9342011-03-31 12:38:53 -070072import java.io.BufferedOutputStream;
73import java.io.File;
Amith Yamasani920ace02012-09-20 22:15:37 -070074import java.io.FileDescriptor;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070075import java.io.FileInputStream;
Amith Yamasanib8151ec2012-04-18 18:02:48 -070076import java.io.FileNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070077import java.io.FileOutputStream;
78import java.io.IOException;
Amith Yamasani920ace02012-09-20 22:15:37 -070079import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +010080import java.nio.charset.StandardCharsets;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070081import java.util.ArrayList;
82import java.util.List;
Fyodor Kupolovb5013302015-04-17 17:59:14 -070083import java.util.Set;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070084
Fyodor Kupolov262f9952015-03-23 18:55:11 -070085import libcore.io.IoUtils;
86
Amith Yamasani258848d2012-08-10 17:06:33 -070087public class UserManagerService extends IUserManager.Stub {
Amith Yamasanib8151ec2012-04-18 18:02:48 -070088
Amith Yamasani2a003292012-08-14 18:25:45 -070089 private static final String LOG_TAG = "UserManagerService";
Amith Yamasanib8151ec2012-04-18 18:02:48 -070090
Amith Yamasani16389312012-10-17 21:20:14 -070091 private static final boolean DBG = false;
92
Amith Yamasani4b2e9342011-03-31 12:38:53 -070093 private static final String TAG_NAME = "name";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070094 private static final String ATTR_FLAGS = "flags";
Amith Yamasanib8151ec2012-04-18 18:02:48 -070095 private static final String ATTR_ICON_PATH = "icon";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070096 private static final String ATTR_ID = "id";
Amith Yamasani920ace02012-09-20 22:15:37 -070097 private static final String ATTR_CREATION_TIME = "created";
98 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
Amith Yamasani2a003292012-08-14 18:25:45 -070099 private static final String ATTR_SERIAL_NO = "serialNumber";
100 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700101 private static final String ATTR_PARTIAL = "partial";
Adam Lesinskieddeb492014-09-08 17:50:03 -0700102 private static final String ATTR_GUEST_TO_REMOVE = "guestToRemove";
Amith Yamasani6f34b412012-10-22 18:19:27 -0700103 private static final String ATTR_USER_VERSION = "version";
Kenny Guy2a764942014-04-02 13:29:20 +0100104 private static final String ATTR_PROFILE_GROUP_ID = "profileGroupId";
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530105 private static final String TAG_GUEST_RESTRICTIONS = "guestRestrictions";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700106 private static final String TAG_USERS = "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700107 private static final String TAG_USER = "user";
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800108 private static final String TAG_RESTRICTIONS = "restrictions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800109 private static final String TAG_ENTRY = "entry";
110 private static final String TAG_VALUE = "value";
111 private static final String ATTR_KEY = "key";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700112 private static final String ATTR_VALUE_TYPE = "type";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800113 private static final String ATTR_MULTIPLE = "m";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700114
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700115 private static final String ATTR_TYPE_STRING_ARRAY = "sa";
116 private static final String ATTR_TYPE_STRING = "s";
117 private static final String ATTR_TYPE_BOOLEAN = "b";
Amith Yamasani5b5aa402014-06-01 20:10:14 -0700118 private static final String ATTR_TYPE_INTEGER = "i";
Fyodor Kupolov262f9952015-03-23 18:55:11 -0700119 private static final String ATTR_TYPE_BUNDLE = "B";
120 private static final String ATTR_TYPE_BUNDLE_ARRAY = "BA";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700121
Amith Yamasani0b285492011-04-14 17:35:23 -0700122 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700123 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700124 private static final String USER_PHOTO_FILENAME = "photo.png";
Adrian Roos1bdff912015-02-17 15:51:35 +0100125 private static final String USER_PHOTO_FILENAME_TMP = USER_PHOTO_FILENAME + ".tmp";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700126
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800127 private static final String RESTRICTIONS_FILE_PREFIX = "res_";
Amith Yamasanifc95e702013-09-26 13:20:17 -0700128 private static final String XML_SUFFIX = ".xml";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800129
Amith Yamasani634cf312012-10-04 17:34:21 -0700130 private static final int MIN_USER_ID = 10;
131
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700132 private static final int USER_VERSION = 5;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700133
Amith Yamasani920ace02012-09-20 22:15:37 -0700134 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
135
Nicolas Prevotb8186812015-08-06 15:00:03 +0100136 // Maximum number of managed profiles permitted per user is 1. This cannot be increased
Amith Yamasani95ab7842014-08-11 17:09:26 -0700137 // without first making sure that the rest of the framework is prepared for it.
138 private static final int MAX_MANAGED_PROFILES = 1;
139
Andres Moralesc5548c02015-08-05 10:23:12 -0700140 /**
141 * Flag indicating whether device credentials are shared among same-user profiles.
142 */
143 private static final boolean CONFIG_PROFILES_SHARE_CREDENTIAL = true;
144
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700145 // Set of user restrictions, which can only be enforced by the system
146 private static final Set<String> SYSTEM_CONTROLLED_RESTRICTIONS = Sets.newArraySet(
147 UserManager.DISALLOW_RECORD_AUDIO);
148
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800149 static final int WRITE_USER_MSG = 1;
150 static final int WRITE_USER_DELAY = 2*1000; // 2 seconds
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530151
Jeff Sharkey6dce4962015-07-03 18:08:41 -0700152 private static final String XATTR_SERIAL = "user.serial";
153
Dianne Hackborn4428e172012-08-24 17:43:05 -0700154 private final Context mContext;
155 private final PackageManagerService mPm;
156 private final Object mInstallLock;
157 private final Object mPackagesLock;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700158
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800159 private final Handler mHandler;
160
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700161 private final File mUsersDir;
162 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700163
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800164 private final SparseArray<UserInfo> mUsers = new SparseArray<UserInfo>();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800165 private final SparseArray<Bundle> mUserRestrictions = new SparseArray<Bundle>();
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530166 private final Bundle mGuestRestrictions = new Bundle();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800167
168 /**
169 * Set of user IDs being actively removed. Removed IDs linger in this set
170 * for several seconds to work around a VFS caching issue.
171 */
172 // @GuardedBy("mPackagesLock")
173 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700174
Amith Yamasani0b285492011-04-14 17:35:23 -0700175 private int[] mUserIds;
Amith Yamasani2a003292012-08-14 18:25:45 -0700176 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700177 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700178
Jason Monk62062992014-05-06 09:55:28 -0400179 private IAppOpsService mAppOpsService;
180
Amith Yamasani258848d2012-08-10 17:06:33 -0700181 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700182
Dianne Hackborn4428e172012-08-24 17:43:05 -0700183 public static UserManagerService getInstance() {
184 synchronized (UserManagerService.class) {
185 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700186 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700187 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700188
189 /**
190 * Available for testing purposes.
191 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700192 UserManagerService(File dataDir, File baseUserPath) {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700193 this(null, null, new Object(), new Object(), dataDir, baseUserPath);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700194 }
195
Dianne Hackborn4428e172012-08-24 17:43:05 -0700196 /**
197 * Called by package manager to create the service. This is closely
198 * associated with the package manager, and the given lock is the
199 * package manager's own lock.
200 */
201 UserManagerService(Context context, PackageManagerService pm,
202 Object installLock, Object packagesLock) {
203 this(context, pm, installLock, packagesLock,
204 Environment.getDataDirectory(),
205 new File(Environment.getDataDirectory(), "user"));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700206 }
207
Dianne Hackborn4428e172012-08-24 17:43:05 -0700208 /**
209 * Available for testing purposes.
210 */
211 private UserManagerService(Context context, PackageManagerService pm,
212 Object installLock, Object packagesLock,
213 File dataDir, File baseUserPath) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700214 mContext = context;
215 mPm = pm;
216 mInstallLock = installLock;
217 mPackagesLock = packagesLock;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800218 mHandler = new MainHandler();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700219 synchronized (mInstallLock) {
220 synchronized (mPackagesLock) {
221 mUsersDir = new File(dataDir, USER_INFO_DIR);
222 mUsersDir.mkdirs();
223 // Make zeroth user directory, for services to migrate their files to that location
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700224 File userZeroDir = new File(mUsersDir, String.valueOf(UserHandle.USER_SYSTEM));
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700225 userZeroDir.mkdirs();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700226 FileUtils.setPermissions(mUsersDir.toString(),
227 FileUtils.S_IRWXU|FileUtils.S_IRWXG
228 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
229 -1, -1);
230 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
Amith Yamasanida0b1682014-11-21 12:58:17 -0800231 initDefaultGuestRestrictions();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700232 readUserListLocked();
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700233 sInstance = this;
234 }
235 }
236 }
237
238 void systemReady() {
239 synchronized (mInstallLock) {
240 synchronized (mPackagesLock) {
Amith Yamasani756901d2012-10-12 12:30:07 -0700241 // Prune out any partially created/partially removed users.
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700242 ArrayList<UserInfo> partials = new ArrayList<UserInfo>();
243 for (int i = 0; i < mUsers.size(); i++) {
244 UserInfo ui = mUsers.valueAt(i);
Adam Lesinskieddeb492014-09-08 17:50:03 -0700245 if ((ui.partial || ui.guestToRemove) && i != 0) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700246 partials.add(ui);
247 }
248 }
249 for (int i = 0; i < partials.size(); i++) {
250 UserInfo ui = partials.get(i);
Amith Yamasania7892482015-08-07 11:09:05 -0700251 Slog.w(LOG_TAG, "Removing partially created user " + ui.id
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700252 + " (name=" + ui.name + ")");
253 removeUserStateLocked(ui.id);
254 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700255 }
Dianne Hackborn4428e172012-08-24 17:43:05 -0700256 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700257 onUserForeground(UserHandle.USER_SYSTEM);
Jason Monk62062992014-05-06 09:55:28 -0400258 mAppOpsService = IAppOpsService.Stub.asInterface(
259 ServiceManager.getService(Context.APP_OPS_SERVICE));
260 for (int i = 0; i < mUserIds.length; ++i) {
261 try {
262 mAppOpsService.setUserRestrictions(mUserRestrictions.get(mUserIds[i]), mUserIds[i]);
263 } catch (RemoteException e) {
264 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
265 }
266 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700267 }
268
269 @Override
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700270 public UserInfo getPrimaryUser() {
271 checkManageUsersPermission("query users");
272 synchronized (mPackagesLock) {
273 for (int i = 0; i < mUsers.size(); i++) {
274 UserInfo ui = mUsers.valueAt(i);
275 if (ui.isPrimary()) {
276 return ui;
277 }
278 }
279 }
280 return null;
281 }
282
283 @Override
Xiaohui Chen594f2082015-08-18 11:04:20 -0700284 public @NonNull List<UserInfo> getUsers(boolean excludeDying) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700285 checkManageUsersPermission("query users");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700286 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700287 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
288 for (int i = 0; i < mUsers.size(); i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700289 UserInfo ui = mUsers.valueAt(i);
290 if (ui.partial) {
291 continue;
292 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800293 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700294 users.add(ui);
Amith Yamasani920ace02012-09-20 22:15:37 -0700295 }
Amith Yamasani13593602012-03-22 16:16:17 -0700296 }
297 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700298 }
Amith Yamasani13593602012-03-22 16:16:17 -0700299 }
300
Amith Yamasani258848d2012-08-10 17:06:33 -0700301 @Override
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100302 public List<UserInfo> getProfiles(int userId, boolean enabledOnly) {
Amith Yamasani4f582632014-02-19 14:31:52 -0800303 if (userId != UserHandle.getCallingUserId()) {
304 checkManageUsersPermission("getting profiles related to user " + userId);
305 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700306 final long ident = Binder.clearCallingIdentity();
307 try {
308 synchronized (mPackagesLock) {
309 return getProfilesLocked(userId, enabledOnly);
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100310 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700311 } finally {
312 Binder.restoreCallingIdentity(ident);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000313 }
314 }
315
Amith Yamasanibe465322014-04-24 13:45:17 -0700316 /** Assume permissions already checked and caller's identity cleared */
317 private List<UserInfo> getProfilesLocked(int userId, boolean enabledOnly) {
Amith Yamasanibe465322014-04-24 13:45:17 -0700318 UserInfo user = getUserInfoLocked(userId);
319 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasanidda003f2014-08-28 18:06:51 -0700320 if (user == null) {
321 // Probably a dying user
322 return users;
323 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700324 for (int i = 0; i < mUsers.size(); i++) {
325 UserInfo profile = mUsers.valueAt(i);
326 if (!isProfileOf(user, profile)) {
327 continue;
328 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100329 if (enabledOnly && !profile.isEnabled()) {
330 continue;
Amith Yamasanibe465322014-04-24 13:45:17 -0700331 }
Amith Yamasani70fcf0c2014-07-11 08:40:19 -0700332 if (mRemovingUserIds.get(profile.id)) {
333 continue;
334 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700335 users.add(profile);
336 }
337 return users;
338 }
339
Jessica Hummelbe81c802014-04-22 15:49:22 +0100340 @Override
Andres Moralesc5548c02015-08-05 10:23:12 -0700341 public int getCredentialOwnerProfile(int userHandle) {
342 checkManageUsersPermission("get the credential owner");
343 if (CONFIG_PROFILES_SHARE_CREDENTIAL) {
344 synchronized (mPackagesLock) {
345 UserInfo profileParent = getProfileParentLocked(userHandle);
346 if (profileParent != null) {
347 return profileParent.id;
348 }
349 }
350 }
351
352 return userHandle;
353 }
354
355 @Override
Jessica Hummelbe81c802014-04-22 15:49:22 +0100356 public UserInfo getProfileParent(int userHandle) {
357 checkManageUsersPermission("get the profile parent");
358 synchronized (mPackagesLock) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700359 return getProfileParentLocked(userHandle);
360 }
361 }
362
363 private UserInfo getProfileParentLocked(int userHandle) {
364 UserInfo profile = getUserInfoLocked(userHandle);
365 if (profile == null) {
366 return null;
367 }
368 int parentUserId = profile.profileGroupId;
369 if (parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
370 return null;
371 } else {
372 return getUserInfoLocked(parentUserId);
Jessica Hummelbe81c802014-04-22 15:49:22 +0100373 }
374 }
375
Kenny Guy2a764942014-04-02 13:29:20 +0100376 private boolean isProfileOf(UserInfo user, UserInfo profile) {
377 return user.id == profile.id ||
378 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
379 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000380 }
381
382 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100383 public void setUserEnabled(int userId) {
384 checkManageUsersPermission("enable user");
385 synchronized (mPackagesLock) {
386 UserInfo info = getUserInfoLocked(userId);
387 if (info != null && !info.isEnabled()) {
388 info.flags ^= UserInfo.FLAG_DISABLED;
389 writeUserLocked(info);
390 }
391 }
392 }
393
394 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700395 public UserInfo getUserInfo(int userId) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700396 checkManageUsersPermission("query user");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700397 synchronized (mPackagesLock) {
Amith Yamasani195263742012-08-21 15:40:12 -0700398 return getUserInfoLocked(userId);
Amith Yamasani13593602012-03-22 16:16:17 -0700399 }
400 }
401
Amith Yamasani71e6c692013-03-24 17:39:28 -0700402 @Override
403 public boolean isRestricted() {
404 synchronized (mPackagesLock) {
405 return getUserInfoLocked(UserHandle.getCallingUserId()).isRestricted();
406 }
407 }
408
Amith Yamasani195263742012-08-21 15:40:12 -0700409 /*
410 * Should be locked on mUsers before calling this.
411 */
412 private UserInfo getUserInfoLocked(int userId) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700413 UserInfo ui = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -0700414 // If it is partial and not in the process of being removed, return as unknown user.
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800415 if (ui != null && ui.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700416 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
417 return null;
418 }
419 return ui;
Amith Yamasani195263742012-08-21 15:40:12 -0700420 }
421
Amith Yamasani236b2b52015-08-18 14:32:14 -0700422 /** Called by PackageManagerService */
Amith Yamasani13593602012-03-22 16:16:17 -0700423 public boolean exists(int userId) {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700424 synchronized (mPackagesLock) {
Amith Yamasani236b2b52015-08-18 14:32:14 -0700425 return mUsers.get(userId) != null;
Amith Yamasani13593602012-03-22 16:16:17 -0700426 }
427 }
428
Amith Yamasani258848d2012-08-10 17:06:33 -0700429 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700430 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700431 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700432 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700433 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700434 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700435 if (info == null || info.partial) {
436 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
437 return;
438 }
Amith Yamasani13593602012-03-22 16:16:17 -0700439 if (name != null && !name.equals(info.name)) {
440 info.name = name;
441 writeUserLocked(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700442 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -0700443 }
444 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700445 if (changed) {
446 sendUserInfoChangedBroadcast(userId);
447 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700448 }
449
Amith Yamasani258848d2012-08-10 17:06:33 -0700450 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700451 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700452 checkManageUsersPermission("update users");
Jason Monk9a944532014-07-08 09:31:21 -0400453 long ident = Binder.clearCallingIdentity();
454 try {
455 synchronized (mPackagesLock) {
456 UserInfo info = mUsers.get(userId);
457 if (info == null || info.partial) {
458 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
459 return;
460 }
461 writeBitmapLocked(info, bitmap);
462 writeUserLocked(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700463 }
Jason Monk9a944532014-07-08 09:31:21 -0400464 sendUserInfoChangedBroadcast(userId);
465 } finally {
466 Binder.restoreCallingIdentity(ident);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700467 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700468 }
469
470 private void sendUserInfoChangedBroadcast(int userId) {
471 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
472 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
473 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -0700474 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700475 }
476
Amith Yamasani258848d2012-08-10 17:06:33 -0700477 @Override
Adrian Roos1bdff912015-02-17 15:51:35 +0100478 public ParcelFileDescriptor getUserIcon(int userId) {
479 String iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700480 synchronized (mPackagesLock) {
481 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700482 if (info == null || info.partial) {
483 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + userId);
484 return null;
485 }
Nicolas Prevot88cc3462014-05-14 14:51:48 +0100486 int callingGroupId = mUsers.get(UserHandle.getCallingUserId()).profileGroupId;
487 if (callingGroupId == UserInfo.NO_PROFILE_GROUP_ID
488 || callingGroupId != info.profileGroupId) {
489 checkManageUsersPermission("get the icon of a user who is not related");
490 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700491 if (info.iconPath == null) {
492 return null;
493 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100494 iconPath = info.iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700495 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100496
497 try {
498 return ParcelFileDescriptor.open(
499 new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
500 } catch (FileNotFoundException e) {
501 Log.e(LOG_TAG, "Couldn't find icon file", e);
502 }
503 return null;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700504 }
505
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700506 public void makeInitialized(int userId) {
507 checkManageUsersPermission("makeInitialized");
508 synchronized (mPackagesLock) {
509 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700510 if (info == null || info.partial) {
511 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
512 }
513 if ((info.flags&UserInfo.FLAG_INITIALIZED) == 0) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700514 info.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800515 scheduleWriteUserLocked(info);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700516 }
517 }
518 }
519
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700520 /**
521 * If default guest restrictions haven't been initialized yet, add the basic
522 * restrictions.
523 */
524 private void initDefaultGuestRestrictions() {
525 if (mGuestRestrictions.isEmpty()) {
526 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
Amith Yamasanida0b1682014-11-21 12:58:17 -0800527 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700528 }
529 }
530
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800531 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530532 public Bundle getDefaultGuestRestrictions() {
533 checkManageUsersPermission("getDefaultGuestRestrictions");
534 synchronized (mPackagesLock) {
535 return new Bundle(mGuestRestrictions);
536 }
537 }
538
539 @Override
540 public void setDefaultGuestRestrictions(Bundle restrictions) {
541 checkManageUsersPermission("setDefaultGuestRestrictions");
542 synchronized (mPackagesLock) {
543 mGuestRestrictions.clear();
544 mGuestRestrictions.putAll(restrictions);
545 writeUserListLocked();
546 }
547 }
548
549 @Override
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700550 public boolean hasUserRestriction(String restrictionKey, int userId) {
551 synchronized (mPackagesLock) {
552 Bundle restrictions = mUserRestrictions.get(userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700553 return restrictions != null && restrictions.getBoolean(restrictionKey);
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700554 }
555 }
556
557 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800558 public Bundle getUserRestrictions(int userId) {
559 // checkManageUsersPermission("getUserRestrictions");
560
561 synchronized (mPackagesLock) {
562 Bundle restrictions = mUserRestrictions.get(userId);
Amith Yamasanibe465322014-04-24 13:45:17 -0700563 return restrictions != null ? new Bundle(restrictions) : new Bundle();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800564 }
565 }
566
567 @Override
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700568 public void setUserRestriction(String key, boolean value, int userId) {
Fyodor Kupolovd4b26042015-07-27 14:30:59 -0700569 checkManageUsersPermission("setUserRestriction");
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700570 synchronized (mPackagesLock) {
571 if (!SYSTEM_CONTROLLED_RESTRICTIONS.contains(key)) {
572 Bundle restrictions = getUserRestrictions(userId);
573 restrictions.putBoolean(key, value);
574 setUserRestrictionsInternalLocked(restrictions, userId);
575 }
576 }
577 }
578
579 @Override
580 public void setSystemControlledUserRestriction(String key, boolean value, int userId) {
581 checkSystemOrRoot("setSystemControlledUserRestriction");
582 synchronized (mPackagesLock) {
583 Bundle restrictions = getUserRestrictions(userId);
584 restrictions.putBoolean(key, value);
585 setUserRestrictionsInternalLocked(restrictions, userId);
586 }
587 }
588
589 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800590 public void setUserRestrictions(Bundle restrictions, int userId) {
Amith Yamasanibe465322014-04-24 13:45:17 -0700591 checkManageUsersPermission("setUserRestrictions");
Amith Yamasani0343ec32013-07-22 14:52:06 -0700592 if (restrictions == null) return;
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800593
594 synchronized (mPackagesLock) {
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700595 final Bundle oldUserRestrictions = mUserRestrictions.get(userId);
596 // Restore the original state of system controlled restrictions from oldUserRestrictions
597 for (String key : SYSTEM_CONTROLLED_RESTRICTIONS) {
598 restrictions.remove(key);
599 if (oldUserRestrictions.containsKey(key)) {
600 restrictions.putBoolean(key, oldUserRestrictions.getBoolean(key));
601 }
Jason Monk62062992014-05-06 09:55:28 -0400602 }
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700603 setUserRestrictionsInternalLocked(restrictions, userId);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800604 }
605 }
606
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700607 private void setUserRestrictionsInternalLocked(Bundle restrictions, int userId) {
608 final Bundle userRestrictions = mUserRestrictions.get(userId);
609 userRestrictions.clear();
610 userRestrictions.putAll(restrictions);
611 long token = Binder.clearCallingIdentity();
612 try {
613 mAppOpsService.setUserRestrictions(userRestrictions, userId);
614 } catch (RemoteException e) {
615 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
616 } finally {
617 Binder.restoreCallingIdentity(token);
618 }
619 scheduleWriteUserLocked(mUsers.get(userId));
620 }
621
Amith Yamasani258848d2012-08-10 17:06:33 -0700622 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700623 * Check if we've hit the limit of how many users can be created.
624 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700625 private boolean isUserLimitReachedLocked() {
Nicolas Prevot12678a92015-05-13 12:15:03 -0700626 return getAliveUsersExcludingGuestsCountLocked() >= UserManager.getMaxSupportedUsers();
627 }
628
629 @Override
Nicolas Prevotb8186812015-08-06 15:00:03 +0100630 public boolean canAddMoreManagedProfiles(int userId) {
Nicolas Prevot12678a92015-05-13 12:15:03 -0700631 checkManageUsersPermission("check if more managed profiles can be added.");
632 if (ActivityManager.isLowRamDeviceStatic()) {
633 return false;
634 }
Fyodor Kupolovb6157992015-06-05 15:32:28 -0700635 if (!mContext.getPackageManager().hasSystemFeature(
636 PackageManager.FEATURE_MANAGED_USERS)) {
637 return false;
638 }
Nicolas Prevotb8186812015-08-06 15:00:03 +0100639 // Limit number of managed profiles that can be created
640 int managedProfilesCount = getProfiles(userId, true).size() - 1;
641 if (managedProfilesCount >= MAX_MANAGED_PROFILES) {
642 return false;
643 }
Nicolas Prevot12678a92015-05-13 12:15:03 -0700644 synchronized(mPackagesLock) {
Nicolas Prevotb8186812015-08-06 15:00:03 +0100645 UserInfo userInfo = getUserInfoLocked(userId);
646 if (!userInfo.canHaveProfile()) {
Nicolas Prevot12678a92015-05-13 12:15:03 -0700647 return false;
648 }
649 int usersCount = getAliveUsersExcludingGuestsCountLocked();
650 // We allow creating a managed profile in the special case where there is only one user.
651 return usersCount == 1 || usersCount < UserManager.getMaxSupportedUsers();
652 }
653 }
654
655 private int getAliveUsersExcludingGuestsCountLocked() {
Amith Yamasanif584f012014-05-19 17:57:25 -0700656 int aliveUserCount = 0;
657 final int totalUserCount = mUsers.size();
658 // Skip over users being removed
659 for (int i = 0; i < totalUserCount; i++) {
660 UserInfo user = mUsers.valueAt(i);
Amith Yamasani95ab7842014-08-11 17:09:26 -0700661 if (!mRemovingUserIds.get(user.id)
Amith Yamasani1df14732014-08-29 21:37:27 -0700662 && !user.isGuest() && !user.partial) {
Amith Yamasanif584f012014-05-19 17:57:25 -0700663 aliveUserCount++;
664 }
665 }
Nicolas Prevot12678a92015-05-13 12:15:03 -0700666 return aliveUserCount;
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700667 }
668
669 /**
Amith Yamasani195263742012-08-21 15:40:12 -0700670 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -0700671 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -0700672 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -0700673 *
674 * @param message used as message if SecurityException is thrown
675 * @throws SecurityException if the caller is not system or root
676 */
Amith Yamasanibe465322014-04-24 13:45:17 -0700677 private static final void checkManageUsersPermission(String message) {
Amith Yamasani258848d2012-08-10 17:06:33 -0700678 final int uid = Binder.getCallingUid();
Amith Yamasanibe465322014-04-24 13:45:17 -0700679 if (uid != Process.SYSTEM_UID && uid != 0
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400680 && ActivityManager.checkComponentPermission(
681 android.Manifest.permission.MANAGE_USERS,
Amith Yamasanibe465322014-04-24 13:45:17 -0700682 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
683 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
684 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400685 }
686
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700687 private static void checkSystemOrRoot(String message) {
688 final int uid = Binder.getCallingUid();
689 if (uid != Process.SYSTEM_UID && uid != 0) {
690 throw new SecurityException("Only system may call: " + message);
691 }
692 }
693
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700694 private void writeBitmapLocked(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700695 try {
696 File dir = new File(mUsersDir, Integer.toString(info.id));
697 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +0100698 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700699 if (!dir.exists()) {
700 dir.mkdir();
701 FileUtils.setPermissions(
702 dir.getPath(),
703 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
704 -1, -1);
705 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700706 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +0100707 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
708 && tmp.renameTo(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -0700709 info.iconPath = file.getAbsolutePath();
710 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700711 try {
712 os.close();
713 } catch (IOException ioe) {
714 // What the ... !
715 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100716 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700717 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700718 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700719 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700720 }
721
Amith Yamasani0b285492011-04-14 17:35:23 -0700722 /**
723 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
724 * cache it elsewhere.
725 * @return the array of user ids.
726 */
Dianne Hackborn1676c852012-09-10 14:52:30 -0700727 public int[] getUserIds() {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700728 synchronized (mPackagesLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700729 return mUserIds;
730 }
Amith Yamasani0b285492011-04-14 17:35:23 -0700731 }
732
Dianne Hackborn4428e172012-08-24 17:43:05 -0700733 int[] getUserIdsLPr() {
734 return mUserIds;
735 }
736
Amith Yamasani13593602012-03-22 16:16:17 -0700737 private void readUserListLocked() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700738 if (!mUserListFile.exists()) {
Amith Yamasani13593602012-03-22 16:16:17 -0700739 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700740 return;
741 }
742 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700743 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700744 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700745 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700746 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100747 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700748 int type;
749 while ((type = parser.next()) != XmlPullParser.START_TAG
750 && type != XmlPullParser.END_DOCUMENT) {
751 ;
752 }
753
754 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700755 Slog.e(LOG_TAG, "Unable to read user list");
Amith Yamasani13593602012-03-22 16:16:17 -0700756 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700757 return;
758 }
759
Amith Yamasani2a003292012-08-14 18:25:45 -0700760 mNextSerialNumber = -1;
761 if (parser.getName().equals(TAG_USERS)) {
762 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
763 if (lastSerialNumber != null) {
764 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
765 }
Amith Yamasani6f34b412012-10-22 18:19:27 -0700766 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
767 if (versionNumber != null) {
768 mUserVersion = Integer.parseInt(versionNumber);
769 }
Amith Yamasani2a003292012-08-14 18:25:45 -0700770 }
771
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700772 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530773 if (type == XmlPullParser.START_TAG) {
774 final String name = parser.getName();
775 if (name.equals(TAG_USER)) {
776 String id = parser.getAttributeValue(null, ATTR_ID);
777 UserInfo user = readUserLocked(Integer.parseInt(id));
Amith Yamasani6f34b412012-10-22 18:19:27 -0700778
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530779 if (user != null) {
780 mUsers.put(user.id, user);
781 if (mNextSerialNumber < 0 || mNextSerialNumber <= user.id) {
782 mNextSerialNumber = user.id + 1;
783 }
Amith Yamasani2a003292012-08-14 18:25:45 -0700784 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530785 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -0800786 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
787 && type != XmlPullParser.END_TAG) {
788 if (type == XmlPullParser.START_TAG) {
789 if (parser.getName().equals(TAG_RESTRICTIONS)) {
790 readRestrictionsLocked(parser, mGuestRestrictions);
791 }
792 break;
793 }
794 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700795 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700796 }
797 }
Amith Yamasani13593602012-03-22 16:16:17 -0700798 updateUserIdsLocked();
Amith Yamasani350962c2013-08-06 11:18:53 -0700799 upgradeIfNecessaryLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700800 } catch (IOException ioe) {
Amith Yamasani13593602012-03-22 16:16:17 -0700801 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700802 } catch (XmlPullParserException pe) {
Amith Yamasani13593602012-03-22 16:16:17 -0700803 fallbackToSingleUserLocked();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -0800804 } finally {
805 if (fis != null) {
806 try {
807 fis.close();
808 } catch (IOException e) {
809 }
810 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700811 }
812 }
813
Amith Yamasani6f34b412012-10-22 18:19:27 -0700814 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -0800815 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -0700816 */
Amith Yamasani350962c2013-08-06 11:18:53 -0700817 private void upgradeIfNecessaryLocked() {
Amith Yamasani6f34b412012-10-22 18:19:27 -0700818 int userVersion = mUserVersion;
819 if (userVersion < 1) {
820 // Assign a proper name for the owner, if not initialized correctly before
821 UserInfo user = mUsers.get(UserHandle.USER_OWNER);
822 if ("Primary".equals(user.name)) {
823 user.name = mContext.getResources().getString(com.android.internal.R.string.owner_name);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800824 scheduleWriteUserLocked(user);
Amith Yamasani6f34b412012-10-22 18:19:27 -0700825 }
826 userVersion = 1;
827 }
828
Amith Yamasanibc9625052012-11-15 14:39:18 -0800829 if (userVersion < 2) {
830 // Owner should be marked as initialized
831 UserInfo user = mUsers.get(UserHandle.USER_OWNER);
832 if ((user.flags & UserInfo.FLAG_INITIALIZED) == 0) {
833 user.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800834 scheduleWriteUserLocked(user);
Amith Yamasanibc9625052012-11-15 14:39:18 -0800835 }
836 userVersion = 2;
837 }
838
Amith Yamasani350962c2013-08-06 11:18:53 -0700839
Amith Yamasani5e486f52013-08-07 11:06:44 -0700840 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -0700841 userVersion = 4;
842 }
843
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700844 if (userVersion < 5) {
845 initDefaultGuestRestrictions();
846 userVersion = 5;
847 }
848
Amith Yamasani6f34b412012-10-22 18:19:27 -0700849 if (userVersion < USER_VERSION) {
850 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
851 + USER_VERSION);
852 } else {
853 mUserVersion = userVersion;
854 writeUserListLocked();
855 }
856 }
857
Amith Yamasani13593602012-03-22 16:16:17 -0700858 private void fallbackToSingleUserLocked() {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -0700859 int flags = UserInfo.FLAG_INITIALIZED;
860 // In split system user mode, the admin and primary flags are assigned to the first human
861 // user.
862 if (!UserManager.isSplitSystemUser()) {
863 flags |= UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY;
864 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700865 // Create the system user
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700866 UserInfo system = new UserInfo(UserHandle.USER_SYSTEM,
Amith Yamasani6f34b412012-10-22 18:19:27 -0700867 mContext.getResources().getString(com.android.internal.R.string.owner_name), null,
Xiaohui Chenb31e14a2015-07-13 16:04:55 -0700868 flags);
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700869 mUsers.put(system.id, system);
Amith Yamasani634cf312012-10-04 17:34:21 -0700870 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -0400871 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -0800872
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -0500873 Bundle restrictions = new Bundle();
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700874 mUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions);
Amith Yamasani67df64b2012-12-14 12:09:36 -0800875
Amith Yamasani13593602012-03-22 16:16:17 -0700876 updateUserIdsLocked();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700877 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700878
Amith Yamasani13593602012-03-22 16:16:17 -0700879 writeUserListLocked();
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700880 writeUserLocked(system);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700881 }
882
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800883 private void scheduleWriteUserLocked(UserInfo userInfo) {
884 if (!mHandler.hasMessages(WRITE_USER_MSG, userInfo)) {
885 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, userInfo);
886 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
887 }
888 }
889
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700890 /*
891 * Writes the user file in this format:
892 *
893 * <user flags="20039023" id="0">
894 * <name>Primary</name>
895 * </user>
896 */
Amith Yamasani13593602012-03-22 16:16:17 -0700897 private void writeUserLocked(UserInfo userInfo) {
Amith Yamasani742a6712011-05-04 14:49:28 -0700898 FileOutputStream fos = null;
Amith Yamasanifc95e702013-09-26 13:20:17 -0700899 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userInfo.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700900 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700901 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700902 final BufferedOutputStream bos = new BufferedOutputStream(fos);
903
904 // XmlSerializer serializer = XmlUtils.serializerInstance();
905 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100906 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700907 serializer.startDocument(null, true);
908 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
909
910 serializer.startTag(null, TAG_USER);
911 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
Amith Yamasani2a003292012-08-14 18:25:45 -0700912 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700913 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Amith Yamasani920ace02012-09-20 22:15:37 -0700914 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
915 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
916 Long.toString(userInfo.lastLoggedInTime));
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700917 if (userInfo.iconPath != null) {
918 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
919 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700920 if (userInfo.partial) {
921 serializer.attribute(null, ATTR_PARTIAL, "true");
922 }
Adam Lesinskieddeb492014-09-08 17:50:03 -0700923 if (userInfo.guestToRemove) {
924 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
925 }
Kenny Guy2a764942014-04-02 13:29:20 +0100926 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
927 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
928 Integer.toString(userInfo.profileGroupId));
Kenny Guya52dc3e2014-02-11 15:33:14 +0000929 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700930
931 serializer.startTag(null, TAG_NAME);
932 serializer.text(userInfo.name);
933 serializer.endTag(null, TAG_NAME);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800934 Bundle restrictions = mUserRestrictions.get(userInfo.id);
935 if (restrictions != null) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530936 writeRestrictionsLocked(serializer, restrictions);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800937 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700938 serializer.endTag(null, TAG_USER);
939
940 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -0700941 userFile.finishWrite(fos);
942 } catch (Exception ioe) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700943 Slog.e(LOG_TAG, "Error writing user info " + userInfo.id + "\n" + ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -0700944 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700945 }
946 }
947
948 /*
949 * Writes the user list file in this format:
950 *
Amith Yamasani2a003292012-08-14 18:25:45 -0700951 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700952 * <user id="0"></user>
953 * <user id="2"></user>
954 * </users>
955 */
Amith Yamasani13593602012-03-22 16:16:17 -0700956 private void writeUserListLocked() {
Amith Yamasani742a6712011-05-04 14:49:28 -0700957 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700958 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700959 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700960 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700961 final BufferedOutputStream bos = new BufferedOutputStream(fos);
962
963 // XmlSerializer serializer = XmlUtils.serializerInstance();
964 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100965 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700966 serializer.startDocument(null, true);
967 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
968
969 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -0700970 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -0700971 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700972
Adam Lesinskieddeb492014-09-08 17:50:03 -0700973 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530974 writeRestrictionsLocked(serializer, mGuestRestrictions);
975 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700976 for (int i = 0; i < mUsers.size(); i++) {
977 UserInfo user = mUsers.valueAt(i);
978 serializer.startTag(null, TAG_USER);
979 serializer.attribute(null, ATTR_ID, Integer.toString(user.id));
980 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700981 }
982
983 serializer.endTag(null, TAG_USERS);
984
985 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -0700986 userListFile.finishWrite(fos);
987 } catch (Exception e) {
988 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -0700989 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700990 }
991 }
992
Andres Moralesc5548c02015-08-05 10:23:12 -0700993 private void writeRestrictionsLocked(XmlSerializer serializer, Bundle restrictions)
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530994 throws IOException {
995 serializer.startTag(null, TAG_RESTRICTIONS);
996 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_WIFI);
997 writeBoolean(serializer, restrictions, UserManager.DISALLOW_MODIFY_ACCOUNTS);
998 writeBoolean(serializer, restrictions, UserManager.DISALLOW_INSTALL_APPS);
999 writeBoolean(serializer, restrictions, UserManager.DISALLOW_UNINSTALL_APPS);
1000 writeBoolean(serializer, restrictions, UserManager.DISALLOW_SHARE_LOCATION);
1001 writeBoolean(serializer, restrictions,
1002 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
1003 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_BLUETOOTH);
1004 writeBoolean(serializer, restrictions, UserManager.DISALLOW_USB_FILE_TRANSFER);
1005 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_CREDENTIALS);
1006 writeBoolean(serializer, restrictions, UserManager.DISALLOW_REMOVE_USER);
1007 writeBoolean(serializer, restrictions, UserManager.DISALLOW_DEBUGGING_FEATURES);
1008 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_VPN);
1009 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_TETHERING);
Stuart Scott94b038b2015-04-20 14:07:45 -07001010 writeBoolean(serializer, restrictions, UserManager.DISALLOW_NETWORK_RESET);
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301011 writeBoolean(serializer, restrictions, UserManager.DISALLOW_FACTORY_RESET);
1012 writeBoolean(serializer, restrictions, UserManager.DISALLOW_ADD_USER);
1013 writeBoolean(serializer, restrictions, UserManager.ENSURE_VERIFY_APPS);
1014 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_CELL_BROADCASTS);
1015 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS);
1016 writeBoolean(serializer, restrictions, UserManager.DISALLOW_APPS_CONTROL);
1017 writeBoolean(serializer, restrictions, UserManager.DISALLOW_MOUNT_PHYSICAL_MEDIA);
1018 writeBoolean(serializer, restrictions, UserManager.DISALLOW_UNMUTE_MICROPHONE);
1019 writeBoolean(serializer, restrictions, UserManager.DISALLOW_ADJUST_VOLUME);
Amith Yamasani390989d2014-07-17 10:52:03 -07001020 writeBoolean(serializer, restrictions, UserManager.DISALLOW_OUTGOING_CALLS);
1021 writeBoolean(serializer, restrictions, UserManager.DISALLOW_SMS);
Jeff Sharkey2cc03e52015-03-20 11:24:04 -07001022 writeBoolean(serializer, restrictions, UserManager.DISALLOW_FUN);
Jason Monk1c7c3192014-06-26 12:52:18 -04001023 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CREATE_WINDOWS);
Amith Yamasani26af8292014-09-09 09:57:27 -07001024 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CROSS_PROFILE_COPY_PASTE);
1025 writeBoolean(serializer, restrictions, UserManager.DISALLOW_OUTGOING_BEAM);
Benjamin Franzf3ece362015-02-11 10:51:10 +00001026 writeBoolean(serializer, restrictions, UserManager.DISALLOW_WALLPAPER);
Benjamin Franzbff46ba2015-03-05 18:33:51 +00001027 writeBoolean(serializer, restrictions, UserManager.DISALLOW_SAFE_BOOT);
Nicolas Prevotf0029c12015-06-25 14:25:41 -07001028 writeBoolean(serializer, restrictions, UserManager.ALLOW_PARENT_PROFILE_APP_LINKING);
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301029 serializer.endTag(null, TAG_RESTRICTIONS);
1030 }
1031
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001032 private UserInfo readUserLocked(int id) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001033 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -07001034 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001035 String name = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001036 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -07001037 long creationTime = 0L;
1038 long lastLoggedInTime = 0L;
Kenny Guy2a764942014-04-02 13:29:20 +01001039 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001040 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001041 boolean guestToRemove = false;
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001042 Bundle restrictions = new Bundle();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001043
1044 FileInputStream fis = null;
1045 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001046 AtomicFile userFile =
Amith Yamasanifc95e702013-09-26 13:20:17 -07001047 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
Amith Yamasani2a003292012-08-14 18:25:45 -07001048 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001049 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001050 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001051 int type;
1052 while ((type = parser.next()) != XmlPullParser.START_TAG
1053 && type != XmlPullParser.END_DOCUMENT) {
1054 ;
1055 }
1056
1057 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001058 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001059 return null;
1060 }
1061
1062 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001063 int storedId = readIntAttribute(parser, ATTR_ID, -1);
1064 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001065 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001066 return null;
1067 }
Amith Yamasani920ace02012-09-20 22:15:37 -07001068 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
1069 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001070 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -07001071 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
1072 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Kenny Guy2a764942014-04-02 13:29:20 +01001073 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
1074 UserInfo.NO_PROFILE_GROUP_ID);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001075 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
1076 if ("true".equals(valueString)) {
1077 partial = true;
1078 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001079 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
1080 if ("true".equals(valueString)) {
1081 guestToRemove = true;
1082 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001083
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001084 int outerDepth = parser.getDepth();
1085 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1086 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1087 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1088 continue;
1089 }
1090 String tag = parser.getName();
1091 if (TAG_NAME.equals(tag)) {
1092 type = parser.next();
1093 if (type == XmlPullParser.TEXT) {
1094 name = parser.getText();
1095 }
1096 } else if (TAG_RESTRICTIONS.equals(tag)) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301097 readRestrictionsLocked(parser, restrictions);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001098 }
1099 }
1100 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001101
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001102 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -07001103 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -07001104 userInfo.creationTime = creationTime;
1105 userInfo.lastLoggedInTime = lastLoggedInTime;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001106 userInfo.partial = partial;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001107 userInfo.guestToRemove = guestToRemove;
Kenny Guy2a764942014-04-02 13:29:20 +01001108 userInfo.profileGroupId = profileGroupId;
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001109 mUserRestrictions.append(id, restrictions);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001110 return userInfo;
1111
1112 } catch (IOException ioe) {
1113 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001114 } finally {
1115 if (fis != null) {
1116 try {
1117 fis.close();
1118 } catch (IOException e) {
1119 }
1120 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001121 }
1122 return null;
1123 }
1124
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301125 private void readRestrictionsLocked(XmlPullParser parser, Bundle restrictions)
1126 throws IOException {
1127 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_WIFI);
1128 readBoolean(parser, restrictions, UserManager.DISALLOW_MODIFY_ACCOUNTS);
1129 readBoolean(parser, restrictions, UserManager.DISALLOW_INSTALL_APPS);
1130 readBoolean(parser, restrictions, UserManager.DISALLOW_UNINSTALL_APPS);
1131 readBoolean(parser, restrictions, UserManager.DISALLOW_SHARE_LOCATION);
1132 readBoolean(parser, restrictions,
1133 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
1134 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_BLUETOOTH);
1135 readBoolean(parser, restrictions, UserManager.DISALLOW_USB_FILE_TRANSFER);
1136 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_CREDENTIALS);
1137 readBoolean(parser, restrictions, UserManager.DISALLOW_REMOVE_USER);
1138 readBoolean(parser, restrictions, UserManager.DISALLOW_DEBUGGING_FEATURES);
1139 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_VPN);
1140 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_TETHERING);
Stuart Scott94b038b2015-04-20 14:07:45 -07001141 readBoolean(parser, restrictions, UserManager.DISALLOW_NETWORK_RESET);
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301142 readBoolean(parser, restrictions, UserManager.DISALLOW_FACTORY_RESET);
1143 readBoolean(parser, restrictions, UserManager.DISALLOW_ADD_USER);
1144 readBoolean(parser, restrictions, UserManager.ENSURE_VERIFY_APPS);
1145 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_CELL_BROADCASTS);
1146 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS);
1147 readBoolean(parser, restrictions, UserManager.DISALLOW_APPS_CONTROL);
1148 readBoolean(parser, restrictions,
1149 UserManager.DISALLOW_MOUNT_PHYSICAL_MEDIA);
1150 readBoolean(parser, restrictions, UserManager.DISALLOW_UNMUTE_MICROPHONE);
1151 readBoolean(parser, restrictions, UserManager.DISALLOW_ADJUST_VOLUME);
Amith Yamasani390989d2014-07-17 10:52:03 -07001152 readBoolean(parser, restrictions, UserManager.DISALLOW_OUTGOING_CALLS);
1153 readBoolean(parser, restrictions, UserManager.DISALLOW_SMS);
Jeff Sharkey2cc03e52015-03-20 11:24:04 -07001154 readBoolean(parser, restrictions, UserManager.DISALLOW_FUN);
Jason Monk1c7c3192014-06-26 12:52:18 -04001155 readBoolean(parser, restrictions, UserManager.DISALLOW_CREATE_WINDOWS);
Amith Yamasani26af8292014-09-09 09:57:27 -07001156 readBoolean(parser, restrictions, UserManager.DISALLOW_CROSS_PROFILE_COPY_PASTE);
1157 readBoolean(parser, restrictions, UserManager.DISALLOW_OUTGOING_BEAM);
Benjamin Franzf3ece362015-02-11 10:51:10 +00001158 readBoolean(parser, restrictions, UserManager.DISALLOW_WALLPAPER);
Benjamin Franzbff46ba2015-03-05 18:33:51 +00001159 readBoolean(parser, restrictions, UserManager.DISALLOW_SAFE_BOOT);
Nicolas Prevotf0029c12015-06-25 14:25:41 -07001160 readBoolean(parser, restrictions, UserManager.ALLOW_PARENT_PROFILE_APP_LINKING);
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301161 }
1162
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001163 private void readBoolean(XmlPullParser parser, Bundle restrictions,
1164 String restrictionKey) {
1165 String value = parser.getAttributeValue(null, restrictionKey);
Amith Yamasani71e6c692013-03-24 17:39:28 -07001166 if (value != null) {
1167 restrictions.putBoolean(restrictionKey, Boolean.parseBoolean(value));
1168 }
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001169 }
1170
1171 private void writeBoolean(XmlSerializer xml, Bundle restrictions, String restrictionKey)
1172 throws IOException {
1173 if (restrictions.containsKey(restrictionKey)) {
1174 xml.attribute(null, restrictionKey,
1175 Boolean.toString(restrictions.getBoolean(restrictionKey)));
1176 }
1177 }
1178
Amith Yamasani920ace02012-09-20 22:15:37 -07001179 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
1180 String valueString = parser.getAttributeValue(null, attr);
1181 if (valueString == null) return defaultValue;
1182 try {
1183 return Integer.parseInt(valueString);
1184 } catch (NumberFormatException nfe) {
1185 return defaultValue;
1186 }
1187 }
1188
1189 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
1190 String valueString = parser.getAttributeValue(null, attr);
1191 if (valueString == null) return defaultValue;
1192 try {
1193 return Long.parseLong(valueString);
1194 } catch (NumberFormatException nfe) {
1195 return defaultValue;
1196 }
1197 }
1198
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001199 private boolean isPackageInstalled(String pkg, int userId) {
1200 final ApplicationInfo info = mPm.getApplicationInfo(pkg,
1201 PackageManager.GET_UNINSTALLED_PACKAGES,
1202 userId);
1203 if (info == null || (info.flags&ApplicationInfo.FLAG_INSTALLED) == 0) {
1204 return false;
1205 }
1206 return true;
1207 }
1208
Amith Yamasanib82add22013-07-09 11:24:44 -07001209 /**
Kenny Guyd21b2182014-07-17 16:38:55 +01001210 * Removes all the restrictions files (res_<packagename>) for a given user.
Amith Yamasanib82add22013-07-09 11:24:44 -07001211 * Does not do any permissions checking.
1212 */
Kenny Guyd21b2182014-07-17 16:38:55 +01001213 private void cleanAppRestrictions(int userId) {
Amith Yamasanib82add22013-07-09 11:24:44 -07001214 synchronized (mPackagesLock) {
1215 File dir = Environment.getUserSystemDirectory(userId);
1216 String[] files = dir.list();
1217 if (files == null) return;
1218 for (String fileName : files) {
1219 if (fileName.startsWith(RESTRICTIONS_FILE_PREFIX)) {
1220 File resFile = new File(dir, fileName);
1221 if (resFile.exists()) {
Kenny Guyd21b2182014-07-17 16:38:55 +01001222 resFile.delete();
Amith Yamasanib82add22013-07-09 11:24:44 -07001223 }
1224 }
1225 }
1226 }
1227 }
1228
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001229 /**
1230 * Removes the app restrictions file for a specific package and user id, if it exists.
1231 */
1232 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
1233 synchronized (mPackagesLock) {
1234 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07001235 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001236 if (resFile.exists()) {
1237 resFile.delete();
1238 }
1239 }
1240 }
1241
Kenny Guya52dc3e2014-02-11 15:33:14 +00001242 @Override
Kenny Guy2a764942014-04-02 13:29:20 +01001243 public UserInfo createProfileForUser(String name, int flags, int userId) {
Kenny Guya52dc3e2014-02-11 15:33:14 +00001244 checkManageUsersPermission("Only the system can create users");
Kenny Guy2a764942014-04-02 13:29:20 +01001245 return createUserInternal(name, flags, userId);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001246 }
1247
Amith Yamasani258848d2012-08-10 17:06:33 -07001248 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07001249 public UserInfo createUser(String name, int flags) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001250 checkManageUsersPermission("Only the system can create users");
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001251 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001252 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001253
Jessica Hummelbe81c802014-04-22 15:49:22 +01001254 private UserInfo createUserInternal(String name, int flags, int parentId) {
Julia Reynolds75175022014-06-26 16:35:00 -04001255 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1256 UserManager.DISALLOW_ADD_USER, false)) {
1257 Log.w(LOG_TAG, "Cannot add user. DISALLOW_ADD_USER is enabled.");
1258 return null;
1259 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001260 if (ActivityManager.isLowRamDeviceStatic()) {
1261 return null;
1262 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07001263 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001264 final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001265 final long ident = Binder.clearCallingIdentity();
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001266 UserInfo userInfo = null;
Amith Yamasanibb054c92015-07-09 14:16:27 -07001267 final int userId;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001268 try {
1269 synchronized (mInstallLock) {
1270 synchronized (mPackagesLock) {
Jessica Hummelbe81c802014-04-22 15:49:22 +01001271 UserInfo parent = null;
1272 if (parentId != UserHandle.USER_NULL) {
1273 parent = getUserInfoLocked(parentId);
1274 if (parent == null) return null;
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001275 }
Nicolas Prevotb8186812015-08-06 15:00:03 +01001276 if (isManagedProfile && !canAddMoreManagedProfiles(parentId)) {
1277 Log.e(LOG_TAG, "Cannot add more managed profiles for user " + parentId);
Nicolas Prevot12678a92015-05-13 12:15:03 -07001278 return null;
1279 }
1280 if (!isGuest && !isManagedProfile && isUserLimitReachedLocked()) {
1281 // If we're not adding a guest user or a managed profile and the limit has
1282 // been reached, cannot add a user.
Amith Yamasani95ab7842014-08-11 17:09:26 -07001283 return null;
1284 }
1285 // If we're adding a guest and there already exists one, bail.
Adam Lesinskieddeb492014-09-08 17:50:03 -07001286 if (isGuest && findCurrentGuestUserLocked() != null) {
Amith Yamasani95ab7842014-08-11 17:09:26 -07001287 return null;
1288 }
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001289 // In split system user mode, we assign the first human user the primary flag.
Xiaohui Chen203243a2015-07-16 11:55:47 -07001290 // And if there is no device owner, we also assign the admin flag to primary
1291 // user.
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001292 if (UserManager.isSplitSystemUser()
Xiaohui Chen203243a2015-07-16 11:55:47 -07001293 && !isGuest && !isManagedProfile && getPrimaryUser() == null) {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001294 flags |= UserInfo.FLAG_PRIMARY;
Xiaohui Chen203243a2015-07-16 11:55:47 -07001295 DevicePolicyManager devicePolicyManager = (DevicePolicyManager)
1296 mContext.getSystemService(Context.DEVICE_POLICY_SERVICE);
1297 if (devicePolicyManager == null
1298 || devicePolicyManager.getDeviceOwner() == null) {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001299 flags |= UserInfo.FLAG_ADMIN;
1300 }
1301 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07001302 userId = getNextAvailableIdLocked();
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001303 userInfo = new UserInfo(userId, name, null, flags);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001304 userInfo.serialNumber = mNextSerialNumber++;
Amith Yamasani920ace02012-09-20 22:15:37 -07001305 long now = System.currentTimeMillis();
1306 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001307 userInfo.partial = true;
Amith Yamasani16389312012-10-17 21:20:14 -07001308 Environment.getUserSystemDirectory(userInfo.id).mkdirs();
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001309 mUsers.put(userId, userInfo);
1310 writeUserListLocked();
Jessica Hummelbe81c802014-04-22 15:49:22 +01001311 if (parent != null) {
1312 if (parent.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
1313 parent.profileGroupId = parent.id;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001314 scheduleWriteUserLocked(parent);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001315 }
Jessica Hummelbe81c802014-04-22 15:49:22 +01001316 userInfo.profileGroupId = parent.profileGroupId;
Kenny Guya52dc3e2014-02-11 15:33:14 +00001317 }
Jeff Sharkey6dce4962015-07-03 18:08:41 -07001318 final StorageManager storage = mContext.getSystemService(StorageManager.class);
1319 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
1320 final String volumeUuid = vol.getFsUuid();
1321 try {
1322 final File userDir = Environment.getDataUserDirectory(volumeUuid,
1323 userId);
Jeff Sharkey3bb8c852015-07-06 16:44:23 -07001324 prepareUserDirectory(mContext, volumeUuid, userId);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07001325 enforceSerialNumber(userDir, userInfo.serialNumber);
1326 } catch (IOException e) {
1327 Log.wtf(LOG_TAG, "Failed to create user directory on " + volumeUuid, e);
1328 }
1329 }
1330 mPm.createNewUserLILPw(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001331 userInfo.partial = false;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001332 scheduleWriteUserLocked(userInfo);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001333 updateUserIdsLocked();
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001334 Bundle restrictions = new Bundle();
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001335 mUserRestrictions.append(userId, restrictions);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001336 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07001337 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07001338 mPm.newUserCreated(userId);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001339 if (userInfo != null) {
1340 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
1341 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userInfo.id);
1342 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
1343 android.Manifest.permission.MANAGE_USERS);
1344 }
1345 } finally {
1346 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07001347 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001348 return userInfo;
1349 }
1350
Amith Yamasani95ab7842014-08-11 17:09:26 -07001351 private int numberOfUsersOfTypeLocked(int flags, boolean excludeDying) {
1352 int count = 0;
1353 for (int i = mUsers.size() - 1; i >= 0; i--) {
1354 UserInfo user = mUsers.valueAt(i);
1355 if (!excludeDying || !mRemovingUserIds.get(user.id)) {
1356 if ((user.flags & flags) != 0) {
1357 count++;
1358 }
1359 }
1360 }
1361 return count;
1362 }
1363
Amith Yamasani0b285492011-04-14 17:35:23 -07001364 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07001365 * Find the current guest user. If the Guest user is partial,
1366 * then do not include it in the results as it is about to die.
1367 * This is different than {@link #numberOfUsersOfTypeLocked(int, boolean)} due to
1368 * the special handling of Guests being removed.
1369 */
1370 private UserInfo findCurrentGuestUserLocked() {
1371 final int size = mUsers.size();
1372 for (int i = 0; i < size; i++) {
1373 final UserInfo user = mUsers.valueAt(i);
1374 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
1375 return user;
1376 }
1377 }
1378 return null;
1379 }
1380
1381 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07001382 * Mark this guest user for deletion to allow us to create another guest
1383 * and switch to that user before actually removing this guest.
1384 * @param userHandle the userid of the current guest
1385 * @return whether the user could be marked for deletion
1386 */
1387 public boolean markGuestForDeletion(int userHandle) {
1388 checkManageUsersPermission("Only the system can remove users");
1389 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1390 UserManager.DISALLOW_REMOVE_USER, false)) {
1391 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1392 return false;
1393 }
1394
1395 long ident = Binder.clearCallingIdentity();
1396 try {
1397 final UserInfo user;
1398 synchronized (mPackagesLock) {
1399 user = mUsers.get(userHandle);
1400 if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
1401 return false;
1402 }
1403 if (!user.isGuest()) {
1404 return false;
1405 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001406 // We set this to a guest user that is to be removed. This is a temporary state
1407 // where we are allowed to add new Guest users, even if this one is still not
1408 // removed. This user will still show up in getUserInfo() calls.
1409 // If we don't get around to removing this Guest user, it will be purged on next
1410 // startup.
1411 user.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07001412 // Mark it as disabled, so that it isn't returned any more when
1413 // profiles are queried.
1414 user.flags |= UserInfo.FLAG_DISABLED;
Amith Yamasani1df14732014-08-29 21:37:27 -07001415 writeUserLocked(user);
1416 }
1417 } finally {
1418 Binder.restoreCallingIdentity(ident);
1419 }
1420 return true;
1421 }
1422
1423 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07001424 * Removes a user and all data directories created for that user. This method should be called
1425 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001426 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07001427 */
Amith Yamasani258848d2012-08-10 17:06:33 -07001428 public boolean removeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001429 checkManageUsersPermission("Only the system can remove users");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04001430 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1431 UserManager.DISALLOW_REMOVE_USER, false)) {
1432 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1433 return false;
1434 }
1435
Kenny Guyee58b4f2014-05-23 15:19:53 +01001436 long ident = Binder.clearCallingIdentity();
1437 try {
1438 final UserInfo user;
1439 synchronized (mPackagesLock) {
1440 user = mUsers.get(userHandle);
Kenny Guy17c9d692014-06-13 13:51:42 +01001441 if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01001442 return false;
1443 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08001444
1445 // We remember deleted user IDs to prevent them from being
1446 // reused during the current boot; they can still be reused
1447 // after a reboot.
Kenny Guyee58b4f2014-05-23 15:19:53 +01001448 mRemovingUserIds.put(userHandle, true);
Jeff Sharkey6eb09392014-11-14 15:57:59 -08001449
Kenny Guyee58b4f2014-05-23 15:19:53 +01001450 try {
1451 mAppOpsService.removeUser(userHandle);
1452 } catch (RemoteException e) {
1453 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
1454 }
1455 // Set this to a partially created user, so that the user will be purged
1456 // on next startup, in case the runtime stops now before stopping and
1457 // removing the user completely.
1458 user.partial = true;
1459 // Mark it as disabled, so that it isn't returned any more when
1460 // profiles are queried.
1461 user.flags |= UserInfo.FLAG_DISABLED;
1462 writeUserLocked(user);
1463 }
1464
1465 if (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
1466 && user.isManagedProfile()) {
1467 // Send broadcast to notify system that the user removed was a
1468 // managed user.
1469 sendProfileRemovedBroadcast(user.profileGroupId, user.id);
1470 }
1471
1472 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
1473 int res;
1474 try {
1475 res = ActivityManagerNative.getDefault().stopUser(userHandle,
1476 new IStopUserCallback.Stub() {
1477 @Override
1478 public void userStopped(int userId) {
1479 finishRemoveUser(userId);
1480 }
1481 @Override
1482 public void userStopAborted(int userId) {
1483 }
1484 });
1485 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001486 return false;
1487 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01001488 return res == ActivityManager.USER_OP_SUCCESS;
1489 } finally {
1490 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001491 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001492 }
1493
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001494 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07001495 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001496 // Let other services shutdown any activity and clean up their state before completely
1497 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001498 long ident = Binder.clearCallingIdentity();
1499 try {
1500 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
1501 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001502 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
1503 android.Manifest.permission.MANAGE_USERS,
1504
1505 new BroadcastReceiver() {
1506 @Override
1507 public void onReceive(Context context, Intent intent) {
1508 if (DBG) {
1509 Slog.i(LOG_TAG,
1510 "USER_REMOVED broadcast sent, cleaning up user data "
1511 + userHandle);
1512 }
1513 new Thread() {
1514 public void run() {
1515 synchronized (mInstallLock) {
1516 synchronized (mPackagesLock) {
1517 removeUserStateLocked(userHandle);
1518 }
1519 }
1520 }
1521 }.start();
1522 }
1523 },
1524
1525 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001526 } finally {
1527 Binder.restoreCallingIdentity(ident);
1528 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001529 }
1530
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001531 private void removeUserStateLocked(final int userHandle) {
Paul Crowley85e4e812015-05-19 12:42:00 +01001532 mContext.getSystemService(StorageManager.class)
1533 .deleteUserKey(userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001534 // Cleanup package manager settings
Amith Yamasanidda003f2014-08-28 18:06:51 -07001535 mPm.cleanUpUserLILPw(this, userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001536
1537 // Remove this user from the list
1538 mUsers.remove(userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001539 // Remove user file
Amith Yamasanifc95e702013-09-26 13:20:17 -07001540 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001541 userFile.delete();
1542 // Update the user list
1543 writeUserListLocked();
1544 updateUserIdsLocked();
1545 removeDirectoryRecursive(Environment.getUserSystemDirectory(userHandle));
1546 }
1547
Amith Yamasani61f57372012-08-31 12:12:28 -07001548 private void removeDirectoryRecursive(File parent) {
1549 if (parent.isDirectory()) {
1550 String[] files = parent.list();
1551 for (String filename : files) {
1552 File child = new File(parent, filename);
1553 removeDirectoryRecursive(child);
1554 }
1555 }
1556 parent.delete();
1557 }
1558
Kenny Guyf8d3a232014-05-15 16:09:52 +01001559 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01001560 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01001561 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
1562 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01001563 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
1564 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01001565 }
1566
Amith Yamasani2a003292012-08-14 18:25:45 -07001567 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001568 public Bundle getApplicationRestrictions(String packageName) {
1569 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
1570 }
1571
1572 @Override
1573 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001574 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07001575 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001576 checkManageUsersPermission("Only system can get restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001577 }
1578 synchronized (mPackagesLock) {
1579 // Read the restrictions from XML
1580 return readApplicationRestrictionsLocked(packageName, userId);
1581 }
1582 }
1583
1584 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001585 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001586 int userId) {
1587 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07001588 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001589 checkManageUsersPermission("Only system can set restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001590 }
1591 synchronized (mPackagesLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01001592 if (restrictions == null || restrictions.isEmpty()) {
1593 cleanAppRestrictionsForPackage(packageName, userId);
1594 } else {
1595 // Write the restrictions to XML
1596 writeApplicationRestrictionsLocked(packageName, restrictions, userId);
1597 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001598 }
Robin Lee66e5d962014-04-09 16:44:21 +01001599
Kenny Guyd21b2182014-07-17 16:38:55 +01001600 if (isPackageInstalled(packageName, userId)) {
1601 // Notify package of changes via an intent - only sent to explicitly registered receivers.
1602 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
1603 changeIntent.setPackage(packageName);
1604 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
1605 mContext.sendBroadcastAsUser(changeIntent, new UserHandle(userId));
1606 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001607 }
1608
Amith Yamasani655d0e22013-06-12 14:19:10 -07001609 @Override
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001610 public void removeRestrictions() {
Amith Yamasanibe465322014-04-24 13:45:17 -07001611 checkManageUsersPermission("Only system can remove restrictions");
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001612 final int userHandle = UserHandle.getCallingUserId();
Amith Yamasani5e486f52013-08-07 11:06:44 -07001613 removeRestrictionsForUser(userHandle, true);
Amith Yamasani350962c2013-08-06 11:18:53 -07001614 }
1615
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001616 private void removeRestrictionsForUser(final int userHandle, boolean unhideApps) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001617 synchronized (mPackagesLock) {
1618 // Remove all user restrictions
1619 setUserRestrictions(new Bundle(), userHandle);
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001620 // Remove any app restrictions
Kenny Guyd21b2182014-07-17 16:38:55 +01001621 cleanAppRestrictions(userHandle);
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001622 }
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001623 if (unhideApps) {
1624 unhideAllInstalledAppsForUser(userHandle);
Amith Yamasani5e486f52013-08-07 11:06:44 -07001625 }
1626 }
1627
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001628 private void unhideAllInstalledAppsForUser(final int userHandle) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001629 mHandler.post(new Runnable() {
1630 @Override
1631 public void run() {
1632 List<ApplicationInfo> apps =
1633 mPm.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES,
1634 userHandle).getList();
1635 final long ident = Binder.clearCallingIdentity();
1636 try {
1637 for (ApplicationInfo appInfo : apps) {
1638 if ((appInfo.flags & ApplicationInfo.FLAG_INSTALLED) != 0
Alex Klyubinb9f8a522015-02-03 11:12:59 -08001639 && (appInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HIDDEN)
1640 != 0) {
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001641 mPm.setApplicationHiddenSettingAsUser(appInfo.packageName, false,
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001642 userHandle);
1643 }
1644 }
1645 } finally {
1646 Binder.restoreCallingIdentity(ident);
1647 }
1648 }
1649 });
1650 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001651 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07001652 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001653 try {
1654 return mContext.getPackageManager().getApplicationInfo(packageName,
1655 PackageManager.GET_UNINSTALLED_PACKAGES).uid;
1656 } catch (NameNotFoundException nnfe) {
1657 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07001658 } finally {
1659 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001660 }
1661 }
1662
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001663 private Bundle readApplicationRestrictionsLocked(String packageName,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001664 int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001665 AtomicFile restrictionsFile =
1666 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
1667 packageToRestrictionsFileName(packageName)));
1668 return readApplicationRestrictionsLocked(restrictionsFile);
1669 }
1670
1671 @VisibleForTesting
1672 static Bundle readApplicationRestrictionsLocked(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001673 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001674 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07001675 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07001676 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07001677 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001678
1679 FileInputStream fis = null;
1680 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001681 fis = restrictionsFile.openRead();
1682 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001683 parser.setInput(fis, StandardCharsets.UTF_8.name());
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001684 XmlUtils.nextElement(parser);
1685 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001686 Slog.e(LOG_TAG, "Unable to read restrictions file "
1687 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001688 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001689 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001690 while (parser.next() != XmlPullParser.END_DOCUMENT) {
1691 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001692 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001693 } catch (IOException|XmlPullParserException e) {
1694 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001695 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001696 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001697 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001698 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001699 }
1700
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001701 private static void readEntry(Bundle restrictions, ArrayList<String> values,
1702 XmlPullParser parser) throws XmlPullParserException, IOException {
1703 int type = parser.getEventType();
1704 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
1705 String key = parser.getAttributeValue(null, ATTR_KEY);
1706 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
1707 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
1708 if (multiple != null) {
1709 values.clear();
1710 int count = Integer.parseInt(multiple);
1711 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1712 if (type == XmlPullParser.START_TAG
1713 && parser.getName().equals(TAG_VALUE)) {
1714 values.add(parser.nextText().trim());
1715 count--;
1716 }
1717 }
1718 String [] valueStrings = new String[values.size()];
1719 values.toArray(valueStrings);
1720 restrictions.putStringArray(key, valueStrings);
1721 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
1722 restrictions.putBundle(key, readBundleEntry(parser, values));
1723 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
1724 final int outerDepth = parser.getDepth();
1725 ArrayList<Bundle> bundleList = new ArrayList<>();
1726 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
1727 Bundle childBundle = readBundleEntry(parser, values);
1728 bundleList.add(childBundle);
1729 }
1730 restrictions.putParcelableArray(key,
1731 bundleList.toArray(new Bundle[bundleList.size()]));
1732 } else {
1733 String value = parser.nextText().trim();
1734 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
1735 restrictions.putBoolean(key, Boolean.parseBoolean(value));
1736 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
1737 restrictions.putInt(key, Integer.parseInt(value));
1738 } else {
1739 restrictions.putString(key, value);
1740 }
1741 }
1742 }
1743 }
1744
1745 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
1746 throws IOException, XmlPullParserException {
1747 Bundle childBundle = new Bundle();
1748 final int outerDepth = parser.getDepth();
1749 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
1750 readEntry(childBundle, values, parser);
1751 }
1752 return childBundle;
1753 }
1754
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001755 private void writeApplicationRestrictionsLocked(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001756 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001757 AtomicFile restrictionsFile = new AtomicFile(
1758 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07001759 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001760 writeApplicationRestrictionsLocked(restrictions, restrictionsFile);
1761 }
1762
1763 @VisibleForTesting
1764 static void writeApplicationRestrictionsLocked(Bundle restrictions,
1765 AtomicFile restrictionsFile) {
1766 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001767 try {
1768 fos = restrictionsFile.startWrite();
1769 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1770
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001771 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001772 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001773 serializer.startDocument(null, true);
1774 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1775
1776 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001777 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001778 serializer.endTag(null, TAG_RESTRICTIONS);
1779
1780 serializer.endDocument();
1781 restrictionsFile.finishWrite(fos);
1782 } catch (Exception e) {
1783 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001784 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
1785 }
1786 }
1787
1788 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
1789 throws IOException {
1790 for (String key : restrictions.keySet()) {
1791 Object value = restrictions.get(key);
1792 serializer.startTag(null, TAG_ENTRY);
1793 serializer.attribute(null, ATTR_KEY, key);
1794
1795 if (value instanceof Boolean) {
1796 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
1797 serializer.text(value.toString());
1798 } else if (value instanceof Integer) {
1799 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
1800 serializer.text(value.toString());
1801 } else if (value == null || value instanceof String) {
1802 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
1803 serializer.text(value != null ? (String) value : "");
1804 } else if (value instanceof Bundle) {
1805 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
1806 writeBundle((Bundle) value, serializer);
1807 } else if (value instanceof Parcelable[]) {
1808 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
1809 Parcelable[] array = (Parcelable[]) value;
1810 for (Parcelable parcelable : array) {
1811 if (!(parcelable instanceof Bundle)) {
1812 throw new IllegalArgumentException("bundle-array can only hold Bundles");
1813 }
1814 serializer.startTag(null, TAG_ENTRY);
1815 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
1816 writeBundle((Bundle) parcelable, serializer);
1817 serializer.endTag(null, TAG_ENTRY);
1818 }
1819 } else {
1820 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
1821 String[] values = (String[]) value;
1822 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
1823 for (String choice : values) {
1824 serializer.startTag(null, TAG_VALUE);
1825 serializer.text(choice != null ? choice : "");
1826 serializer.endTag(null, TAG_VALUE);
1827 }
1828 }
1829 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001830 }
1831 }
1832
1833 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07001834 public int getUserSerialNumber(int userHandle) {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001835 synchronized (mPackagesLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001836 if (!exists(userHandle)) return -1;
Amith Yamasani195263742012-08-21 15:40:12 -07001837 return getUserInfoLocked(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07001838 }
1839 }
1840
1841 @Override
1842 public int getUserHandle(int userSerialNumber) {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001843 synchronized (mPackagesLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001844 for (int userId : mUserIds) {
Kenny Guy945f8832015-02-10 15:17:26 +00001845 UserInfo info = getUserInfoLocked(userId);
1846 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07001847 }
1848 // Not found
1849 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07001850 }
1851 }
1852
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07001853 @Override
1854 public long getUserCreationTime(int userHandle) {
1855 int callingUserId = UserHandle.getCallingUserId();
1856 UserInfo userInfo = null;
1857 synchronized (mPackagesLock) {
1858 if (callingUserId == userHandle) {
1859 userInfo = getUserInfoLocked(userHandle);
1860 } else {
1861 UserInfo parent = getProfileParentLocked(userHandle);
1862 if (parent != null && parent.id == callingUserId) {
1863 userInfo = getUserInfoLocked(userHandle);
1864 }
1865 }
1866 }
1867 if (userInfo == null) {
1868 throw new SecurityException("userHandle can only be the calling user or a managed "
1869 + "profile associated with this user");
1870 }
1871 return userInfo.creationTime;
1872 }
1873
Amith Yamasani0b285492011-04-14 17:35:23 -07001874 /**
1875 * Caches the list of user ids in an array, adjusting the array size when necessary.
1876 */
Amith Yamasani13593602012-03-22 16:16:17 -07001877 private void updateUserIdsLocked() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001878 int num = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -07001879 for (int i = 0; i < mUsers.size(); i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001880 if (!mUsers.valueAt(i).partial) {
1881 num++;
1882 }
1883 }
Amith Yamasani16389312012-10-17 21:20:14 -07001884 final int[] newUsers = new int[num];
1885 int n = 0;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001886 for (int i = 0; i < mUsers.size(); i++) {
1887 if (!mUsers.valueAt(i).partial) {
Amith Yamasani16389312012-10-17 21:20:14 -07001888 newUsers[n++] = mUsers.keyAt(i);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001889 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001890 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001891 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07001892 }
1893
1894 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001895 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasani920ace02012-09-20 22:15:37 -07001896 * @param userId the user that was just foregrounded
1897 */
Amith Yamasani06bf8242015-05-08 16:36:21 -07001898 public void onUserForeground(int userId) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001899 synchronized (mPackagesLock) {
1900 UserInfo user = mUsers.get(userId);
1901 long now = System.currentTimeMillis();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001902 if (user == null || user.partial) {
1903 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
1904 return;
1905 }
1906 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001907 user.lastLoggedInTime = now;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001908 scheduleWriteUserLocked(user);
Amith Yamasani920ace02012-09-20 22:15:37 -07001909 }
1910 }
1911 }
1912
1913 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07001914 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani742a6712011-05-04 14:49:28 -07001915 * TODO: May not be a good idea to recycle ids, in case it results in confusion
1916 * for data and battery stats collection, or unexpected cross-talk.
Amith Yamasani0b285492011-04-14 17:35:23 -07001917 * @return
1918 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001919 private int getNextAvailableIdLocked() {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001920 synchronized (mPackagesLock) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001921 int i = MIN_USER_ID;
Amith Yamasani195263742012-08-21 15:40:12 -07001922 while (i < Integer.MAX_VALUE) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001923 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
Amith Yamasani195263742012-08-21 15:40:12 -07001924 break;
1925 }
1926 i++;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001927 }
Amith Yamasani195263742012-08-21 15:40:12 -07001928 return i;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001929 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001930 }
Amith Yamasani920ace02012-09-20 22:15:37 -07001931
Amith Yamasanifc95e702013-09-26 13:20:17 -07001932 private String packageToRestrictionsFileName(String packageName) {
1933 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
1934 }
1935
Jeff Sharkey6dce4962015-07-03 18:08:41 -07001936 /**
1937 * Create new {@code /data/user/[id]} directory and sets default
1938 * permissions.
1939 */
Jeff Sharkey3bb8c852015-07-06 16:44:23 -07001940 public static void prepareUserDirectory(Context context, String volumeUuid, int userId) {
1941 final StorageManager storage = context.getSystemService(StorageManager.class);
1942 final File userDir = Environment.getDataUserDirectory(volumeUuid, userId);
1943 storage.createNewUserDir(userId, userDir);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07001944 }
1945
1946 /**
1947 * Enforce that serial number stored in user directory inode matches the
1948 * given expected value. Gracefully sets the serial number if currently
1949 * undefined.
1950 *
1951 * @throws IOException when problem extracting serial number, or serial
1952 * number is mismatched.
1953 */
1954 public static void enforceSerialNumber(File file, int serialNumber) throws IOException {
1955 final int foundSerial = getSerialNumber(file);
1956 Slog.v(LOG_TAG, "Found " + file + " with serial number " + foundSerial);
1957
1958 if (foundSerial == -1) {
1959 Slog.d(LOG_TAG, "Serial number missing on " + file + "; assuming current is valid");
1960 try {
1961 setSerialNumber(file, serialNumber);
1962 } catch (IOException e) {
1963 Slog.w(LOG_TAG, "Failed to set serial number on " + file, e);
1964 }
1965
1966 } else if (foundSerial != serialNumber) {
1967 throw new IOException("Found serial number " + foundSerial
1968 + " doesn't match expected " + serialNumber);
1969 }
1970 }
1971
1972 /**
1973 * Set serial number stored in user directory inode.
1974 *
1975 * @throws IOException if serial number was already set
1976 */
1977 private static void setSerialNumber(File file, int serialNumber)
1978 throws IOException {
1979 try {
1980 final byte[] buf = Integer.toString(serialNumber).getBytes(StandardCharsets.UTF_8);
1981 Os.setxattr(file.getAbsolutePath(), XATTR_SERIAL, buf, OsConstants.XATTR_CREATE);
1982 } catch (ErrnoException e) {
1983 throw e.rethrowAsIOException();
1984 }
1985 }
1986
1987 /**
1988 * Return serial number stored in user directory inode.
1989 *
1990 * @return parsed serial number, or -1 if not set
1991 */
1992 private static int getSerialNumber(File file) throws IOException {
1993 try {
1994 final byte[] buf = new byte[256];
1995 final int len = Os.getxattr(file.getAbsolutePath(), XATTR_SERIAL, buf);
1996 final String serial = new String(buf, 0, len);
1997 try {
1998 return Integer.parseInt(serial);
1999 } catch (NumberFormatException e) {
2000 throw new IOException("Bad serial number: " + serial);
2001 }
2002 } catch (ErrnoException e) {
2003 if (e.errno == OsConstants.ENODATA) {
2004 return -1;
2005 } else {
2006 throw e.rethrowAsIOException();
2007 }
2008 }
2009 }
2010
Amith Yamasani920ace02012-09-20 22:15:37 -07002011 @Override
2012 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2013 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2014 != PackageManager.PERMISSION_GRANTED) {
2015 pw.println("Permission Denial: can't dump UserManager from from pid="
2016 + Binder.getCallingPid()
2017 + ", uid=" + Binder.getCallingUid()
2018 + " without permission "
2019 + android.Manifest.permission.DUMP);
2020 return;
2021 }
2022
2023 long now = System.currentTimeMillis();
2024 StringBuilder sb = new StringBuilder();
2025 synchronized (mPackagesLock) {
2026 pw.println("Users:");
2027 for (int i = 0; i < mUsers.size(); i++) {
2028 UserInfo user = mUsers.valueAt(i);
2029 if (user == null) continue;
Amith Yamasani634cf312012-10-04 17:34:21 -07002030 pw.print(" "); pw.print(user); pw.print(" serialNo="); pw.print(user.serialNumber);
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002031 if (mRemovingUserIds.get(mUsers.keyAt(i))) pw.print(" <removing> ");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002032 if (user.partial) pw.print(" <partial>");
2033 pw.println();
Amith Yamasani920ace02012-09-20 22:15:37 -07002034 pw.print(" Created: ");
2035 if (user.creationTime == 0) {
2036 pw.println("<unknown>");
2037 } else {
2038 sb.setLength(0);
2039 TimeUtils.formatDuration(now - user.creationTime, sb);
2040 sb.append(" ago");
2041 pw.println(sb);
2042 }
2043 pw.print(" Last logged in: ");
2044 if (user.lastLoggedInTime == 0) {
2045 pw.println("<unknown>");
2046 } else {
2047 sb.setLength(0);
2048 TimeUtils.formatDuration(now - user.lastLoggedInTime, sb);
2049 sb.append(" ago");
2050 pw.println(sb);
2051 }
2052 }
2053 }
2054 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002055
2056 final class MainHandler extends Handler {
2057
2058 @Override
2059 public void handleMessage(Message msg) {
2060 switch (msg.what) {
2061 case WRITE_USER_MSG:
2062 removeMessages(WRITE_USER_MSG, msg.obj);
2063 synchronized (mPackagesLock) {
2064 int userId = ((UserInfo) msg.obj).id;
2065 UserInfo userInfo = mUsers.get(userId);
2066 if (userInfo != null) {
2067 writeUserLocked(userInfo);
2068 }
2069 }
2070 }
2071 }
2072 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07002073
2074 /**
2075 * @param userId
2076 * @return whether the user has been initialized yet
2077 */
2078 boolean isInitialized(int userId) {
2079 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
2080 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002081}