blob: 0577d5905085c81b0f1c35ed05069148983a053a [file] [log] [blame]
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -070019import android.accounts.Account;
Xiaohui Chen594f2082015-08-18 11:04:20 -070020import android.annotation.NonNull;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070021import android.app.Activity;
Amith Yamasani2a003292012-08-14 18:25:45 -070022import android.app.ActivityManager;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070023import android.app.ActivityManagerNative;
24import android.app.IStopUserCallback;
Xiaohui Chen203243a2015-07-16 11:55:47 -070025import android.app.admin.DevicePolicyManager;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070026import android.content.BroadcastReceiver;
Amith Yamasani258848d2012-08-10 17:06:33 -070027import android.content.Context;
28import android.content.Intent;
Amith Yamasani1a7472e2013-07-02 11:17:30 -070029import android.content.pm.ApplicationInfo;
Amith Yamasani0b285492011-04-14 17:35:23 -070030import android.content.pm.PackageManager;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -080031import android.content.pm.PackageManager.NameNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070032import android.content.pm.UserInfo;
Amith Yamasanie928d7d2012-09-17 21:46:51 -070033import android.graphics.Bitmap;
Amith Yamasani258848d2012-08-10 17:06:33 -070034import android.os.Binder;
Amith Yamasanie4cf7342012-12-17 11:12:09 -080035import android.os.Bundle;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070036import android.os.Environment;
37import android.os.FileUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080038import android.os.Handler;
Amith Yamasani258848d2012-08-10 17:06:33 -070039import android.os.IUserManager;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -080040import android.os.Message;
Adrian Roos1bdff912015-02-17 15:51:35 +010041import android.os.ParcelFileDescriptor;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070042import android.os.Parcelable;
Amith Yamasani258848d2012-08-10 17:06:33 -070043import android.os.Process;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070044import android.os.RemoteException;
Jason Monk62062992014-05-06 09:55:28 -040045import android.os.ServiceManager;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070046import android.os.UserHandle;
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070047import android.os.UserManager;
Paul Crowley85e4e812015-05-19 12:42:00 +010048import android.os.storage.StorageManager;
Jeff Sharkey6dce4962015-07-03 18:08:41 -070049import android.os.storage.VolumeInfo;
50import android.system.ErrnoException;
51import android.system.Os;
52import android.system.OsConstants;
Amith Yamasani2a003292012-08-14 18:25:45 -070053import android.util.AtomicFile;
Amith Yamasani655d0e22013-06-12 14:19:10 -070054import android.util.Log;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070055import android.util.Slog;
56import android.util.SparseArray;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080057import android.util.SparseBooleanArray;
Amith Yamasani920ace02012-09-20 22:15:37 -070058import android.util.TimeUtils;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070059import android.util.Xml;
60
Fyodor Kupolovb5013302015-04-17 17:59:14 -070061import com.google.android.collect.Sets;
62
Fyodor Kupolov262f9952015-03-23 18:55:11 -070063import com.android.internal.annotations.VisibleForTesting;
Jason Monk62062992014-05-06 09:55:28 -040064import com.android.internal.app.IAppOpsService;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080065import com.android.internal.util.FastXmlSerializer;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070066import com.android.internal.util.XmlUtils;
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -070067import com.android.server.accounts.AccountManagerService;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080068
69import org.xmlpull.v1.XmlPullParser;
70import org.xmlpull.v1.XmlPullParserException;
71import org.xmlpull.v1.XmlSerializer;
72
Amith Yamasani4b2e9342011-03-31 12:38:53 -070073import java.io.BufferedOutputStream;
74import java.io.File;
Amith Yamasani920ace02012-09-20 22:15:37 -070075import java.io.FileDescriptor;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070076import java.io.FileInputStream;
Amith Yamasanib8151ec2012-04-18 18:02:48 -070077import java.io.FileNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070078import java.io.FileOutputStream;
79import java.io.IOException;
Amith Yamasani920ace02012-09-20 22:15:37 -070080import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +010081import java.nio.charset.StandardCharsets;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070082import java.util.ArrayList;
83import java.util.List;
Fyodor Kupolovb5013302015-04-17 17:59:14 -070084import java.util.Set;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070085
Fyodor Kupolov262f9952015-03-23 18:55:11 -070086import libcore.io.IoUtils;
87
Amith Yamasani258848d2012-08-10 17:06:33 -070088public class UserManagerService extends IUserManager.Stub {
Amith Yamasanib8151ec2012-04-18 18:02:48 -070089
Amith Yamasani2a003292012-08-14 18:25:45 -070090 private static final String LOG_TAG = "UserManagerService";
Amith Yamasanib8151ec2012-04-18 18:02:48 -070091
Amith Yamasani16389312012-10-17 21:20:14 -070092 private static final boolean DBG = false;
93
Amith Yamasani4b2e9342011-03-31 12:38:53 -070094 private static final String TAG_NAME = "name";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070095 private static final String ATTR_FLAGS = "flags";
Amith Yamasanib8151ec2012-04-18 18:02:48 -070096 private static final String ATTR_ICON_PATH = "icon";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070097 private static final String ATTR_ID = "id";
Amith Yamasani920ace02012-09-20 22:15:37 -070098 private static final String ATTR_CREATION_TIME = "created";
99 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
Amith Yamasani2a003292012-08-14 18:25:45 -0700100 private static final String ATTR_SERIAL_NO = "serialNumber";
101 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700102 private static final String ATTR_PARTIAL = "partial";
Adam Lesinskieddeb492014-09-08 17:50:03 -0700103 private static final String ATTR_GUEST_TO_REMOVE = "guestToRemove";
Amith Yamasani6f34b412012-10-22 18:19:27 -0700104 private static final String ATTR_USER_VERSION = "version";
Kenny Guy2a764942014-04-02 13:29:20 +0100105 private static final String ATTR_PROFILE_GROUP_ID = "profileGroupId";
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700106 private static final String ATTR_RESTRICTED_PROFILE_PARENT_ID = "restrictedProfileParentId";
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530107 private static final String TAG_GUEST_RESTRICTIONS = "guestRestrictions";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700108 private static final String TAG_USERS = "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700109 private static final String TAG_USER = "user";
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800110 private static final String TAG_RESTRICTIONS = "restrictions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800111 private static final String TAG_ENTRY = "entry";
112 private static final String TAG_VALUE = "value";
113 private static final String ATTR_KEY = "key";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700114 private static final String ATTR_VALUE_TYPE = "type";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800115 private static final String ATTR_MULTIPLE = "m";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700116
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700117 private static final String ATTR_TYPE_STRING_ARRAY = "sa";
118 private static final String ATTR_TYPE_STRING = "s";
119 private static final String ATTR_TYPE_BOOLEAN = "b";
Amith Yamasani5b5aa402014-06-01 20:10:14 -0700120 private static final String ATTR_TYPE_INTEGER = "i";
Fyodor Kupolov262f9952015-03-23 18:55:11 -0700121 private static final String ATTR_TYPE_BUNDLE = "B";
122 private static final String ATTR_TYPE_BUNDLE_ARRAY = "BA";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700123
Amith Yamasani0b285492011-04-14 17:35:23 -0700124 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700125 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700126 private static final String USER_PHOTO_FILENAME = "photo.png";
Adrian Roos1bdff912015-02-17 15:51:35 +0100127 private static final String USER_PHOTO_FILENAME_TMP = USER_PHOTO_FILENAME + ".tmp";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700128
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800129 private static final String RESTRICTIONS_FILE_PREFIX = "res_";
Amith Yamasanifc95e702013-09-26 13:20:17 -0700130 private static final String XML_SUFFIX = ".xml";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800131
Amith Yamasani634cf312012-10-04 17:34:21 -0700132 private static final int MIN_USER_ID = 10;
133
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700134 private static final int USER_VERSION = 5;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700135
Amith Yamasani920ace02012-09-20 22:15:37 -0700136 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
137
Nicolas Prevotb8186812015-08-06 15:00:03 +0100138 // Maximum number of managed profiles permitted per user is 1. This cannot be increased
Amith Yamasani95ab7842014-08-11 17:09:26 -0700139 // without first making sure that the rest of the framework is prepared for it.
140 private static final int MAX_MANAGED_PROFILES = 1;
141
Andres Moralesc5548c02015-08-05 10:23:12 -0700142 /**
143 * Flag indicating whether device credentials are shared among same-user profiles.
144 */
145 private static final boolean CONFIG_PROFILES_SHARE_CREDENTIAL = true;
146
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700147 // Set of user restrictions, which can only be enforced by the system
148 private static final Set<String> SYSTEM_CONTROLLED_RESTRICTIONS = Sets.newArraySet(
149 UserManager.DISALLOW_RECORD_AUDIO);
150
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800151 static final int WRITE_USER_MSG = 1;
152 static final int WRITE_USER_DELAY = 2*1000; // 2 seconds
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530153
Jeff Sharkey6dce4962015-07-03 18:08:41 -0700154 private static final String XATTR_SERIAL = "user.serial";
155
Dianne Hackborn4428e172012-08-24 17:43:05 -0700156 private final Context mContext;
157 private final PackageManagerService mPm;
158 private final Object mInstallLock;
159 private final Object mPackagesLock;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700160
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800161 private final Handler mHandler;
162
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700163 private final File mUsersDir;
164 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700165
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800166 private final SparseArray<UserInfo> mUsers = new SparseArray<UserInfo>();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800167 private final SparseArray<Bundle> mUserRestrictions = new SparseArray<Bundle>();
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530168 private final Bundle mGuestRestrictions = new Bundle();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800169
170 /**
171 * Set of user IDs being actively removed. Removed IDs linger in this set
172 * for several seconds to work around a VFS caching issue.
173 */
174 // @GuardedBy("mPackagesLock")
175 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700176
Amith Yamasani0b285492011-04-14 17:35:23 -0700177 private int[] mUserIds;
Amith Yamasani2a003292012-08-14 18:25:45 -0700178 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700179 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700180
Jason Monk62062992014-05-06 09:55:28 -0400181 private IAppOpsService mAppOpsService;
182
Amith Yamasani258848d2012-08-10 17:06:33 -0700183 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700184
Dianne Hackborn4428e172012-08-24 17:43:05 -0700185 public static UserManagerService getInstance() {
186 synchronized (UserManagerService.class) {
187 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700188 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700189 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700190
191 /**
192 * Available for testing purposes.
193 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700194 UserManagerService(File dataDir, File baseUserPath) {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700195 this(null, null, new Object(), new Object(), dataDir, baseUserPath);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700196 }
197
Dianne Hackborn4428e172012-08-24 17:43:05 -0700198 /**
199 * Called by package manager to create the service. This is closely
200 * associated with the package manager, and the given lock is the
201 * package manager's own lock.
202 */
203 UserManagerService(Context context, PackageManagerService pm,
204 Object installLock, Object packagesLock) {
205 this(context, pm, installLock, packagesLock,
206 Environment.getDataDirectory(),
207 new File(Environment.getDataDirectory(), "user"));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700208 }
209
Dianne Hackborn4428e172012-08-24 17:43:05 -0700210 /**
211 * Available for testing purposes.
212 */
213 private UserManagerService(Context context, PackageManagerService pm,
214 Object installLock, Object packagesLock,
215 File dataDir, File baseUserPath) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700216 mContext = context;
217 mPm = pm;
218 mInstallLock = installLock;
219 mPackagesLock = packagesLock;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800220 mHandler = new MainHandler();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700221 synchronized (mInstallLock) {
222 synchronized (mPackagesLock) {
223 mUsersDir = new File(dataDir, USER_INFO_DIR);
224 mUsersDir.mkdirs();
225 // Make zeroth user directory, for services to migrate their files to that location
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700226 File userZeroDir = new File(mUsersDir, String.valueOf(UserHandle.USER_SYSTEM));
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700227 userZeroDir.mkdirs();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700228 FileUtils.setPermissions(mUsersDir.toString(),
229 FileUtils.S_IRWXU|FileUtils.S_IRWXG
230 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
231 -1, -1);
232 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
Amith Yamasanida0b1682014-11-21 12:58:17 -0800233 initDefaultGuestRestrictions();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700234 readUserListLocked();
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700235 sInstance = this;
236 }
237 }
238 }
239
240 void systemReady() {
241 synchronized (mInstallLock) {
242 synchronized (mPackagesLock) {
Amith Yamasani756901d2012-10-12 12:30:07 -0700243 // Prune out any partially created/partially removed users.
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700244 ArrayList<UserInfo> partials = new ArrayList<UserInfo>();
245 for (int i = 0; i < mUsers.size(); i++) {
246 UserInfo ui = mUsers.valueAt(i);
Adam Lesinskieddeb492014-09-08 17:50:03 -0700247 if ((ui.partial || ui.guestToRemove) && i != 0) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700248 partials.add(ui);
249 }
250 }
251 for (int i = 0; i < partials.size(); i++) {
252 UserInfo ui = partials.get(i);
Amith Yamasania7892482015-08-07 11:09:05 -0700253 Slog.w(LOG_TAG, "Removing partially created user " + ui.id
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700254 + " (name=" + ui.name + ")");
255 removeUserStateLocked(ui.id);
256 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700257 }
Dianne Hackborn4428e172012-08-24 17:43:05 -0700258 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700259 onUserForeground(UserHandle.USER_SYSTEM);
Jason Monk62062992014-05-06 09:55:28 -0400260 mAppOpsService = IAppOpsService.Stub.asInterface(
261 ServiceManager.getService(Context.APP_OPS_SERVICE));
262 for (int i = 0; i < mUserIds.length; ++i) {
263 try {
264 mAppOpsService.setUserRestrictions(mUserRestrictions.get(mUserIds[i]), mUserIds[i]);
265 } catch (RemoteException e) {
266 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
267 }
268 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700269 }
270
271 @Override
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700272 public UserInfo getPrimaryUser() {
273 checkManageUsersPermission("query users");
274 synchronized (mPackagesLock) {
275 for (int i = 0; i < mUsers.size(); i++) {
276 UserInfo ui = mUsers.valueAt(i);
277 if (ui.isPrimary()) {
278 return ui;
279 }
280 }
281 }
282 return null;
283 }
284
285 @Override
Xiaohui Chen594f2082015-08-18 11:04:20 -0700286 public @NonNull List<UserInfo> getUsers(boolean excludeDying) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700287 checkManageUsersPermission("query users");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700288 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700289 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
290 for (int i = 0; i < mUsers.size(); i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700291 UserInfo ui = mUsers.valueAt(i);
292 if (ui.partial) {
293 continue;
294 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800295 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700296 users.add(ui);
Amith Yamasani920ace02012-09-20 22:15:37 -0700297 }
Amith Yamasani13593602012-03-22 16:16:17 -0700298 }
299 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700300 }
Amith Yamasani13593602012-03-22 16:16:17 -0700301 }
302
Amith Yamasani258848d2012-08-10 17:06:33 -0700303 @Override
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100304 public List<UserInfo> getProfiles(int userId, boolean enabledOnly) {
Amith Yamasani4f582632014-02-19 14:31:52 -0800305 if (userId != UserHandle.getCallingUserId()) {
306 checkManageUsersPermission("getting profiles related to user " + userId);
307 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700308 final long ident = Binder.clearCallingIdentity();
309 try {
310 synchronized (mPackagesLock) {
311 return getProfilesLocked(userId, enabledOnly);
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100312 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700313 } finally {
314 Binder.restoreCallingIdentity(ident);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000315 }
316 }
317
Amith Yamasanibe465322014-04-24 13:45:17 -0700318 /** Assume permissions already checked and caller's identity cleared */
319 private List<UserInfo> getProfilesLocked(int userId, boolean enabledOnly) {
Amith Yamasanibe465322014-04-24 13:45:17 -0700320 UserInfo user = getUserInfoLocked(userId);
321 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasanidda003f2014-08-28 18:06:51 -0700322 if (user == null) {
323 // Probably a dying user
324 return users;
325 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700326 for (int i = 0; i < mUsers.size(); i++) {
327 UserInfo profile = mUsers.valueAt(i);
328 if (!isProfileOf(user, profile)) {
329 continue;
330 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100331 if (enabledOnly && !profile.isEnabled()) {
332 continue;
Amith Yamasanibe465322014-04-24 13:45:17 -0700333 }
Amith Yamasani70fcf0c2014-07-11 08:40:19 -0700334 if (mRemovingUserIds.get(profile.id)) {
335 continue;
336 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700337 users.add(profile);
338 }
339 return users;
340 }
341
Jessica Hummelbe81c802014-04-22 15:49:22 +0100342 @Override
Andres Moralesc5548c02015-08-05 10:23:12 -0700343 public int getCredentialOwnerProfile(int userHandle) {
344 checkManageUsersPermission("get the credential owner");
345 if (CONFIG_PROFILES_SHARE_CREDENTIAL) {
346 synchronized (mPackagesLock) {
347 UserInfo profileParent = getProfileParentLocked(userHandle);
348 if (profileParent != null) {
349 return profileParent.id;
350 }
351 }
352 }
353
354 return userHandle;
355 }
356
357 @Override
Jessica Hummelbe81c802014-04-22 15:49:22 +0100358 public UserInfo getProfileParent(int userHandle) {
359 checkManageUsersPermission("get the profile parent");
360 synchronized (mPackagesLock) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700361 return getProfileParentLocked(userHandle);
362 }
363 }
364
365 private UserInfo getProfileParentLocked(int userHandle) {
366 UserInfo profile = getUserInfoLocked(userHandle);
367 if (profile == null) {
368 return null;
369 }
370 int parentUserId = profile.profileGroupId;
371 if (parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
372 return null;
373 } else {
374 return getUserInfoLocked(parentUserId);
Jessica Hummelbe81c802014-04-22 15:49:22 +0100375 }
376 }
377
Kenny Guy2a764942014-04-02 13:29:20 +0100378 private boolean isProfileOf(UserInfo user, UserInfo profile) {
379 return user.id == profile.id ||
380 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
381 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000382 }
383
384 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100385 public void setUserEnabled(int userId) {
386 checkManageUsersPermission("enable user");
387 synchronized (mPackagesLock) {
388 UserInfo info = getUserInfoLocked(userId);
389 if (info != null && !info.isEnabled()) {
390 info.flags ^= UserInfo.FLAG_DISABLED;
391 writeUserLocked(info);
392 }
393 }
394 }
395
396 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700397 public UserInfo getUserInfo(int userId) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700398 checkManageUsersPermission("query user");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700399 synchronized (mPackagesLock) {
Amith Yamasani195263742012-08-21 15:40:12 -0700400 return getUserInfoLocked(userId);
Amith Yamasani13593602012-03-22 16:16:17 -0700401 }
402 }
403
Amith Yamasani71e6c692013-03-24 17:39:28 -0700404 @Override
405 public boolean isRestricted() {
406 synchronized (mPackagesLock) {
407 return getUserInfoLocked(UserHandle.getCallingUserId()).isRestricted();
408 }
409 }
410
Amith Yamasani195263742012-08-21 15:40:12 -0700411 /*
412 * Should be locked on mUsers before calling this.
413 */
414 private UserInfo getUserInfoLocked(int userId) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700415 UserInfo ui = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -0700416 // If it is partial and not in the process of being removed, return as unknown user.
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800417 if (ui != null && ui.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700418 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
419 return null;
420 }
421 return ui;
Amith Yamasani195263742012-08-21 15:40:12 -0700422 }
423
Amith Yamasani236b2b52015-08-18 14:32:14 -0700424 /** Called by PackageManagerService */
Amith Yamasani13593602012-03-22 16:16:17 -0700425 public boolean exists(int userId) {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700426 synchronized (mPackagesLock) {
Amith Yamasani236b2b52015-08-18 14:32:14 -0700427 return mUsers.get(userId) != null;
Amith Yamasani13593602012-03-22 16:16:17 -0700428 }
429 }
430
Amith Yamasani258848d2012-08-10 17:06:33 -0700431 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700432 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700433 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700434 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700435 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700436 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700437 if (info == null || info.partial) {
438 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
439 return;
440 }
Amith Yamasani13593602012-03-22 16:16:17 -0700441 if (name != null && !name.equals(info.name)) {
442 info.name = name;
443 writeUserLocked(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700444 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -0700445 }
446 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700447 if (changed) {
448 sendUserInfoChangedBroadcast(userId);
449 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700450 }
451
Amith Yamasani258848d2012-08-10 17:06:33 -0700452 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700453 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700454 checkManageUsersPermission("update users");
Jason Monk9a944532014-07-08 09:31:21 -0400455 long ident = Binder.clearCallingIdentity();
456 try {
457 synchronized (mPackagesLock) {
458 UserInfo info = mUsers.get(userId);
459 if (info == null || info.partial) {
460 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
461 return;
462 }
463 writeBitmapLocked(info, bitmap);
464 writeUserLocked(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700465 }
Jason Monk9a944532014-07-08 09:31:21 -0400466 sendUserInfoChangedBroadcast(userId);
467 } finally {
468 Binder.restoreCallingIdentity(ident);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700469 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700470 }
471
472 private void sendUserInfoChangedBroadcast(int userId) {
473 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
474 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
475 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -0700476 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700477 }
478
Amith Yamasani258848d2012-08-10 17:06:33 -0700479 @Override
Adrian Roos1bdff912015-02-17 15:51:35 +0100480 public ParcelFileDescriptor getUserIcon(int userId) {
481 String iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700482 synchronized (mPackagesLock) {
483 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700484 if (info == null || info.partial) {
485 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + userId);
486 return null;
487 }
Nicolas Prevot88cc3462014-05-14 14:51:48 +0100488 int callingGroupId = mUsers.get(UserHandle.getCallingUserId()).profileGroupId;
489 if (callingGroupId == UserInfo.NO_PROFILE_GROUP_ID
490 || callingGroupId != info.profileGroupId) {
491 checkManageUsersPermission("get the icon of a user who is not related");
492 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700493 if (info.iconPath == null) {
494 return null;
495 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100496 iconPath = info.iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700497 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100498
499 try {
500 return ParcelFileDescriptor.open(
501 new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
502 } catch (FileNotFoundException e) {
503 Log.e(LOG_TAG, "Couldn't find icon file", e);
504 }
505 return null;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700506 }
507
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700508 public void makeInitialized(int userId) {
509 checkManageUsersPermission("makeInitialized");
510 synchronized (mPackagesLock) {
511 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700512 if (info == null || info.partial) {
513 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
514 }
515 if ((info.flags&UserInfo.FLAG_INITIALIZED) == 0) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700516 info.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800517 scheduleWriteUserLocked(info);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700518 }
519 }
520 }
521
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700522 /**
523 * If default guest restrictions haven't been initialized yet, add the basic
524 * restrictions.
525 */
526 private void initDefaultGuestRestrictions() {
527 if (mGuestRestrictions.isEmpty()) {
528 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
Amith Yamasanida0b1682014-11-21 12:58:17 -0800529 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700530 }
531 }
532
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800533 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530534 public Bundle getDefaultGuestRestrictions() {
535 checkManageUsersPermission("getDefaultGuestRestrictions");
536 synchronized (mPackagesLock) {
537 return new Bundle(mGuestRestrictions);
538 }
539 }
540
541 @Override
542 public void setDefaultGuestRestrictions(Bundle restrictions) {
543 checkManageUsersPermission("setDefaultGuestRestrictions");
544 synchronized (mPackagesLock) {
545 mGuestRestrictions.clear();
546 mGuestRestrictions.putAll(restrictions);
547 writeUserListLocked();
548 }
549 }
550
551 @Override
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700552 public boolean hasUserRestriction(String restrictionKey, int userId) {
553 synchronized (mPackagesLock) {
554 Bundle restrictions = mUserRestrictions.get(userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700555 return restrictions != null && restrictions.getBoolean(restrictionKey);
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700556 }
557 }
558
559 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800560 public Bundle getUserRestrictions(int userId) {
561 // checkManageUsersPermission("getUserRestrictions");
562
563 synchronized (mPackagesLock) {
564 Bundle restrictions = mUserRestrictions.get(userId);
Amith Yamasanibe465322014-04-24 13:45:17 -0700565 return restrictions != null ? new Bundle(restrictions) : new Bundle();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800566 }
567 }
568
569 @Override
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700570 public void setUserRestriction(String key, boolean value, int userId) {
Fyodor Kupolovd4b26042015-07-27 14:30:59 -0700571 checkManageUsersPermission("setUserRestriction");
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700572 synchronized (mPackagesLock) {
573 if (!SYSTEM_CONTROLLED_RESTRICTIONS.contains(key)) {
574 Bundle restrictions = getUserRestrictions(userId);
575 restrictions.putBoolean(key, value);
576 setUserRestrictionsInternalLocked(restrictions, userId);
577 }
578 }
579 }
580
581 @Override
582 public void setSystemControlledUserRestriction(String key, boolean value, int userId) {
583 checkSystemOrRoot("setSystemControlledUserRestriction");
584 synchronized (mPackagesLock) {
585 Bundle restrictions = getUserRestrictions(userId);
586 restrictions.putBoolean(key, value);
587 setUserRestrictionsInternalLocked(restrictions, userId);
588 }
589 }
590
591 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800592 public void setUserRestrictions(Bundle restrictions, int userId) {
Amith Yamasanibe465322014-04-24 13:45:17 -0700593 checkManageUsersPermission("setUserRestrictions");
Amith Yamasani0343ec32013-07-22 14:52:06 -0700594 if (restrictions == null) return;
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800595
596 synchronized (mPackagesLock) {
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700597 final Bundle oldUserRestrictions = mUserRestrictions.get(userId);
598 // Restore the original state of system controlled restrictions from oldUserRestrictions
599 for (String key : SYSTEM_CONTROLLED_RESTRICTIONS) {
600 restrictions.remove(key);
601 if (oldUserRestrictions.containsKey(key)) {
602 restrictions.putBoolean(key, oldUserRestrictions.getBoolean(key));
603 }
Jason Monk62062992014-05-06 09:55:28 -0400604 }
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700605 setUserRestrictionsInternalLocked(restrictions, userId);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800606 }
607 }
608
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700609 private void setUserRestrictionsInternalLocked(Bundle restrictions, int userId) {
610 final Bundle userRestrictions = mUserRestrictions.get(userId);
611 userRestrictions.clear();
612 userRestrictions.putAll(restrictions);
613 long token = Binder.clearCallingIdentity();
614 try {
615 mAppOpsService.setUserRestrictions(userRestrictions, userId);
616 } catch (RemoteException e) {
617 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
618 } finally {
619 Binder.restoreCallingIdentity(token);
620 }
621 scheduleWriteUserLocked(mUsers.get(userId));
622 }
623
Amith Yamasani258848d2012-08-10 17:06:33 -0700624 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700625 * Check if we've hit the limit of how many users can be created.
626 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700627 private boolean isUserLimitReachedLocked() {
Nicolas Prevot12678a92015-05-13 12:15:03 -0700628 return getAliveUsersExcludingGuestsCountLocked() >= UserManager.getMaxSupportedUsers();
629 }
630
631 @Override
Nicolas Prevotb8186812015-08-06 15:00:03 +0100632 public boolean canAddMoreManagedProfiles(int userId) {
Nicolas Prevot12678a92015-05-13 12:15:03 -0700633 checkManageUsersPermission("check if more managed profiles can be added.");
634 if (ActivityManager.isLowRamDeviceStatic()) {
635 return false;
636 }
Fyodor Kupolovb6157992015-06-05 15:32:28 -0700637 if (!mContext.getPackageManager().hasSystemFeature(
638 PackageManager.FEATURE_MANAGED_USERS)) {
639 return false;
640 }
Nicolas Prevotb8186812015-08-06 15:00:03 +0100641 // Limit number of managed profiles that can be created
642 int managedProfilesCount = getProfiles(userId, true).size() - 1;
643 if (managedProfilesCount >= MAX_MANAGED_PROFILES) {
644 return false;
645 }
Nicolas Prevot12678a92015-05-13 12:15:03 -0700646 synchronized(mPackagesLock) {
Nicolas Prevotb8186812015-08-06 15:00:03 +0100647 UserInfo userInfo = getUserInfoLocked(userId);
648 if (!userInfo.canHaveProfile()) {
Nicolas Prevot12678a92015-05-13 12:15:03 -0700649 return false;
650 }
651 int usersCount = getAliveUsersExcludingGuestsCountLocked();
652 // We allow creating a managed profile in the special case where there is only one user.
653 return usersCount == 1 || usersCount < UserManager.getMaxSupportedUsers();
654 }
655 }
656
657 private int getAliveUsersExcludingGuestsCountLocked() {
Amith Yamasanif584f012014-05-19 17:57:25 -0700658 int aliveUserCount = 0;
659 final int totalUserCount = mUsers.size();
660 // Skip over users being removed
661 for (int i = 0; i < totalUserCount; i++) {
662 UserInfo user = mUsers.valueAt(i);
Amith Yamasani95ab7842014-08-11 17:09:26 -0700663 if (!mRemovingUserIds.get(user.id)
Amith Yamasani1df14732014-08-29 21:37:27 -0700664 && !user.isGuest() && !user.partial) {
Amith Yamasanif584f012014-05-19 17:57:25 -0700665 aliveUserCount++;
666 }
667 }
Nicolas Prevot12678a92015-05-13 12:15:03 -0700668 return aliveUserCount;
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700669 }
670
671 /**
Amith Yamasani195263742012-08-21 15:40:12 -0700672 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -0700673 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -0700674 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -0700675 *
676 * @param message used as message if SecurityException is thrown
677 * @throws SecurityException if the caller is not system or root
678 */
Amith Yamasanibe465322014-04-24 13:45:17 -0700679 private static final void checkManageUsersPermission(String message) {
Amith Yamasani258848d2012-08-10 17:06:33 -0700680 final int uid = Binder.getCallingUid();
Amith Yamasanibe465322014-04-24 13:45:17 -0700681 if (uid != Process.SYSTEM_UID && uid != 0
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400682 && ActivityManager.checkComponentPermission(
683 android.Manifest.permission.MANAGE_USERS,
Amith Yamasanibe465322014-04-24 13:45:17 -0700684 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
685 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
686 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400687 }
688
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700689 private static void checkSystemOrRoot(String message) {
690 final int uid = Binder.getCallingUid();
691 if (uid != Process.SYSTEM_UID && uid != 0) {
692 throw new SecurityException("Only system may call: " + message);
693 }
694 }
695
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700696 private void writeBitmapLocked(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700697 try {
698 File dir = new File(mUsersDir, Integer.toString(info.id));
699 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +0100700 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700701 if (!dir.exists()) {
702 dir.mkdir();
703 FileUtils.setPermissions(
704 dir.getPath(),
705 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
706 -1, -1);
707 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700708 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +0100709 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
710 && tmp.renameTo(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -0700711 info.iconPath = file.getAbsolutePath();
712 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700713 try {
714 os.close();
715 } catch (IOException ioe) {
716 // What the ... !
717 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100718 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700719 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700720 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700721 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700722 }
723
Amith Yamasani0b285492011-04-14 17:35:23 -0700724 /**
725 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
726 * cache it elsewhere.
727 * @return the array of user ids.
728 */
Dianne Hackborn1676c852012-09-10 14:52:30 -0700729 public int[] getUserIds() {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700730 synchronized (mPackagesLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700731 return mUserIds;
732 }
Amith Yamasani0b285492011-04-14 17:35:23 -0700733 }
734
Dianne Hackborn4428e172012-08-24 17:43:05 -0700735 int[] getUserIdsLPr() {
736 return mUserIds;
737 }
738
Amith Yamasani13593602012-03-22 16:16:17 -0700739 private void readUserListLocked() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700740 if (!mUserListFile.exists()) {
Amith Yamasani13593602012-03-22 16:16:17 -0700741 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700742 return;
743 }
744 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700745 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700746 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700747 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700748 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100749 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700750 int type;
751 while ((type = parser.next()) != XmlPullParser.START_TAG
752 && type != XmlPullParser.END_DOCUMENT) {
753 ;
754 }
755
756 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700757 Slog.e(LOG_TAG, "Unable to read user list");
Amith Yamasani13593602012-03-22 16:16:17 -0700758 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700759 return;
760 }
761
Amith Yamasani2a003292012-08-14 18:25:45 -0700762 mNextSerialNumber = -1;
763 if (parser.getName().equals(TAG_USERS)) {
764 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
765 if (lastSerialNumber != null) {
766 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
767 }
Amith Yamasani6f34b412012-10-22 18:19:27 -0700768 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
769 if (versionNumber != null) {
770 mUserVersion = Integer.parseInt(versionNumber);
771 }
Amith Yamasani2a003292012-08-14 18:25:45 -0700772 }
773
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700774 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530775 if (type == XmlPullParser.START_TAG) {
776 final String name = parser.getName();
777 if (name.equals(TAG_USER)) {
778 String id = parser.getAttributeValue(null, ATTR_ID);
779 UserInfo user = readUserLocked(Integer.parseInt(id));
Amith Yamasani6f34b412012-10-22 18:19:27 -0700780
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530781 if (user != null) {
782 mUsers.put(user.id, user);
783 if (mNextSerialNumber < 0 || mNextSerialNumber <= user.id) {
784 mNextSerialNumber = user.id + 1;
785 }
Amith Yamasani2a003292012-08-14 18:25:45 -0700786 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530787 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -0800788 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
789 && type != XmlPullParser.END_TAG) {
790 if (type == XmlPullParser.START_TAG) {
791 if (parser.getName().equals(TAG_RESTRICTIONS)) {
792 readRestrictionsLocked(parser, mGuestRestrictions);
793 }
794 break;
795 }
796 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700797 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700798 }
799 }
Amith Yamasani13593602012-03-22 16:16:17 -0700800 updateUserIdsLocked();
Amith Yamasani350962c2013-08-06 11:18:53 -0700801 upgradeIfNecessaryLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700802 } catch (IOException ioe) {
Amith Yamasani13593602012-03-22 16:16:17 -0700803 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700804 } catch (XmlPullParserException pe) {
Amith Yamasani13593602012-03-22 16:16:17 -0700805 fallbackToSingleUserLocked();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -0800806 } finally {
807 if (fis != null) {
808 try {
809 fis.close();
810 } catch (IOException e) {
811 }
812 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700813 }
814 }
815
Amith Yamasani6f34b412012-10-22 18:19:27 -0700816 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -0800817 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -0700818 */
Amith Yamasani350962c2013-08-06 11:18:53 -0700819 private void upgradeIfNecessaryLocked() {
Amith Yamasani6f34b412012-10-22 18:19:27 -0700820 int userVersion = mUserVersion;
821 if (userVersion < 1) {
822 // Assign a proper name for the owner, if not initialized correctly before
823 UserInfo user = mUsers.get(UserHandle.USER_OWNER);
824 if ("Primary".equals(user.name)) {
825 user.name = mContext.getResources().getString(com.android.internal.R.string.owner_name);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800826 scheduleWriteUserLocked(user);
Amith Yamasani6f34b412012-10-22 18:19:27 -0700827 }
828 userVersion = 1;
829 }
830
Amith Yamasanibc9625052012-11-15 14:39:18 -0800831 if (userVersion < 2) {
832 // Owner should be marked as initialized
833 UserInfo user = mUsers.get(UserHandle.USER_OWNER);
834 if ((user.flags & UserInfo.FLAG_INITIALIZED) == 0) {
835 user.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800836 scheduleWriteUserLocked(user);
Amith Yamasanibc9625052012-11-15 14:39:18 -0800837 }
838 userVersion = 2;
839 }
840
Amith Yamasani350962c2013-08-06 11:18:53 -0700841
Amith Yamasani5e486f52013-08-07 11:06:44 -0700842 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -0700843 userVersion = 4;
844 }
845
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700846 if (userVersion < 5) {
847 initDefaultGuestRestrictions();
848 userVersion = 5;
849 }
850
Amith Yamasani6f34b412012-10-22 18:19:27 -0700851 if (userVersion < USER_VERSION) {
852 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
853 + USER_VERSION);
854 } else {
855 mUserVersion = userVersion;
856 writeUserListLocked();
857 }
858 }
859
Amith Yamasani13593602012-03-22 16:16:17 -0700860 private void fallbackToSingleUserLocked() {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -0700861 int flags = UserInfo.FLAG_INITIALIZED;
862 // In split system user mode, the admin and primary flags are assigned to the first human
863 // user.
864 if (!UserManager.isSplitSystemUser()) {
865 flags |= UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY;
866 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700867 // Create the system user
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700868 UserInfo system = new UserInfo(UserHandle.USER_SYSTEM,
Amith Yamasani6f34b412012-10-22 18:19:27 -0700869 mContext.getResources().getString(com.android.internal.R.string.owner_name), null,
Xiaohui Chenb31e14a2015-07-13 16:04:55 -0700870 flags);
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700871 mUsers.put(system.id, system);
Amith Yamasani634cf312012-10-04 17:34:21 -0700872 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -0400873 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -0800874
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -0500875 Bundle restrictions = new Bundle();
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700876 mUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions);
Amith Yamasani67df64b2012-12-14 12:09:36 -0800877
Amith Yamasani13593602012-03-22 16:16:17 -0700878 updateUserIdsLocked();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700879 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700880
Amith Yamasani13593602012-03-22 16:16:17 -0700881 writeUserListLocked();
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700882 writeUserLocked(system);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700883 }
884
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800885 private void scheduleWriteUserLocked(UserInfo userInfo) {
886 if (!mHandler.hasMessages(WRITE_USER_MSG, userInfo)) {
887 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, userInfo);
888 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
889 }
890 }
891
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700892 /*
893 * Writes the user file in this format:
894 *
895 * <user flags="20039023" id="0">
896 * <name>Primary</name>
897 * </user>
898 */
Amith Yamasani13593602012-03-22 16:16:17 -0700899 private void writeUserLocked(UserInfo userInfo) {
Amith Yamasani742a6712011-05-04 14:49:28 -0700900 FileOutputStream fos = null;
Amith Yamasanifc95e702013-09-26 13:20:17 -0700901 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userInfo.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700902 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700903 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700904 final BufferedOutputStream bos = new BufferedOutputStream(fos);
905
906 // XmlSerializer serializer = XmlUtils.serializerInstance();
907 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100908 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700909 serializer.startDocument(null, true);
910 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
911
912 serializer.startTag(null, TAG_USER);
913 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
Amith Yamasani2a003292012-08-14 18:25:45 -0700914 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700915 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Amith Yamasani920ace02012-09-20 22:15:37 -0700916 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
917 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
918 Long.toString(userInfo.lastLoggedInTime));
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700919 if (userInfo.iconPath != null) {
920 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
921 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700922 if (userInfo.partial) {
923 serializer.attribute(null, ATTR_PARTIAL, "true");
924 }
Adam Lesinskieddeb492014-09-08 17:50:03 -0700925 if (userInfo.guestToRemove) {
926 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
927 }
Kenny Guy2a764942014-04-02 13:29:20 +0100928 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
929 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
930 Integer.toString(userInfo.profileGroupId));
Kenny Guya52dc3e2014-02-11 15:33:14 +0000931 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700932 if (userInfo.restrictedProfileParentId != UserInfo.NO_PROFILE_GROUP_ID) {
933 serializer.attribute(null, ATTR_RESTRICTED_PROFILE_PARENT_ID,
934 Integer.toString(userInfo.restrictedProfileParentId));
935 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700936 serializer.startTag(null, TAG_NAME);
937 serializer.text(userInfo.name);
938 serializer.endTag(null, TAG_NAME);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800939 Bundle restrictions = mUserRestrictions.get(userInfo.id);
940 if (restrictions != null) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530941 writeRestrictionsLocked(serializer, restrictions);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800942 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700943 serializer.endTag(null, TAG_USER);
944
945 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -0700946 userFile.finishWrite(fos);
947 } catch (Exception ioe) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700948 Slog.e(LOG_TAG, "Error writing user info " + userInfo.id + "\n" + ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -0700949 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700950 }
951 }
952
953 /*
954 * Writes the user list file in this format:
955 *
Amith Yamasani2a003292012-08-14 18:25:45 -0700956 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700957 * <user id="0"></user>
958 * <user id="2"></user>
959 * </users>
960 */
Amith Yamasani13593602012-03-22 16:16:17 -0700961 private void writeUserListLocked() {
Amith Yamasani742a6712011-05-04 14:49:28 -0700962 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700963 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700964 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700965 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700966 final BufferedOutputStream bos = new BufferedOutputStream(fos);
967
968 // XmlSerializer serializer = XmlUtils.serializerInstance();
969 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100970 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700971 serializer.startDocument(null, true);
972 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
973
974 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -0700975 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -0700976 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700977
Adam Lesinskieddeb492014-09-08 17:50:03 -0700978 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530979 writeRestrictionsLocked(serializer, mGuestRestrictions);
980 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700981 for (int i = 0; i < mUsers.size(); i++) {
982 UserInfo user = mUsers.valueAt(i);
983 serializer.startTag(null, TAG_USER);
984 serializer.attribute(null, ATTR_ID, Integer.toString(user.id));
985 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700986 }
987
988 serializer.endTag(null, TAG_USERS);
989
990 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -0700991 userListFile.finishWrite(fos);
992 } catch (Exception e) {
993 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -0700994 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700995 }
996 }
997
Andres Moralesc5548c02015-08-05 10:23:12 -0700998 private void writeRestrictionsLocked(XmlSerializer serializer, Bundle restrictions)
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530999 throws IOException {
1000 serializer.startTag(null, TAG_RESTRICTIONS);
1001 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_WIFI);
1002 writeBoolean(serializer, restrictions, UserManager.DISALLOW_MODIFY_ACCOUNTS);
1003 writeBoolean(serializer, restrictions, UserManager.DISALLOW_INSTALL_APPS);
1004 writeBoolean(serializer, restrictions, UserManager.DISALLOW_UNINSTALL_APPS);
1005 writeBoolean(serializer, restrictions, UserManager.DISALLOW_SHARE_LOCATION);
1006 writeBoolean(serializer, restrictions,
1007 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
1008 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_BLUETOOTH);
1009 writeBoolean(serializer, restrictions, UserManager.DISALLOW_USB_FILE_TRANSFER);
1010 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_CREDENTIALS);
1011 writeBoolean(serializer, restrictions, UserManager.DISALLOW_REMOVE_USER);
1012 writeBoolean(serializer, restrictions, UserManager.DISALLOW_DEBUGGING_FEATURES);
1013 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_VPN);
1014 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_TETHERING);
Stuart Scott94b038b2015-04-20 14:07:45 -07001015 writeBoolean(serializer, restrictions, UserManager.DISALLOW_NETWORK_RESET);
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301016 writeBoolean(serializer, restrictions, UserManager.DISALLOW_FACTORY_RESET);
1017 writeBoolean(serializer, restrictions, UserManager.DISALLOW_ADD_USER);
1018 writeBoolean(serializer, restrictions, UserManager.ENSURE_VERIFY_APPS);
1019 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_CELL_BROADCASTS);
1020 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS);
1021 writeBoolean(serializer, restrictions, UserManager.DISALLOW_APPS_CONTROL);
1022 writeBoolean(serializer, restrictions, UserManager.DISALLOW_MOUNT_PHYSICAL_MEDIA);
1023 writeBoolean(serializer, restrictions, UserManager.DISALLOW_UNMUTE_MICROPHONE);
1024 writeBoolean(serializer, restrictions, UserManager.DISALLOW_ADJUST_VOLUME);
Amith Yamasani390989d2014-07-17 10:52:03 -07001025 writeBoolean(serializer, restrictions, UserManager.DISALLOW_OUTGOING_CALLS);
1026 writeBoolean(serializer, restrictions, UserManager.DISALLOW_SMS);
Jeff Sharkey2cc03e52015-03-20 11:24:04 -07001027 writeBoolean(serializer, restrictions, UserManager.DISALLOW_FUN);
Jason Monk1c7c3192014-06-26 12:52:18 -04001028 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CREATE_WINDOWS);
Amith Yamasani26af8292014-09-09 09:57:27 -07001029 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CROSS_PROFILE_COPY_PASTE);
1030 writeBoolean(serializer, restrictions, UserManager.DISALLOW_OUTGOING_BEAM);
Benjamin Franzf3ece362015-02-11 10:51:10 +00001031 writeBoolean(serializer, restrictions, UserManager.DISALLOW_WALLPAPER);
Benjamin Franzbff46ba2015-03-05 18:33:51 +00001032 writeBoolean(serializer, restrictions, UserManager.DISALLOW_SAFE_BOOT);
Nicolas Prevotf0029c12015-06-25 14:25:41 -07001033 writeBoolean(serializer, restrictions, UserManager.ALLOW_PARENT_PROFILE_APP_LINKING);
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301034 serializer.endTag(null, TAG_RESTRICTIONS);
1035 }
1036
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001037 private UserInfo readUserLocked(int id) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001038 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -07001039 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001040 String name = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001041 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -07001042 long creationTime = 0L;
1043 long lastLoggedInTime = 0L;
Kenny Guy2a764942014-04-02 13:29:20 +01001044 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001045 int restrictedProfileParentId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001046 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001047 boolean guestToRemove = false;
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001048 Bundle restrictions = new Bundle();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001049
1050 FileInputStream fis = null;
1051 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001052 AtomicFile userFile =
Amith Yamasanifc95e702013-09-26 13:20:17 -07001053 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
Amith Yamasani2a003292012-08-14 18:25:45 -07001054 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001055 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001056 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001057 int type;
1058 while ((type = parser.next()) != XmlPullParser.START_TAG
1059 && type != XmlPullParser.END_DOCUMENT) {
1060 ;
1061 }
1062
1063 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001064 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001065 return null;
1066 }
1067
1068 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001069 int storedId = readIntAttribute(parser, ATTR_ID, -1);
1070 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001071 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001072 return null;
1073 }
Amith Yamasani920ace02012-09-20 22:15:37 -07001074 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
1075 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001076 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -07001077 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
1078 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Kenny Guy2a764942014-04-02 13:29:20 +01001079 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
1080 UserInfo.NO_PROFILE_GROUP_ID);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001081 restrictedProfileParentId = readIntAttribute(parser,
1082 ATTR_RESTRICTED_PROFILE_PARENT_ID, UserInfo.NO_PROFILE_GROUP_ID);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001083 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
1084 if ("true".equals(valueString)) {
1085 partial = true;
1086 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001087 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
1088 if ("true".equals(valueString)) {
1089 guestToRemove = true;
1090 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001091
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001092 int outerDepth = parser.getDepth();
1093 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1094 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1095 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1096 continue;
1097 }
1098 String tag = parser.getName();
1099 if (TAG_NAME.equals(tag)) {
1100 type = parser.next();
1101 if (type == XmlPullParser.TEXT) {
1102 name = parser.getText();
1103 }
1104 } else if (TAG_RESTRICTIONS.equals(tag)) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301105 readRestrictionsLocked(parser, restrictions);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001106 }
1107 }
1108 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001109
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001110 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -07001111 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -07001112 userInfo.creationTime = creationTime;
1113 userInfo.lastLoggedInTime = lastLoggedInTime;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001114 userInfo.partial = partial;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001115 userInfo.guestToRemove = guestToRemove;
Kenny Guy2a764942014-04-02 13:29:20 +01001116 userInfo.profileGroupId = profileGroupId;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001117 userInfo.restrictedProfileParentId = restrictedProfileParentId;
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001118 mUserRestrictions.append(id, restrictions);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001119 return userInfo;
1120
1121 } catch (IOException ioe) {
1122 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001123 } finally {
1124 if (fis != null) {
1125 try {
1126 fis.close();
1127 } catch (IOException e) {
1128 }
1129 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001130 }
1131 return null;
1132 }
1133
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301134 private void readRestrictionsLocked(XmlPullParser parser, Bundle restrictions)
1135 throws IOException {
1136 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_WIFI);
1137 readBoolean(parser, restrictions, UserManager.DISALLOW_MODIFY_ACCOUNTS);
1138 readBoolean(parser, restrictions, UserManager.DISALLOW_INSTALL_APPS);
1139 readBoolean(parser, restrictions, UserManager.DISALLOW_UNINSTALL_APPS);
1140 readBoolean(parser, restrictions, UserManager.DISALLOW_SHARE_LOCATION);
1141 readBoolean(parser, restrictions,
1142 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
1143 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_BLUETOOTH);
1144 readBoolean(parser, restrictions, UserManager.DISALLOW_USB_FILE_TRANSFER);
1145 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_CREDENTIALS);
1146 readBoolean(parser, restrictions, UserManager.DISALLOW_REMOVE_USER);
1147 readBoolean(parser, restrictions, UserManager.DISALLOW_DEBUGGING_FEATURES);
1148 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_VPN);
1149 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_TETHERING);
Stuart Scott94b038b2015-04-20 14:07:45 -07001150 readBoolean(parser, restrictions, UserManager.DISALLOW_NETWORK_RESET);
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301151 readBoolean(parser, restrictions, UserManager.DISALLOW_FACTORY_RESET);
1152 readBoolean(parser, restrictions, UserManager.DISALLOW_ADD_USER);
1153 readBoolean(parser, restrictions, UserManager.ENSURE_VERIFY_APPS);
1154 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_CELL_BROADCASTS);
1155 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS);
1156 readBoolean(parser, restrictions, UserManager.DISALLOW_APPS_CONTROL);
1157 readBoolean(parser, restrictions,
1158 UserManager.DISALLOW_MOUNT_PHYSICAL_MEDIA);
1159 readBoolean(parser, restrictions, UserManager.DISALLOW_UNMUTE_MICROPHONE);
1160 readBoolean(parser, restrictions, UserManager.DISALLOW_ADJUST_VOLUME);
Amith Yamasani390989d2014-07-17 10:52:03 -07001161 readBoolean(parser, restrictions, UserManager.DISALLOW_OUTGOING_CALLS);
1162 readBoolean(parser, restrictions, UserManager.DISALLOW_SMS);
Jeff Sharkey2cc03e52015-03-20 11:24:04 -07001163 readBoolean(parser, restrictions, UserManager.DISALLOW_FUN);
Jason Monk1c7c3192014-06-26 12:52:18 -04001164 readBoolean(parser, restrictions, UserManager.DISALLOW_CREATE_WINDOWS);
Amith Yamasani26af8292014-09-09 09:57:27 -07001165 readBoolean(parser, restrictions, UserManager.DISALLOW_CROSS_PROFILE_COPY_PASTE);
1166 readBoolean(parser, restrictions, UserManager.DISALLOW_OUTGOING_BEAM);
Benjamin Franzf3ece362015-02-11 10:51:10 +00001167 readBoolean(parser, restrictions, UserManager.DISALLOW_WALLPAPER);
Benjamin Franzbff46ba2015-03-05 18:33:51 +00001168 readBoolean(parser, restrictions, UserManager.DISALLOW_SAFE_BOOT);
Nicolas Prevotf0029c12015-06-25 14:25:41 -07001169 readBoolean(parser, restrictions, UserManager.ALLOW_PARENT_PROFILE_APP_LINKING);
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301170 }
1171
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001172 private void readBoolean(XmlPullParser parser, Bundle restrictions,
1173 String restrictionKey) {
1174 String value = parser.getAttributeValue(null, restrictionKey);
Amith Yamasani71e6c692013-03-24 17:39:28 -07001175 if (value != null) {
1176 restrictions.putBoolean(restrictionKey, Boolean.parseBoolean(value));
1177 }
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001178 }
1179
1180 private void writeBoolean(XmlSerializer xml, Bundle restrictions, String restrictionKey)
1181 throws IOException {
1182 if (restrictions.containsKey(restrictionKey)) {
1183 xml.attribute(null, restrictionKey,
1184 Boolean.toString(restrictions.getBoolean(restrictionKey)));
1185 }
1186 }
1187
Amith Yamasani920ace02012-09-20 22:15:37 -07001188 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
1189 String valueString = parser.getAttributeValue(null, attr);
1190 if (valueString == null) return defaultValue;
1191 try {
1192 return Integer.parseInt(valueString);
1193 } catch (NumberFormatException nfe) {
1194 return defaultValue;
1195 }
1196 }
1197
1198 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
1199 String valueString = parser.getAttributeValue(null, attr);
1200 if (valueString == null) return defaultValue;
1201 try {
1202 return Long.parseLong(valueString);
1203 } catch (NumberFormatException nfe) {
1204 return defaultValue;
1205 }
1206 }
1207
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001208 private boolean isPackageInstalled(String pkg, int userId) {
1209 final ApplicationInfo info = mPm.getApplicationInfo(pkg,
1210 PackageManager.GET_UNINSTALLED_PACKAGES,
1211 userId);
1212 if (info == null || (info.flags&ApplicationInfo.FLAG_INSTALLED) == 0) {
1213 return false;
1214 }
1215 return true;
1216 }
1217
Amith Yamasanib82add22013-07-09 11:24:44 -07001218 /**
Kenny Guyd21b2182014-07-17 16:38:55 +01001219 * Removes all the restrictions files (res_<packagename>) for a given user.
Amith Yamasanib82add22013-07-09 11:24:44 -07001220 * Does not do any permissions checking.
1221 */
Kenny Guyd21b2182014-07-17 16:38:55 +01001222 private void cleanAppRestrictions(int userId) {
Amith Yamasanib82add22013-07-09 11:24:44 -07001223 synchronized (mPackagesLock) {
1224 File dir = Environment.getUserSystemDirectory(userId);
1225 String[] files = dir.list();
1226 if (files == null) return;
1227 for (String fileName : files) {
1228 if (fileName.startsWith(RESTRICTIONS_FILE_PREFIX)) {
1229 File resFile = new File(dir, fileName);
1230 if (resFile.exists()) {
Kenny Guyd21b2182014-07-17 16:38:55 +01001231 resFile.delete();
Amith Yamasanib82add22013-07-09 11:24:44 -07001232 }
1233 }
1234 }
1235 }
1236 }
1237
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001238 /**
1239 * Removes the app restrictions file for a specific package and user id, if it exists.
1240 */
1241 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
1242 synchronized (mPackagesLock) {
1243 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07001244 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001245 if (resFile.exists()) {
1246 resFile.delete();
1247 }
1248 }
1249 }
1250
Kenny Guya52dc3e2014-02-11 15:33:14 +00001251 @Override
Kenny Guy2a764942014-04-02 13:29:20 +01001252 public UserInfo createProfileForUser(String name, int flags, int userId) {
Kenny Guya52dc3e2014-02-11 15:33:14 +00001253 checkManageUsersPermission("Only the system can create users");
Kenny Guy2a764942014-04-02 13:29:20 +01001254 return createUserInternal(name, flags, userId);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001255 }
1256
Amith Yamasani258848d2012-08-10 17:06:33 -07001257 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07001258 public UserInfo createUser(String name, int flags) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001259 checkManageUsersPermission("Only the system can create users");
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001260 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001261 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001262
Jessica Hummelbe81c802014-04-22 15:49:22 +01001263 private UserInfo createUserInternal(String name, int flags, int parentId) {
Julia Reynolds75175022014-06-26 16:35:00 -04001264 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1265 UserManager.DISALLOW_ADD_USER, false)) {
1266 Log.w(LOG_TAG, "Cannot add user. DISALLOW_ADD_USER is enabled.");
1267 return null;
1268 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001269 if (ActivityManager.isLowRamDeviceStatic()) {
1270 return null;
1271 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07001272 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001273 final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001274 final boolean isRestricted = (flags & UserInfo.FLAG_RESTRICTED) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001275 final long ident = Binder.clearCallingIdentity();
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001276 UserInfo userInfo = null;
Amith Yamasanibb054c92015-07-09 14:16:27 -07001277 final int userId;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001278 try {
1279 synchronized (mInstallLock) {
1280 synchronized (mPackagesLock) {
Jessica Hummelbe81c802014-04-22 15:49:22 +01001281 UserInfo parent = null;
1282 if (parentId != UserHandle.USER_NULL) {
1283 parent = getUserInfoLocked(parentId);
1284 if (parent == null) return null;
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001285 }
Nicolas Prevotb8186812015-08-06 15:00:03 +01001286 if (isManagedProfile && !canAddMoreManagedProfiles(parentId)) {
1287 Log.e(LOG_TAG, "Cannot add more managed profiles for user " + parentId);
Nicolas Prevot12678a92015-05-13 12:15:03 -07001288 return null;
1289 }
1290 if (!isGuest && !isManagedProfile && isUserLimitReachedLocked()) {
1291 // If we're not adding a guest user or a managed profile and the limit has
1292 // been reached, cannot add a user.
Amith Yamasani95ab7842014-08-11 17:09:26 -07001293 return null;
1294 }
1295 // If we're adding a guest and there already exists one, bail.
Adam Lesinskieddeb492014-09-08 17:50:03 -07001296 if (isGuest && findCurrentGuestUserLocked() != null) {
Amith Yamasani95ab7842014-08-11 17:09:26 -07001297 return null;
1298 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001299 // In legacy mode, restricted profile's parent can only be the owner user
1300 if (isRestricted && !UserManager.isSplitSystemUser()
1301 && (parentId != UserHandle.USER_SYSTEM)) {
1302 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
1303 return null;
1304 }
1305 if (isRestricted && UserManager.isSplitSystemUser()) {
1306 if (parent == null) {
1307 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be "
1308 + "specified");
1309 return null;
1310 }
1311 if (!parent.canHaveProfile()) {
1312 Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be "
1313 + "created for the specified parent user id " + parentId);
1314 return null;
1315 }
1316 }
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001317 // In split system user mode, we assign the first human user the primary flag.
Xiaohui Chen203243a2015-07-16 11:55:47 -07001318 // And if there is no device owner, we also assign the admin flag to primary
1319 // user.
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001320 if (UserManager.isSplitSystemUser()
Xiaohui Chen203243a2015-07-16 11:55:47 -07001321 && !isGuest && !isManagedProfile && getPrimaryUser() == null) {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001322 flags |= UserInfo.FLAG_PRIMARY;
Xiaohui Chen203243a2015-07-16 11:55:47 -07001323 DevicePolicyManager devicePolicyManager = (DevicePolicyManager)
1324 mContext.getSystemService(Context.DEVICE_POLICY_SERVICE);
1325 if (devicePolicyManager == null
1326 || devicePolicyManager.getDeviceOwner() == null) {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001327 flags |= UserInfo.FLAG_ADMIN;
1328 }
1329 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07001330 userId = getNextAvailableIdLocked();
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001331 userInfo = new UserInfo(userId, name, null, flags);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001332 userInfo.serialNumber = mNextSerialNumber++;
Amith Yamasani920ace02012-09-20 22:15:37 -07001333 long now = System.currentTimeMillis();
1334 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001335 userInfo.partial = true;
Amith Yamasani16389312012-10-17 21:20:14 -07001336 Environment.getUserSystemDirectory(userInfo.id).mkdirs();
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001337 mUsers.put(userId, userInfo);
1338 writeUserListLocked();
Jessica Hummelbe81c802014-04-22 15:49:22 +01001339 if (parent != null) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001340 if (isManagedProfile) {
1341 if (parent.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
1342 parent.profileGroupId = parent.id;
1343 scheduleWriteUserLocked(parent);
1344 }
1345 userInfo.profileGroupId = parent.profileGroupId;
1346 } else if (isRestricted) {
1347 if (!parent.canHaveProfile()) {
1348 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
1349 }
1350 if (parent.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) {
1351 parent.restrictedProfileParentId = parent.id;
1352 scheduleWriteUserLocked(parent);
1353 }
1354 userInfo.restrictedProfileParentId = parent.restrictedProfileParentId;
Kenny Guya52dc3e2014-02-11 15:33:14 +00001355 }
Kenny Guya52dc3e2014-02-11 15:33:14 +00001356 }
Jeff Sharkey6dce4962015-07-03 18:08:41 -07001357 final StorageManager storage = mContext.getSystemService(StorageManager.class);
1358 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
1359 final String volumeUuid = vol.getFsUuid();
1360 try {
1361 final File userDir = Environment.getDataUserDirectory(volumeUuid,
1362 userId);
Jeff Sharkey3bb8c852015-07-06 16:44:23 -07001363 prepareUserDirectory(mContext, volumeUuid, userId);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07001364 enforceSerialNumber(userDir, userInfo.serialNumber);
1365 } catch (IOException e) {
1366 Log.wtf(LOG_TAG, "Failed to create user directory on " + volumeUuid, e);
1367 }
1368 }
1369 mPm.createNewUserLILPw(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001370 userInfo.partial = false;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001371 scheduleWriteUserLocked(userInfo);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001372 updateUserIdsLocked();
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001373 Bundle restrictions = new Bundle();
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001374 mUserRestrictions.append(userId, restrictions);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001375 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07001376 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07001377 mPm.newUserCreated(userId);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001378 if (userInfo != null) {
1379 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
1380 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userInfo.id);
1381 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
1382 android.Manifest.permission.MANAGE_USERS);
1383 }
1384 } finally {
1385 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07001386 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001387 return userInfo;
1388 }
1389
Amith Yamasani0b285492011-04-14 17:35:23 -07001390 /**
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07001391 * @hide
1392 */
1393 public UserInfo createRestrictedProfile(String name, int parentUserId) {
1394 checkManageUsersPermission("setupRestrictedProfile");
1395 final UserInfo user = createProfileForUser(name, UserInfo.FLAG_RESTRICTED, parentUserId);
1396 if (user == null) {
1397 return null;
1398 }
1399 setUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, true, user.id);
1400 // Change the setting before applying the DISALLOW_SHARE_LOCATION restriction, otherwise
1401 // the putIntForUser() will fail.
1402 android.provider.Settings.Secure.putIntForUser(mContext.getContentResolver(),
1403 android.provider.Settings.Secure.LOCATION_MODE,
1404 android.provider.Settings.Secure.LOCATION_MODE_OFF, user.id);
1405 setUserRestriction(UserManager.DISALLOW_SHARE_LOCATION, true, user.id);
1406 return user;
1407 }
1408
1409 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07001410 * Find the current guest user. If the Guest user is partial,
1411 * then do not include it in the results as it is about to die.
Adam Lesinskieddeb492014-09-08 17:50:03 -07001412 */
1413 private UserInfo findCurrentGuestUserLocked() {
1414 final int size = mUsers.size();
1415 for (int i = 0; i < size; i++) {
1416 final UserInfo user = mUsers.valueAt(i);
1417 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
1418 return user;
1419 }
1420 }
1421 return null;
1422 }
1423
1424 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07001425 * Mark this guest user for deletion to allow us to create another guest
1426 * and switch to that user before actually removing this guest.
1427 * @param userHandle the userid of the current guest
1428 * @return whether the user could be marked for deletion
1429 */
1430 public boolean markGuestForDeletion(int userHandle) {
1431 checkManageUsersPermission("Only the system can remove users");
1432 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1433 UserManager.DISALLOW_REMOVE_USER, false)) {
1434 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1435 return false;
1436 }
1437
1438 long ident = Binder.clearCallingIdentity();
1439 try {
1440 final UserInfo user;
1441 synchronized (mPackagesLock) {
1442 user = mUsers.get(userHandle);
1443 if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
1444 return false;
1445 }
1446 if (!user.isGuest()) {
1447 return false;
1448 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001449 // We set this to a guest user that is to be removed. This is a temporary state
1450 // where we are allowed to add new Guest users, even if this one is still not
1451 // removed. This user will still show up in getUserInfo() calls.
1452 // If we don't get around to removing this Guest user, it will be purged on next
1453 // startup.
1454 user.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07001455 // Mark it as disabled, so that it isn't returned any more when
1456 // profiles are queried.
1457 user.flags |= UserInfo.FLAG_DISABLED;
Amith Yamasani1df14732014-08-29 21:37:27 -07001458 writeUserLocked(user);
1459 }
1460 } finally {
1461 Binder.restoreCallingIdentity(ident);
1462 }
1463 return true;
1464 }
1465
1466 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07001467 * Removes a user and all data directories created for that user. This method should be called
1468 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001469 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07001470 */
Amith Yamasani258848d2012-08-10 17:06:33 -07001471 public boolean removeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001472 checkManageUsersPermission("Only the system can remove users");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04001473 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1474 UserManager.DISALLOW_REMOVE_USER, false)) {
1475 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1476 return false;
1477 }
1478
Kenny Guyee58b4f2014-05-23 15:19:53 +01001479 long ident = Binder.clearCallingIdentity();
1480 try {
1481 final UserInfo user;
1482 synchronized (mPackagesLock) {
1483 user = mUsers.get(userHandle);
Kenny Guy17c9d692014-06-13 13:51:42 +01001484 if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01001485 return false;
1486 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08001487
1488 // We remember deleted user IDs to prevent them from being
1489 // reused during the current boot; they can still be reused
1490 // after a reboot.
Kenny Guyee58b4f2014-05-23 15:19:53 +01001491 mRemovingUserIds.put(userHandle, true);
Jeff Sharkey6eb09392014-11-14 15:57:59 -08001492
Kenny Guyee58b4f2014-05-23 15:19:53 +01001493 try {
1494 mAppOpsService.removeUser(userHandle);
1495 } catch (RemoteException e) {
1496 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
1497 }
1498 // Set this to a partially created user, so that the user will be purged
1499 // on next startup, in case the runtime stops now before stopping and
1500 // removing the user completely.
1501 user.partial = true;
1502 // Mark it as disabled, so that it isn't returned any more when
1503 // profiles are queried.
1504 user.flags |= UserInfo.FLAG_DISABLED;
1505 writeUserLocked(user);
1506 }
1507
1508 if (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
1509 && user.isManagedProfile()) {
1510 // Send broadcast to notify system that the user removed was a
1511 // managed user.
1512 sendProfileRemovedBroadcast(user.profileGroupId, user.id);
1513 }
1514
1515 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
1516 int res;
1517 try {
1518 res = ActivityManagerNative.getDefault().stopUser(userHandle,
1519 new IStopUserCallback.Stub() {
1520 @Override
1521 public void userStopped(int userId) {
1522 finishRemoveUser(userId);
1523 }
1524 @Override
1525 public void userStopAborted(int userId) {
1526 }
1527 });
1528 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001529 return false;
1530 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01001531 return res == ActivityManager.USER_OP_SUCCESS;
1532 } finally {
1533 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001534 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001535 }
1536
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001537 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07001538 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001539 // Let other services shutdown any activity and clean up their state before completely
1540 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001541 long ident = Binder.clearCallingIdentity();
1542 try {
1543 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
1544 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001545 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
1546 android.Manifest.permission.MANAGE_USERS,
1547
1548 new BroadcastReceiver() {
1549 @Override
1550 public void onReceive(Context context, Intent intent) {
1551 if (DBG) {
1552 Slog.i(LOG_TAG,
1553 "USER_REMOVED broadcast sent, cleaning up user data "
1554 + userHandle);
1555 }
1556 new Thread() {
1557 public void run() {
1558 synchronized (mInstallLock) {
1559 synchronized (mPackagesLock) {
1560 removeUserStateLocked(userHandle);
1561 }
1562 }
1563 }
1564 }.start();
1565 }
1566 },
1567
1568 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001569 } finally {
1570 Binder.restoreCallingIdentity(ident);
1571 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001572 }
1573
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001574 private void removeUserStateLocked(final int userHandle) {
Paul Crowley85e4e812015-05-19 12:42:00 +01001575 mContext.getSystemService(StorageManager.class)
1576 .deleteUserKey(userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001577 // Cleanup package manager settings
Amith Yamasanidda003f2014-08-28 18:06:51 -07001578 mPm.cleanUpUserLILPw(this, userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001579
1580 // Remove this user from the list
1581 mUsers.remove(userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001582 // Remove user file
Amith Yamasanifc95e702013-09-26 13:20:17 -07001583 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001584 userFile.delete();
1585 // Update the user list
1586 writeUserListLocked();
1587 updateUserIdsLocked();
1588 removeDirectoryRecursive(Environment.getUserSystemDirectory(userHandle));
1589 }
1590
Amith Yamasani61f57372012-08-31 12:12:28 -07001591 private void removeDirectoryRecursive(File parent) {
1592 if (parent.isDirectory()) {
1593 String[] files = parent.list();
1594 for (String filename : files) {
1595 File child = new File(parent, filename);
1596 removeDirectoryRecursive(child);
1597 }
1598 }
1599 parent.delete();
1600 }
1601
Kenny Guyf8d3a232014-05-15 16:09:52 +01001602 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01001603 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01001604 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
1605 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01001606 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
1607 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01001608 }
1609
Amith Yamasani2a003292012-08-14 18:25:45 -07001610 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001611 public Bundle getApplicationRestrictions(String packageName) {
1612 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
1613 }
1614
1615 @Override
1616 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001617 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07001618 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001619 checkManageUsersPermission("Only system can get restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001620 }
1621 synchronized (mPackagesLock) {
1622 // Read the restrictions from XML
1623 return readApplicationRestrictionsLocked(packageName, userId);
1624 }
1625 }
1626
1627 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001628 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001629 int userId) {
1630 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07001631 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001632 checkManageUsersPermission("Only system can set restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001633 }
1634 synchronized (mPackagesLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01001635 if (restrictions == null || restrictions.isEmpty()) {
1636 cleanAppRestrictionsForPackage(packageName, userId);
1637 } else {
1638 // Write the restrictions to XML
1639 writeApplicationRestrictionsLocked(packageName, restrictions, userId);
1640 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001641 }
Robin Lee66e5d962014-04-09 16:44:21 +01001642
Kenny Guyd21b2182014-07-17 16:38:55 +01001643 if (isPackageInstalled(packageName, userId)) {
1644 // Notify package of changes via an intent - only sent to explicitly registered receivers.
1645 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
1646 changeIntent.setPackage(packageName);
1647 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
1648 mContext.sendBroadcastAsUser(changeIntent, new UserHandle(userId));
1649 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001650 }
1651
Amith Yamasani655d0e22013-06-12 14:19:10 -07001652 @Override
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001653 public void removeRestrictions() {
Amith Yamasanibe465322014-04-24 13:45:17 -07001654 checkManageUsersPermission("Only system can remove restrictions");
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001655 final int userHandle = UserHandle.getCallingUserId();
Amith Yamasani5e486f52013-08-07 11:06:44 -07001656 removeRestrictionsForUser(userHandle, true);
Amith Yamasani350962c2013-08-06 11:18:53 -07001657 }
1658
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001659 private void removeRestrictionsForUser(final int userHandle, boolean unhideApps) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001660 synchronized (mPackagesLock) {
1661 // Remove all user restrictions
1662 setUserRestrictions(new Bundle(), userHandle);
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001663 // Remove any app restrictions
Kenny Guyd21b2182014-07-17 16:38:55 +01001664 cleanAppRestrictions(userHandle);
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001665 }
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001666 if (unhideApps) {
1667 unhideAllInstalledAppsForUser(userHandle);
Amith Yamasani5e486f52013-08-07 11:06:44 -07001668 }
1669 }
1670
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001671 private void unhideAllInstalledAppsForUser(final int userHandle) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001672 mHandler.post(new Runnable() {
1673 @Override
1674 public void run() {
1675 List<ApplicationInfo> apps =
1676 mPm.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES,
1677 userHandle).getList();
1678 final long ident = Binder.clearCallingIdentity();
1679 try {
1680 for (ApplicationInfo appInfo : apps) {
1681 if ((appInfo.flags & ApplicationInfo.FLAG_INSTALLED) != 0
Alex Klyubinb9f8a522015-02-03 11:12:59 -08001682 && (appInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HIDDEN)
1683 != 0) {
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001684 mPm.setApplicationHiddenSettingAsUser(appInfo.packageName, false,
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001685 userHandle);
1686 }
1687 }
1688 } finally {
1689 Binder.restoreCallingIdentity(ident);
1690 }
1691 }
1692 });
1693 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001694 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07001695 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001696 try {
1697 return mContext.getPackageManager().getApplicationInfo(packageName,
1698 PackageManager.GET_UNINSTALLED_PACKAGES).uid;
1699 } catch (NameNotFoundException nnfe) {
1700 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07001701 } finally {
1702 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001703 }
1704 }
1705
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001706 private Bundle readApplicationRestrictionsLocked(String packageName,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001707 int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001708 AtomicFile restrictionsFile =
1709 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
1710 packageToRestrictionsFileName(packageName)));
1711 return readApplicationRestrictionsLocked(restrictionsFile);
1712 }
1713
1714 @VisibleForTesting
1715 static Bundle readApplicationRestrictionsLocked(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001716 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001717 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07001718 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07001719 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07001720 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001721
1722 FileInputStream fis = null;
1723 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001724 fis = restrictionsFile.openRead();
1725 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001726 parser.setInput(fis, StandardCharsets.UTF_8.name());
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001727 XmlUtils.nextElement(parser);
1728 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001729 Slog.e(LOG_TAG, "Unable to read restrictions file "
1730 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001731 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001732 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001733 while (parser.next() != XmlPullParser.END_DOCUMENT) {
1734 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001735 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001736 } catch (IOException|XmlPullParserException e) {
1737 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001738 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001739 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001740 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001741 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001742 }
1743
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001744 private static void readEntry(Bundle restrictions, ArrayList<String> values,
1745 XmlPullParser parser) throws XmlPullParserException, IOException {
1746 int type = parser.getEventType();
1747 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
1748 String key = parser.getAttributeValue(null, ATTR_KEY);
1749 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
1750 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
1751 if (multiple != null) {
1752 values.clear();
1753 int count = Integer.parseInt(multiple);
1754 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1755 if (type == XmlPullParser.START_TAG
1756 && parser.getName().equals(TAG_VALUE)) {
1757 values.add(parser.nextText().trim());
1758 count--;
1759 }
1760 }
1761 String [] valueStrings = new String[values.size()];
1762 values.toArray(valueStrings);
1763 restrictions.putStringArray(key, valueStrings);
1764 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
1765 restrictions.putBundle(key, readBundleEntry(parser, values));
1766 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
1767 final int outerDepth = parser.getDepth();
1768 ArrayList<Bundle> bundleList = new ArrayList<>();
1769 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
1770 Bundle childBundle = readBundleEntry(parser, values);
1771 bundleList.add(childBundle);
1772 }
1773 restrictions.putParcelableArray(key,
1774 bundleList.toArray(new Bundle[bundleList.size()]));
1775 } else {
1776 String value = parser.nextText().trim();
1777 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
1778 restrictions.putBoolean(key, Boolean.parseBoolean(value));
1779 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
1780 restrictions.putInt(key, Integer.parseInt(value));
1781 } else {
1782 restrictions.putString(key, value);
1783 }
1784 }
1785 }
1786 }
1787
1788 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
1789 throws IOException, XmlPullParserException {
1790 Bundle childBundle = new Bundle();
1791 final int outerDepth = parser.getDepth();
1792 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
1793 readEntry(childBundle, values, parser);
1794 }
1795 return childBundle;
1796 }
1797
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001798 private void writeApplicationRestrictionsLocked(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001799 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001800 AtomicFile restrictionsFile = new AtomicFile(
1801 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07001802 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001803 writeApplicationRestrictionsLocked(restrictions, restrictionsFile);
1804 }
1805
1806 @VisibleForTesting
1807 static void writeApplicationRestrictionsLocked(Bundle restrictions,
1808 AtomicFile restrictionsFile) {
1809 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001810 try {
1811 fos = restrictionsFile.startWrite();
1812 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1813
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001814 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001815 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001816 serializer.startDocument(null, true);
1817 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1818
1819 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001820 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001821 serializer.endTag(null, TAG_RESTRICTIONS);
1822
1823 serializer.endDocument();
1824 restrictionsFile.finishWrite(fos);
1825 } catch (Exception e) {
1826 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001827 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
1828 }
1829 }
1830
1831 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
1832 throws IOException {
1833 for (String key : restrictions.keySet()) {
1834 Object value = restrictions.get(key);
1835 serializer.startTag(null, TAG_ENTRY);
1836 serializer.attribute(null, ATTR_KEY, key);
1837
1838 if (value instanceof Boolean) {
1839 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
1840 serializer.text(value.toString());
1841 } else if (value instanceof Integer) {
1842 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
1843 serializer.text(value.toString());
1844 } else if (value == null || value instanceof String) {
1845 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
1846 serializer.text(value != null ? (String) value : "");
1847 } else if (value instanceof Bundle) {
1848 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
1849 writeBundle((Bundle) value, serializer);
1850 } else if (value instanceof Parcelable[]) {
1851 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
1852 Parcelable[] array = (Parcelable[]) value;
1853 for (Parcelable parcelable : array) {
1854 if (!(parcelable instanceof Bundle)) {
1855 throw new IllegalArgumentException("bundle-array can only hold Bundles");
1856 }
1857 serializer.startTag(null, TAG_ENTRY);
1858 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
1859 writeBundle((Bundle) parcelable, serializer);
1860 serializer.endTag(null, TAG_ENTRY);
1861 }
1862 } else {
1863 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
1864 String[] values = (String[]) value;
1865 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
1866 for (String choice : values) {
1867 serializer.startTag(null, TAG_VALUE);
1868 serializer.text(choice != null ? choice : "");
1869 serializer.endTag(null, TAG_VALUE);
1870 }
1871 }
1872 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001873 }
1874 }
1875
1876 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07001877 public int getUserSerialNumber(int userHandle) {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001878 synchronized (mPackagesLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001879 if (!exists(userHandle)) return -1;
Amith Yamasani195263742012-08-21 15:40:12 -07001880 return getUserInfoLocked(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07001881 }
1882 }
1883
1884 @Override
1885 public int getUserHandle(int userSerialNumber) {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001886 synchronized (mPackagesLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001887 for (int userId : mUserIds) {
Kenny Guy945f8832015-02-10 15:17:26 +00001888 UserInfo info = getUserInfoLocked(userId);
1889 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07001890 }
1891 // Not found
1892 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07001893 }
1894 }
1895
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07001896 @Override
1897 public long getUserCreationTime(int userHandle) {
1898 int callingUserId = UserHandle.getCallingUserId();
1899 UserInfo userInfo = null;
1900 synchronized (mPackagesLock) {
1901 if (callingUserId == userHandle) {
1902 userInfo = getUserInfoLocked(userHandle);
1903 } else {
1904 UserInfo parent = getProfileParentLocked(userHandle);
1905 if (parent != null && parent.id == callingUserId) {
1906 userInfo = getUserInfoLocked(userHandle);
1907 }
1908 }
1909 }
1910 if (userInfo == null) {
1911 throw new SecurityException("userHandle can only be the calling user or a managed "
1912 + "profile associated with this user");
1913 }
1914 return userInfo.creationTime;
1915 }
1916
Amith Yamasani0b285492011-04-14 17:35:23 -07001917 /**
1918 * Caches the list of user ids in an array, adjusting the array size when necessary.
1919 */
Amith Yamasani13593602012-03-22 16:16:17 -07001920 private void updateUserIdsLocked() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001921 int num = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -07001922 for (int i = 0; i < mUsers.size(); i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001923 if (!mUsers.valueAt(i).partial) {
1924 num++;
1925 }
1926 }
Amith Yamasani16389312012-10-17 21:20:14 -07001927 final int[] newUsers = new int[num];
1928 int n = 0;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001929 for (int i = 0; i < mUsers.size(); i++) {
1930 if (!mUsers.valueAt(i).partial) {
Amith Yamasani16389312012-10-17 21:20:14 -07001931 newUsers[n++] = mUsers.keyAt(i);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001932 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001933 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001934 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07001935 }
1936
1937 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001938 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasani920ace02012-09-20 22:15:37 -07001939 * @param userId the user that was just foregrounded
1940 */
Amith Yamasani06bf8242015-05-08 16:36:21 -07001941 public void onUserForeground(int userId) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001942 synchronized (mPackagesLock) {
1943 UserInfo user = mUsers.get(userId);
1944 long now = System.currentTimeMillis();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001945 if (user == null || user.partial) {
1946 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
1947 return;
1948 }
1949 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001950 user.lastLoggedInTime = now;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001951 scheduleWriteUserLocked(user);
Amith Yamasani920ace02012-09-20 22:15:37 -07001952 }
1953 }
1954 }
1955
1956 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07001957 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani742a6712011-05-04 14:49:28 -07001958 * TODO: May not be a good idea to recycle ids, in case it results in confusion
1959 * for data and battery stats collection, or unexpected cross-talk.
Amith Yamasani0b285492011-04-14 17:35:23 -07001960 * @return
1961 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001962 private int getNextAvailableIdLocked() {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001963 synchronized (mPackagesLock) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001964 int i = MIN_USER_ID;
Amith Yamasani195263742012-08-21 15:40:12 -07001965 while (i < Integer.MAX_VALUE) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001966 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
Amith Yamasani195263742012-08-21 15:40:12 -07001967 break;
1968 }
1969 i++;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001970 }
Amith Yamasani195263742012-08-21 15:40:12 -07001971 return i;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001972 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001973 }
Amith Yamasani920ace02012-09-20 22:15:37 -07001974
Amith Yamasanifc95e702013-09-26 13:20:17 -07001975 private String packageToRestrictionsFileName(String packageName) {
1976 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
1977 }
1978
Jeff Sharkey6dce4962015-07-03 18:08:41 -07001979 /**
1980 * Create new {@code /data/user/[id]} directory and sets default
1981 * permissions.
1982 */
Jeff Sharkey3bb8c852015-07-06 16:44:23 -07001983 public static void prepareUserDirectory(Context context, String volumeUuid, int userId) {
1984 final StorageManager storage = context.getSystemService(StorageManager.class);
1985 final File userDir = Environment.getDataUserDirectory(volumeUuid, userId);
1986 storage.createNewUserDir(userId, userDir);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07001987 }
1988
1989 /**
1990 * Enforce that serial number stored in user directory inode matches the
1991 * given expected value. Gracefully sets the serial number if currently
1992 * undefined.
1993 *
1994 * @throws IOException when problem extracting serial number, or serial
1995 * number is mismatched.
1996 */
1997 public static void enforceSerialNumber(File file, int serialNumber) throws IOException {
1998 final int foundSerial = getSerialNumber(file);
1999 Slog.v(LOG_TAG, "Found " + file + " with serial number " + foundSerial);
2000
2001 if (foundSerial == -1) {
2002 Slog.d(LOG_TAG, "Serial number missing on " + file + "; assuming current is valid");
2003 try {
2004 setSerialNumber(file, serialNumber);
2005 } catch (IOException e) {
2006 Slog.w(LOG_TAG, "Failed to set serial number on " + file, e);
2007 }
2008
2009 } else if (foundSerial != serialNumber) {
2010 throw new IOException("Found serial number " + foundSerial
2011 + " doesn't match expected " + serialNumber);
2012 }
2013 }
2014
2015 /**
2016 * Set serial number stored in user directory inode.
2017 *
2018 * @throws IOException if serial number was already set
2019 */
2020 private static void setSerialNumber(File file, int serialNumber)
2021 throws IOException {
2022 try {
2023 final byte[] buf = Integer.toString(serialNumber).getBytes(StandardCharsets.UTF_8);
2024 Os.setxattr(file.getAbsolutePath(), XATTR_SERIAL, buf, OsConstants.XATTR_CREATE);
2025 } catch (ErrnoException e) {
2026 throw e.rethrowAsIOException();
2027 }
2028 }
2029
2030 /**
2031 * Return serial number stored in user directory inode.
2032 *
2033 * @return parsed serial number, or -1 if not set
2034 */
2035 private static int getSerialNumber(File file) throws IOException {
2036 try {
2037 final byte[] buf = new byte[256];
2038 final int len = Os.getxattr(file.getAbsolutePath(), XATTR_SERIAL, buf);
2039 final String serial = new String(buf, 0, len);
2040 try {
2041 return Integer.parseInt(serial);
2042 } catch (NumberFormatException e) {
2043 throw new IOException("Bad serial number: " + serial);
2044 }
2045 } catch (ErrnoException e) {
2046 if (e.errno == OsConstants.ENODATA) {
2047 return -1;
2048 } else {
2049 throw e.rethrowAsIOException();
2050 }
2051 }
2052 }
2053
Amith Yamasani920ace02012-09-20 22:15:37 -07002054 @Override
2055 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2056 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2057 != PackageManager.PERMISSION_GRANTED) {
2058 pw.println("Permission Denial: can't dump UserManager from from pid="
2059 + Binder.getCallingPid()
2060 + ", uid=" + Binder.getCallingUid()
2061 + " without permission "
2062 + android.Manifest.permission.DUMP);
2063 return;
2064 }
2065
2066 long now = System.currentTimeMillis();
2067 StringBuilder sb = new StringBuilder();
2068 synchronized (mPackagesLock) {
2069 pw.println("Users:");
2070 for (int i = 0; i < mUsers.size(); i++) {
2071 UserInfo user = mUsers.valueAt(i);
2072 if (user == null) continue;
Amith Yamasani634cf312012-10-04 17:34:21 -07002073 pw.print(" "); pw.print(user); pw.print(" serialNo="); pw.print(user.serialNumber);
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002074 if (mRemovingUserIds.get(mUsers.keyAt(i))) pw.print(" <removing> ");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002075 if (user.partial) pw.print(" <partial>");
2076 pw.println();
Amith Yamasani920ace02012-09-20 22:15:37 -07002077 pw.print(" Created: ");
2078 if (user.creationTime == 0) {
2079 pw.println("<unknown>");
2080 } else {
2081 sb.setLength(0);
2082 TimeUtils.formatDuration(now - user.creationTime, sb);
2083 sb.append(" ago");
2084 pw.println(sb);
2085 }
2086 pw.print(" Last logged in: ");
2087 if (user.lastLoggedInTime == 0) {
2088 pw.println("<unknown>");
2089 } else {
2090 sb.setLength(0);
2091 TimeUtils.formatDuration(now - user.lastLoggedInTime, sb);
2092 sb.append(" ago");
2093 pw.println(sb);
2094 }
2095 }
2096 }
2097 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002098
2099 final class MainHandler extends Handler {
2100
2101 @Override
2102 public void handleMessage(Message msg) {
2103 switch (msg.what) {
2104 case WRITE_USER_MSG:
2105 removeMessages(WRITE_USER_MSG, msg.obj);
2106 synchronized (mPackagesLock) {
2107 int userId = ((UserInfo) msg.obj).id;
2108 UserInfo userInfo = mUsers.get(userId);
2109 if (userInfo != null) {
2110 writeUserLocked(userInfo);
2111 }
2112 }
2113 }
2114 }
2115 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07002116
2117 /**
2118 * @param userId
2119 * @return whether the user has been initialized yet
2120 */
2121 boolean isInitialized(int userId) {
2122 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
2123 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002124}