blob: de106a1d0d3c6a3edd5aeb712392020b8ce63fbb [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
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700134 private static final int USER_VERSION = 6;
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
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700411 @Override
412 public boolean canHaveRestrictedProfile(int userId) {
413 checkManageUsersPermission("canHaveRestrictedProfile");
414 synchronized (mPackagesLock) {
415 final UserInfo userInfo = getUserInfoLocked(userId);
416 if (userInfo == null || !userInfo.canHaveProfile()) {
417 return false;
418 }
419 if (!userInfo.isAdmin()) {
420 return false;
421 }
422 }
423 DevicePolicyManager dpm = (DevicePolicyManager) mContext.getSystemService(
424 Context.DEVICE_POLICY_SERVICE);
425 // restricted profile can be created if there is no DO set and the admin user has no PO
426 return dpm.getDeviceOwner() == null && dpm.getProfileOwnerAsUser(userId) == null;
427 }
428
Amith Yamasani195263742012-08-21 15:40:12 -0700429 /*
430 * Should be locked on mUsers before calling this.
431 */
432 private UserInfo getUserInfoLocked(int userId) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700433 UserInfo ui = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -0700434 // If it is partial and not in the process of being removed, return as unknown user.
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800435 if (ui != null && ui.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700436 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
437 return null;
438 }
439 return ui;
Amith Yamasani195263742012-08-21 15:40:12 -0700440 }
441
Amith Yamasani236b2b52015-08-18 14:32:14 -0700442 /** Called by PackageManagerService */
Amith Yamasani13593602012-03-22 16:16:17 -0700443 public boolean exists(int userId) {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700444 synchronized (mPackagesLock) {
Amith Yamasani236b2b52015-08-18 14:32:14 -0700445 return mUsers.get(userId) != null;
Amith Yamasani13593602012-03-22 16:16:17 -0700446 }
447 }
448
Amith Yamasani258848d2012-08-10 17:06:33 -0700449 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700450 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700451 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700452 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700453 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700454 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700455 if (info == null || info.partial) {
456 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
457 return;
458 }
Amith Yamasani13593602012-03-22 16:16:17 -0700459 if (name != null && !name.equals(info.name)) {
460 info.name = name;
461 writeUserLocked(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700462 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -0700463 }
464 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700465 if (changed) {
466 sendUserInfoChangedBroadcast(userId);
467 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700468 }
469
Amith Yamasani258848d2012-08-10 17:06:33 -0700470 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700471 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700472 checkManageUsersPermission("update users");
Jason Monk9a944532014-07-08 09:31:21 -0400473 long ident = Binder.clearCallingIdentity();
474 try {
475 synchronized (mPackagesLock) {
476 UserInfo info = mUsers.get(userId);
477 if (info == null || info.partial) {
478 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
479 return;
480 }
481 writeBitmapLocked(info, bitmap);
482 writeUserLocked(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700483 }
Jason Monk9a944532014-07-08 09:31:21 -0400484 sendUserInfoChangedBroadcast(userId);
485 } finally {
486 Binder.restoreCallingIdentity(ident);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700487 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700488 }
489
490 private void sendUserInfoChangedBroadcast(int userId) {
491 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
492 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
493 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -0700494 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700495 }
496
Amith Yamasani258848d2012-08-10 17:06:33 -0700497 @Override
Adrian Roos1bdff912015-02-17 15:51:35 +0100498 public ParcelFileDescriptor getUserIcon(int userId) {
499 String iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700500 synchronized (mPackagesLock) {
501 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700502 if (info == null || info.partial) {
503 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + userId);
504 return null;
505 }
Nicolas Prevot88cc3462014-05-14 14:51:48 +0100506 int callingGroupId = mUsers.get(UserHandle.getCallingUserId()).profileGroupId;
507 if (callingGroupId == UserInfo.NO_PROFILE_GROUP_ID
508 || callingGroupId != info.profileGroupId) {
509 checkManageUsersPermission("get the icon of a user who is not related");
510 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700511 if (info.iconPath == null) {
512 return null;
513 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100514 iconPath = info.iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700515 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100516
517 try {
518 return ParcelFileDescriptor.open(
519 new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
520 } catch (FileNotFoundException e) {
521 Log.e(LOG_TAG, "Couldn't find icon file", e);
522 }
523 return null;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700524 }
525
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700526 public void makeInitialized(int userId) {
527 checkManageUsersPermission("makeInitialized");
528 synchronized (mPackagesLock) {
529 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700530 if (info == null || info.partial) {
531 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
532 }
533 if ((info.flags&UserInfo.FLAG_INITIALIZED) == 0) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700534 info.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800535 scheduleWriteUserLocked(info);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700536 }
537 }
538 }
539
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700540 /**
541 * If default guest restrictions haven't been initialized yet, add the basic
542 * restrictions.
543 */
544 private void initDefaultGuestRestrictions() {
545 if (mGuestRestrictions.isEmpty()) {
546 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
Amith Yamasanida0b1682014-11-21 12:58:17 -0800547 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700548 }
549 }
550
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800551 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530552 public Bundle getDefaultGuestRestrictions() {
553 checkManageUsersPermission("getDefaultGuestRestrictions");
554 synchronized (mPackagesLock) {
555 return new Bundle(mGuestRestrictions);
556 }
557 }
558
559 @Override
560 public void setDefaultGuestRestrictions(Bundle restrictions) {
561 checkManageUsersPermission("setDefaultGuestRestrictions");
562 synchronized (mPackagesLock) {
563 mGuestRestrictions.clear();
564 mGuestRestrictions.putAll(restrictions);
565 writeUserListLocked();
566 }
567 }
568
569 @Override
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700570 public boolean hasUserRestriction(String restrictionKey, int userId) {
571 synchronized (mPackagesLock) {
572 Bundle restrictions = mUserRestrictions.get(userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700573 return restrictions != null && restrictions.getBoolean(restrictionKey);
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700574 }
575 }
576
577 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800578 public Bundle getUserRestrictions(int userId) {
579 // checkManageUsersPermission("getUserRestrictions");
580
581 synchronized (mPackagesLock) {
582 Bundle restrictions = mUserRestrictions.get(userId);
Amith Yamasanibe465322014-04-24 13:45:17 -0700583 return restrictions != null ? new Bundle(restrictions) : new Bundle();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800584 }
585 }
586
587 @Override
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700588 public void setUserRestriction(String key, boolean value, int userId) {
Fyodor Kupolovd4b26042015-07-27 14:30:59 -0700589 checkManageUsersPermission("setUserRestriction");
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700590 synchronized (mPackagesLock) {
591 if (!SYSTEM_CONTROLLED_RESTRICTIONS.contains(key)) {
592 Bundle restrictions = getUserRestrictions(userId);
593 restrictions.putBoolean(key, value);
594 setUserRestrictionsInternalLocked(restrictions, userId);
595 }
596 }
597 }
598
599 @Override
600 public void setSystemControlledUserRestriction(String key, boolean value, int userId) {
601 checkSystemOrRoot("setSystemControlledUserRestriction");
602 synchronized (mPackagesLock) {
603 Bundle restrictions = getUserRestrictions(userId);
604 restrictions.putBoolean(key, value);
605 setUserRestrictionsInternalLocked(restrictions, userId);
606 }
607 }
608
609 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800610 public void setUserRestrictions(Bundle restrictions, int userId) {
Amith Yamasanibe465322014-04-24 13:45:17 -0700611 checkManageUsersPermission("setUserRestrictions");
Amith Yamasani0343ec32013-07-22 14:52:06 -0700612 if (restrictions == null) return;
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800613
614 synchronized (mPackagesLock) {
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700615 final Bundle oldUserRestrictions = mUserRestrictions.get(userId);
616 // Restore the original state of system controlled restrictions from oldUserRestrictions
617 for (String key : SYSTEM_CONTROLLED_RESTRICTIONS) {
618 restrictions.remove(key);
619 if (oldUserRestrictions.containsKey(key)) {
620 restrictions.putBoolean(key, oldUserRestrictions.getBoolean(key));
621 }
Jason Monk62062992014-05-06 09:55:28 -0400622 }
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700623 setUserRestrictionsInternalLocked(restrictions, userId);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800624 }
625 }
626
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700627 private void setUserRestrictionsInternalLocked(Bundle restrictions, int userId) {
628 final Bundle userRestrictions = mUserRestrictions.get(userId);
629 userRestrictions.clear();
630 userRestrictions.putAll(restrictions);
631 long token = Binder.clearCallingIdentity();
632 try {
633 mAppOpsService.setUserRestrictions(userRestrictions, userId);
634 } catch (RemoteException e) {
635 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
636 } finally {
637 Binder.restoreCallingIdentity(token);
638 }
639 scheduleWriteUserLocked(mUsers.get(userId));
640 }
641
Amith Yamasani258848d2012-08-10 17:06:33 -0700642 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700643 * Check if we've hit the limit of how many users can be created.
644 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700645 private boolean isUserLimitReachedLocked() {
Nicolas Prevot12678a92015-05-13 12:15:03 -0700646 return getAliveUsersExcludingGuestsCountLocked() >= UserManager.getMaxSupportedUsers();
647 }
648
649 @Override
Nicolas Prevotb8186812015-08-06 15:00:03 +0100650 public boolean canAddMoreManagedProfiles(int userId) {
Nicolas Prevot12678a92015-05-13 12:15:03 -0700651 checkManageUsersPermission("check if more managed profiles can be added.");
652 if (ActivityManager.isLowRamDeviceStatic()) {
653 return false;
654 }
Fyodor Kupolovb6157992015-06-05 15:32:28 -0700655 if (!mContext.getPackageManager().hasSystemFeature(
656 PackageManager.FEATURE_MANAGED_USERS)) {
657 return false;
658 }
Nicolas Prevotb8186812015-08-06 15:00:03 +0100659 // Limit number of managed profiles that can be created
660 int managedProfilesCount = getProfiles(userId, true).size() - 1;
661 if (managedProfilesCount >= MAX_MANAGED_PROFILES) {
662 return false;
663 }
Nicolas Prevot12678a92015-05-13 12:15:03 -0700664 synchronized(mPackagesLock) {
Nicolas Prevotb8186812015-08-06 15:00:03 +0100665 UserInfo userInfo = getUserInfoLocked(userId);
666 if (!userInfo.canHaveProfile()) {
Nicolas Prevot12678a92015-05-13 12:15:03 -0700667 return false;
668 }
669 int usersCount = getAliveUsersExcludingGuestsCountLocked();
670 // We allow creating a managed profile in the special case where there is only one user.
671 return usersCount == 1 || usersCount < UserManager.getMaxSupportedUsers();
672 }
673 }
674
675 private int getAliveUsersExcludingGuestsCountLocked() {
Amith Yamasanif584f012014-05-19 17:57:25 -0700676 int aliveUserCount = 0;
677 final int totalUserCount = mUsers.size();
678 // Skip over users being removed
679 for (int i = 0; i < totalUserCount; i++) {
680 UserInfo user = mUsers.valueAt(i);
Amith Yamasani95ab7842014-08-11 17:09:26 -0700681 if (!mRemovingUserIds.get(user.id)
Amith Yamasani1df14732014-08-29 21:37:27 -0700682 && !user.isGuest() && !user.partial) {
Amith Yamasanif584f012014-05-19 17:57:25 -0700683 aliveUserCount++;
684 }
685 }
Nicolas Prevot12678a92015-05-13 12:15:03 -0700686 return aliveUserCount;
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700687 }
688
689 /**
Amith Yamasani195263742012-08-21 15:40:12 -0700690 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -0700691 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -0700692 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -0700693 *
694 * @param message used as message if SecurityException is thrown
695 * @throws SecurityException if the caller is not system or root
696 */
Amith Yamasanibe465322014-04-24 13:45:17 -0700697 private static final void checkManageUsersPermission(String message) {
Amith Yamasani258848d2012-08-10 17:06:33 -0700698 final int uid = Binder.getCallingUid();
Amith Yamasanibe465322014-04-24 13:45:17 -0700699 if (uid != Process.SYSTEM_UID && uid != 0
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400700 && ActivityManager.checkComponentPermission(
701 android.Manifest.permission.MANAGE_USERS,
Amith Yamasanibe465322014-04-24 13:45:17 -0700702 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
703 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
704 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400705 }
706
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700707 private static void checkSystemOrRoot(String message) {
708 final int uid = Binder.getCallingUid();
709 if (uid != Process.SYSTEM_UID && uid != 0) {
710 throw new SecurityException("Only system may call: " + message);
711 }
712 }
713
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700714 private void writeBitmapLocked(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700715 try {
716 File dir = new File(mUsersDir, Integer.toString(info.id));
717 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +0100718 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700719 if (!dir.exists()) {
720 dir.mkdir();
721 FileUtils.setPermissions(
722 dir.getPath(),
723 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
724 -1, -1);
725 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700726 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +0100727 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
728 && tmp.renameTo(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -0700729 info.iconPath = file.getAbsolutePath();
730 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700731 try {
732 os.close();
733 } catch (IOException ioe) {
734 // What the ... !
735 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100736 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700737 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700738 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700739 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700740 }
741
Amith Yamasani0b285492011-04-14 17:35:23 -0700742 /**
743 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
744 * cache it elsewhere.
745 * @return the array of user ids.
746 */
Dianne Hackborn1676c852012-09-10 14:52:30 -0700747 public int[] getUserIds() {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700748 synchronized (mPackagesLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700749 return mUserIds;
750 }
Amith Yamasani0b285492011-04-14 17:35:23 -0700751 }
752
Dianne Hackborn4428e172012-08-24 17:43:05 -0700753 int[] getUserIdsLPr() {
754 return mUserIds;
755 }
756
Amith Yamasani13593602012-03-22 16:16:17 -0700757 private void readUserListLocked() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700758 if (!mUserListFile.exists()) {
Amith Yamasani13593602012-03-22 16:16:17 -0700759 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700760 return;
761 }
762 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700763 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700764 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700765 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700766 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100767 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700768 int type;
769 while ((type = parser.next()) != XmlPullParser.START_TAG
770 && type != XmlPullParser.END_DOCUMENT) {
771 ;
772 }
773
774 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700775 Slog.e(LOG_TAG, "Unable to read user list");
Amith Yamasani13593602012-03-22 16:16:17 -0700776 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700777 return;
778 }
779
Amith Yamasani2a003292012-08-14 18:25:45 -0700780 mNextSerialNumber = -1;
781 if (parser.getName().equals(TAG_USERS)) {
782 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
783 if (lastSerialNumber != null) {
784 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
785 }
Amith Yamasani6f34b412012-10-22 18:19:27 -0700786 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
787 if (versionNumber != null) {
788 mUserVersion = Integer.parseInt(versionNumber);
789 }
Amith Yamasani2a003292012-08-14 18:25:45 -0700790 }
791
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700792 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530793 if (type == XmlPullParser.START_TAG) {
794 final String name = parser.getName();
795 if (name.equals(TAG_USER)) {
796 String id = parser.getAttributeValue(null, ATTR_ID);
797 UserInfo user = readUserLocked(Integer.parseInt(id));
Amith Yamasani6f34b412012-10-22 18:19:27 -0700798
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530799 if (user != null) {
800 mUsers.put(user.id, user);
801 if (mNextSerialNumber < 0 || mNextSerialNumber <= user.id) {
802 mNextSerialNumber = user.id + 1;
803 }
Amith Yamasani2a003292012-08-14 18:25:45 -0700804 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530805 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -0800806 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
807 && type != XmlPullParser.END_TAG) {
808 if (type == XmlPullParser.START_TAG) {
809 if (parser.getName().equals(TAG_RESTRICTIONS)) {
810 readRestrictionsLocked(parser, mGuestRestrictions);
811 }
812 break;
813 }
814 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700815 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700816 }
817 }
Amith Yamasani13593602012-03-22 16:16:17 -0700818 updateUserIdsLocked();
Amith Yamasani350962c2013-08-06 11:18:53 -0700819 upgradeIfNecessaryLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700820 } catch (IOException ioe) {
Amith Yamasani13593602012-03-22 16:16:17 -0700821 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700822 } catch (XmlPullParserException pe) {
Amith Yamasani13593602012-03-22 16:16:17 -0700823 fallbackToSingleUserLocked();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -0800824 } finally {
825 if (fis != null) {
826 try {
827 fis.close();
828 } catch (IOException e) {
829 }
830 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700831 }
832 }
833
Amith Yamasani6f34b412012-10-22 18:19:27 -0700834 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -0800835 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -0700836 */
Amith Yamasani350962c2013-08-06 11:18:53 -0700837 private void upgradeIfNecessaryLocked() {
Amith Yamasani6f34b412012-10-22 18:19:27 -0700838 int userVersion = mUserVersion;
839 if (userVersion < 1) {
840 // Assign a proper name for the owner, if not initialized correctly before
841 UserInfo user = mUsers.get(UserHandle.USER_OWNER);
842 if ("Primary".equals(user.name)) {
843 user.name = mContext.getResources().getString(com.android.internal.R.string.owner_name);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800844 scheduleWriteUserLocked(user);
Amith Yamasani6f34b412012-10-22 18:19:27 -0700845 }
846 userVersion = 1;
847 }
848
Amith Yamasanibc9625052012-11-15 14:39:18 -0800849 if (userVersion < 2) {
850 // Owner should be marked as initialized
851 UserInfo user = mUsers.get(UserHandle.USER_OWNER);
852 if ((user.flags & UserInfo.FLAG_INITIALIZED) == 0) {
853 user.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800854 scheduleWriteUserLocked(user);
Amith Yamasanibc9625052012-11-15 14:39:18 -0800855 }
856 userVersion = 2;
857 }
858
Amith Yamasani350962c2013-08-06 11:18:53 -0700859
Amith Yamasani5e486f52013-08-07 11:06:44 -0700860 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -0700861 userVersion = 4;
862 }
863
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700864 if (userVersion < 5) {
865 initDefaultGuestRestrictions();
866 userVersion = 5;
867 }
868
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700869 if (userVersion < 6) {
870 final boolean splitSystemUser = UserManager.isSplitSystemUser();
871 for (int i = 0; i < mUsers.size(); i++) {
872 UserInfo user = mUsers.valueAt(i);
873 // In non-split mode, only user 0 can have restricted profiles
874 if (!splitSystemUser && user.isRestricted()
875 && (user.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID)) {
876 user.restrictedProfileParentId = UserHandle.USER_SYSTEM;
877 scheduleWriteUserLocked(user);
878 }
879 }
880 userVersion = 6;
881 }
882
Amith Yamasani6f34b412012-10-22 18:19:27 -0700883 if (userVersion < USER_VERSION) {
884 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
885 + USER_VERSION);
886 } else {
887 mUserVersion = userVersion;
888 writeUserListLocked();
889 }
890 }
891
Amith Yamasani13593602012-03-22 16:16:17 -0700892 private void fallbackToSingleUserLocked() {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -0700893 int flags = UserInfo.FLAG_INITIALIZED;
894 // In split system user mode, the admin and primary flags are assigned to the first human
895 // user.
896 if (!UserManager.isSplitSystemUser()) {
897 flags |= UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY;
898 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700899 // Create the system user
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700900 UserInfo system = new UserInfo(UserHandle.USER_SYSTEM,
Amith Yamasani6f34b412012-10-22 18:19:27 -0700901 mContext.getResources().getString(com.android.internal.R.string.owner_name), null,
Xiaohui Chenb31e14a2015-07-13 16:04:55 -0700902 flags);
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700903 mUsers.put(system.id, system);
Amith Yamasani634cf312012-10-04 17:34:21 -0700904 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -0400905 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -0800906
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -0500907 Bundle restrictions = new Bundle();
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700908 mUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions);
Amith Yamasani67df64b2012-12-14 12:09:36 -0800909
Amith Yamasani13593602012-03-22 16:16:17 -0700910 updateUserIdsLocked();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700911 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700912
Amith Yamasani13593602012-03-22 16:16:17 -0700913 writeUserListLocked();
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700914 writeUserLocked(system);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700915 }
916
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800917 private void scheduleWriteUserLocked(UserInfo userInfo) {
918 if (!mHandler.hasMessages(WRITE_USER_MSG, userInfo)) {
919 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, userInfo);
920 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
921 }
922 }
923
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700924 /*
925 * Writes the user file in this format:
926 *
927 * <user flags="20039023" id="0">
928 * <name>Primary</name>
929 * </user>
930 */
Amith Yamasani13593602012-03-22 16:16:17 -0700931 private void writeUserLocked(UserInfo userInfo) {
Amith Yamasani742a6712011-05-04 14:49:28 -0700932 FileOutputStream fos = null;
Amith Yamasanifc95e702013-09-26 13:20:17 -0700933 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userInfo.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700934 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700935 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700936 final BufferedOutputStream bos = new BufferedOutputStream(fos);
937
938 // XmlSerializer serializer = XmlUtils.serializerInstance();
939 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100940 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700941 serializer.startDocument(null, true);
942 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
943
944 serializer.startTag(null, TAG_USER);
945 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
Amith Yamasani2a003292012-08-14 18:25:45 -0700946 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700947 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Amith Yamasani920ace02012-09-20 22:15:37 -0700948 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
949 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
950 Long.toString(userInfo.lastLoggedInTime));
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700951 if (userInfo.iconPath != null) {
952 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
953 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700954 if (userInfo.partial) {
955 serializer.attribute(null, ATTR_PARTIAL, "true");
956 }
Adam Lesinskieddeb492014-09-08 17:50:03 -0700957 if (userInfo.guestToRemove) {
958 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
959 }
Kenny Guy2a764942014-04-02 13:29:20 +0100960 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
961 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
962 Integer.toString(userInfo.profileGroupId));
Kenny Guya52dc3e2014-02-11 15:33:14 +0000963 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700964 if (userInfo.restrictedProfileParentId != UserInfo.NO_PROFILE_GROUP_ID) {
965 serializer.attribute(null, ATTR_RESTRICTED_PROFILE_PARENT_ID,
966 Integer.toString(userInfo.restrictedProfileParentId));
967 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700968 serializer.startTag(null, TAG_NAME);
969 serializer.text(userInfo.name);
970 serializer.endTag(null, TAG_NAME);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800971 Bundle restrictions = mUserRestrictions.get(userInfo.id);
972 if (restrictions != null) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530973 writeRestrictionsLocked(serializer, restrictions);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800974 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700975 serializer.endTag(null, TAG_USER);
976
977 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -0700978 userFile.finishWrite(fos);
979 } catch (Exception ioe) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700980 Slog.e(LOG_TAG, "Error writing user info " + userInfo.id + "\n" + ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -0700981 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700982 }
983 }
984
985 /*
986 * Writes the user list file in this format:
987 *
Amith Yamasani2a003292012-08-14 18:25:45 -0700988 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700989 * <user id="0"></user>
990 * <user id="2"></user>
991 * </users>
992 */
Amith Yamasani13593602012-03-22 16:16:17 -0700993 private void writeUserListLocked() {
Amith Yamasani742a6712011-05-04 14:49:28 -0700994 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700995 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700996 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700997 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700998 final BufferedOutputStream bos = new BufferedOutputStream(fos);
999
1000 // XmlSerializer serializer = XmlUtils.serializerInstance();
1001 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001002 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001003 serializer.startDocument(null, true);
1004 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1005
1006 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -07001007 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -07001008 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001009
Adam Lesinskieddeb492014-09-08 17:50:03 -07001010 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301011 writeRestrictionsLocked(serializer, mGuestRestrictions);
1012 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001013 for (int i = 0; i < mUsers.size(); i++) {
1014 UserInfo user = mUsers.valueAt(i);
1015 serializer.startTag(null, TAG_USER);
1016 serializer.attribute(null, ATTR_ID, Integer.toString(user.id));
1017 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001018 }
1019
1020 serializer.endTag(null, TAG_USERS);
1021
1022 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001023 userListFile.finishWrite(fos);
1024 } catch (Exception e) {
1025 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -07001026 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001027 }
1028 }
1029
Andres Moralesc5548c02015-08-05 10:23:12 -07001030 private void writeRestrictionsLocked(XmlSerializer serializer, Bundle restrictions)
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301031 throws IOException {
1032 serializer.startTag(null, TAG_RESTRICTIONS);
1033 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_WIFI);
1034 writeBoolean(serializer, restrictions, UserManager.DISALLOW_MODIFY_ACCOUNTS);
1035 writeBoolean(serializer, restrictions, UserManager.DISALLOW_INSTALL_APPS);
1036 writeBoolean(serializer, restrictions, UserManager.DISALLOW_UNINSTALL_APPS);
1037 writeBoolean(serializer, restrictions, UserManager.DISALLOW_SHARE_LOCATION);
1038 writeBoolean(serializer, restrictions,
1039 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
1040 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_BLUETOOTH);
1041 writeBoolean(serializer, restrictions, UserManager.DISALLOW_USB_FILE_TRANSFER);
1042 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_CREDENTIALS);
1043 writeBoolean(serializer, restrictions, UserManager.DISALLOW_REMOVE_USER);
1044 writeBoolean(serializer, restrictions, UserManager.DISALLOW_DEBUGGING_FEATURES);
1045 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_VPN);
1046 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_TETHERING);
Stuart Scott94b038b2015-04-20 14:07:45 -07001047 writeBoolean(serializer, restrictions, UserManager.DISALLOW_NETWORK_RESET);
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301048 writeBoolean(serializer, restrictions, UserManager.DISALLOW_FACTORY_RESET);
1049 writeBoolean(serializer, restrictions, UserManager.DISALLOW_ADD_USER);
1050 writeBoolean(serializer, restrictions, UserManager.ENSURE_VERIFY_APPS);
1051 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_CELL_BROADCASTS);
1052 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS);
1053 writeBoolean(serializer, restrictions, UserManager.DISALLOW_APPS_CONTROL);
1054 writeBoolean(serializer, restrictions, UserManager.DISALLOW_MOUNT_PHYSICAL_MEDIA);
1055 writeBoolean(serializer, restrictions, UserManager.DISALLOW_UNMUTE_MICROPHONE);
1056 writeBoolean(serializer, restrictions, UserManager.DISALLOW_ADJUST_VOLUME);
Amith Yamasani390989d2014-07-17 10:52:03 -07001057 writeBoolean(serializer, restrictions, UserManager.DISALLOW_OUTGOING_CALLS);
1058 writeBoolean(serializer, restrictions, UserManager.DISALLOW_SMS);
Jeff Sharkey2cc03e52015-03-20 11:24:04 -07001059 writeBoolean(serializer, restrictions, UserManager.DISALLOW_FUN);
Jason Monk1c7c3192014-06-26 12:52:18 -04001060 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CREATE_WINDOWS);
Amith Yamasani26af8292014-09-09 09:57:27 -07001061 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CROSS_PROFILE_COPY_PASTE);
1062 writeBoolean(serializer, restrictions, UserManager.DISALLOW_OUTGOING_BEAM);
Benjamin Franzf3ece362015-02-11 10:51:10 +00001063 writeBoolean(serializer, restrictions, UserManager.DISALLOW_WALLPAPER);
Benjamin Franzbff46ba2015-03-05 18:33:51 +00001064 writeBoolean(serializer, restrictions, UserManager.DISALLOW_SAFE_BOOT);
Nicolas Prevotf0029c12015-06-25 14:25:41 -07001065 writeBoolean(serializer, restrictions, UserManager.ALLOW_PARENT_PROFILE_APP_LINKING);
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301066 serializer.endTag(null, TAG_RESTRICTIONS);
1067 }
1068
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001069 private UserInfo readUserLocked(int id) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001070 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -07001071 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001072 String name = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001073 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -07001074 long creationTime = 0L;
1075 long lastLoggedInTime = 0L;
Kenny Guy2a764942014-04-02 13:29:20 +01001076 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001077 int restrictedProfileParentId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001078 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001079 boolean guestToRemove = false;
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001080 Bundle restrictions = new Bundle();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001081
1082 FileInputStream fis = null;
1083 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001084 AtomicFile userFile =
Amith Yamasanifc95e702013-09-26 13:20:17 -07001085 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
Amith Yamasani2a003292012-08-14 18:25:45 -07001086 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001087 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001088 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001089 int type;
1090 while ((type = parser.next()) != XmlPullParser.START_TAG
1091 && type != XmlPullParser.END_DOCUMENT) {
1092 ;
1093 }
1094
1095 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001096 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001097 return null;
1098 }
1099
1100 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001101 int storedId = readIntAttribute(parser, ATTR_ID, -1);
1102 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001103 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001104 return null;
1105 }
Amith Yamasani920ace02012-09-20 22:15:37 -07001106 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
1107 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001108 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -07001109 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
1110 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Kenny Guy2a764942014-04-02 13:29:20 +01001111 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
1112 UserInfo.NO_PROFILE_GROUP_ID);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001113 restrictedProfileParentId = readIntAttribute(parser,
1114 ATTR_RESTRICTED_PROFILE_PARENT_ID, UserInfo.NO_PROFILE_GROUP_ID);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001115 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
1116 if ("true".equals(valueString)) {
1117 partial = true;
1118 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001119 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
1120 if ("true".equals(valueString)) {
1121 guestToRemove = true;
1122 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001123
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001124 int outerDepth = parser.getDepth();
1125 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1126 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1127 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1128 continue;
1129 }
1130 String tag = parser.getName();
1131 if (TAG_NAME.equals(tag)) {
1132 type = parser.next();
1133 if (type == XmlPullParser.TEXT) {
1134 name = parser.getText();
1135 }
1136 } else if (TAG_RESTRICTIONS.equals(tag)) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301137 readRestrictionsLocked(parser, restrictions);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001138 }
1139 }
1140 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001141
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001142 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -07001143 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -07001144 userInfo.creationTime = creationTime;
1145 userInfo.lastLoggedInTime = lastLoggedInTime;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001146 userInfo.partial = partial;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001147 userInfo.guestToRemove = guestToRemove;
Kenny Guy2a764942014-04-02 13:29:20 +01001148 userInfo.profileGroupId = profileGroupId;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001149 userInfo.restrictedProfileParentId = restrictedProfileParentId;
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001150 mUserRestrictions.append(id, restrictions);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001151 return userInfo;
1152
1153 } catch (IOException ioe) {
1154 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001155 } finally {
1156 if (fis != null) {
1157 try {
1158 fis.close();
1159 } catch (IOException e) {
1160 }
1161 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001162 }
1163 return null;
1164 }
1165
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301166 private void readRestrictionsLocked(XmlPullParser parser, Bundle restrictions)
1167 throws IOException {
1168 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_WIFI);
1169 readBoolean(parser, restrictions, UserManager.DISALLOW_MODIFY_ACCOUNTS);
1170 readBoolean(parser, restrictions, UserManager.DISALLOW_INSTALL_APPS);
1171 readBoolean(parser, restrictions, UserManager.DISALLOW_UNINSTALL_APPS);
1172 readBoolean(parser, restrictions, UserManager.DISALLOW_SHARE_LOCATION);
1173 readBoolean(parser, restrictions,
1174 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
1175 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_BLUETOOTH);
1176 readBoolean(parser, restrictions, UserManager.DISALLOW_USB_FILE_TRANSFER);
1177 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_CREDENTIALS);
1178 readBoolean(parser, restrictions, UserManager.DISALLOW_REMOVE_USER);
1179 readBoolean(parser, restrictions, UserManager.DISALLOW_DEBUGGING_FEATURES);
1180 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_VPN);
1181 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_TETHERING);
Stuart Scott94b038b2015-04-20 14:07:45 -07001182 readBoolean(parser, restrictions, UserManager.DISALLOW_NETWORK_RESET);
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301183 readBoolean(parser, restrictions, UserManager.DISALLOW_FACTORY_RESET);
1184 readBoolean(parser, restrictions, UserManager.DISALLOW_ADD_USER);
1185 readBoolean(parser, restrictions, UserManager.ENSURE_VERIFY_APPS);
1186 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_CELL_BROADCASTS);
1187 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS);
1188 readBoolean(parser, restrictions, UserManager.DISALLOW_APPS_CONTROL);
1189 readBoolean(parser, restrictions,
1190 UserManager.DISALLOW_MOUNT_PHYSICAL_MEDIA);
1191 readBoolean(parser, restrictions, UserManager.DISALLOW_UNMUTE_MICROPHONE);
1192 readBoolean(parser, restrictions, UserManager.DISALLOW_ADJUST_VOLUME);
Amith Yamasani390989d2014-07-17 10:52:03 -07001193 readBoolean(parser, restrictions, UserManager.DISALLOW_OUTGOING_CALLS);
1194 readBoolean(parser, restrictions, UserManager.DISALLOW_SMS);
Jeff Sharkey2cc03e52015-03-20 11:24:04 -07001195 readBoolean(parser, restrictions, UserManager.DISALLOW_FUN);
Jason Monk1c7c3192014-06-26 12:52:18 -04001196 readBoolean(parser, restrictions, UserManager.DISALLOW_CREATE_WINDOWS);
Amith Yamasani26af8292014-09-09 09:57:27 -07001197 readBoolean(parser, restrictions, UserManager.DISALLOW_CROSS_PROFILE_COPY_PASTE);
1198 readBoolean(parser, restrictions, UserManager.DISALLOW_OUTGOING_BEAM);
Benjamin Franzf3ece362015-02-11 10:51:10 +00001199 readBoolean(parser, restrictions, UserManager.DISALLOW_WALLPAPER);
Benjamin Franzbff46ba2015-03-05 18:33:51 +00001200 readBoolean(parser, restrictions, UserManager.DISALLOW_SAFE_BOOT);
Nicolas Prevotf0029c12015-06-25 14:25:41 -07001201 readBoolean(parser, restrictions, UserManager.ALLOW_PARENT_PROFILE_APP_LINKING);
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301202 }
1203
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001204 private void readBoolean(XmlPullParser parser, Bundle restrictions,
1205 String restrictionKey) {
1206 String value = parser.getAttributeValue(null, restrictionKey);
Amith Yamasani71e6c692013-03-24 17:39:28 -07001207 if (value != null) {
1208 restrictions.putBoolean(restrictionKey, Boolean.parseBoolean(value));
1209 }
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001210 }
1211
1212 private void writeBoolean(XmlSerializer xml, Bundle restrictions, String restrictionKey)
1213 throws IOException {
1214 if (restrictions.containsKey(restrictionKey)) {
1215 xml.attribute(null, restrictionKey,
1216 Boolean.toString(restrictions.getBoolean(restrictionKey)));
1217 }
1218 }
1219
Amith Yamasani920ace02012-09-20 22:15:37 -07001220 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
1221 String valueString = parser.getAttributeValue(null, attr);
1222 if (valueString == null) return defaultValue;
1223 try {
1224 return Integer.parseInt(valueString);
1225 } catch (NumberFormatException nfe) {
1226 return defaultValue;
1227 }
1228 }
1229
1230 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
1231 String valueString = parser.getAttributeValue(null, attr);
1232 if (valueString == null) return defaultValue;
1233 try {
1234 return Long.parseLong(valueString);
1235 } catch (NumberFormatException nfe) {
1236 return defaultValue;
1237 }
1238 }
1239
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001240 private boolean isPackageInstalled(String pkg, int userId) {
1241 final ApplicationInfo info = mPm.getApplicationInfo(pkg,
1242 PackageManager.GET_UNINSTALLED_PACKAGES,
1243 userId);
1244 if (info == null || (info.flags&ApplicationInfo.FLAG_INSTALLED) == 0) {
1245 return false;
1246 }
1247 return true;
1248 }
1249
Amith Yamasanib82add22013-07-09 11:24:44 -07001250 /**
Kenny Guyd21b2182014-07-17 16:38:55 +01001251 * Removes all the restrictions files (res_<packagename>) for a given user.
Amith Yamasanib82add22013-07-09 11:24:44 -07001252 * Does not do any permissions checking.
1253 */
Kenny Guyd21b2182014-07-17 16:38:55 +01001254 private void cleanAppRestrictions(int userId) {
Amith Yamasanib82add22013-07-09 11:24:44 -07001255 synchronized (mPackagesLock) {
1256 File dir = Environment.getUserSystemDirectory(userId);
1257 String[] files = dir.list();
1258 if (files == null) return;
1259 for (String fileName : files) {
1260 if (fileName.startsWith(RESTRICTIONS_FILE_PREFIX)) {
1261 File resFile = new File(dir, fileName);
1262 if (resFile.exists()) {
Kenny Guyd21b2182014-07-17 16:38:55 +01001263 resFile.delete();
Amith Yamasanib82add22013-07-09 11:24:44 -07001264 }
1265 }
1266 }
1267 }
1268 }
1269
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001270 /**
1271 * Removes the app restrictions file for a specific package and user id, if it exists.
1272 */
1273 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
1274 synchronized (mPackagesLock) {
1275 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07001276 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001277 if (resFile.exists()) {
1278 resFile.delete();
1279 }
1280 }
1281 }
1282
Kenny Guya52dc3e2014-02-11 15:33:14 +00001283 @Override
Kenny Guy2a764942014-04-02 13:29:20 +01001284 public UserInfo createProfileForUser(String name, int flags, int userId) {
Kenny Guya52dc3e2014-02-11 15:33:14 +00001285 checkManageUsersPermission("Only the system can create users");
Kenny Guy2a764942014-04-02 13:29:20 +01001286 return createUserInternal(name, flags, userId);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001287 }
1288
Amith Yamasani258848d2012-08-10 17:06:33 -07001289 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07001290 public UserInfo createUser(String name, int flags) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001291 checkManageUsersPermission("Only the system can create users");
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001292 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001293 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001294
Jessica Hummelbe81c802014-04-22 15:49:22 +01001295 private UserInfo createUserInternal(String name, int flags, int parentId) {
Julia Reynolds75175022014-06-26 16:35:00 -04001296 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1297 UserManager.DISALLOW_ADD_USER, false)) {
1298 Log.w(LOG_TAG, "Cannot add user. DISALLOW_ADD_USER is enabled.");
1299 return null;
1300 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001301 if (ActivityManager.isLowRamDeviceStatic()) {
1302 return null;
1303 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07001304 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001305 final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001306 final boolean isRestricted = (flags & UserInfo.FLAG_RESTRICTED) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001307 final long ident = Binder.clearCallingIdentity();
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001308 UserInfo userInfo = null;
Amith Yamasanibb054c92015-07-09 14:16:27 -07001309 final int userId;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001310 try {
1311 synchronized (mInstallLock) {
1312 synchronized (mPackagesLock) {
Jessica Hummelbe81c802014-04-22 15:49:22 +01001313 UserInfo parent = null;
1314 if (parentId != UserHandle.USER_NULL) {
1315 parent = getUserInfoLocked(parentId);
1316 if (parent == null) return null;
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001317 }
Nicolas Prevotb8186812015-08-06 15:00:03 +01001318 if (isManagedProfile && !canAddMoreManagedProfiles(parentId)) {
1319 Log.e(LOG_TAG, "Cannot add more managed profiles for user " + parentId);
Nicolas Prevot12678a92015-05-13 12:15:03 -07001320 return null;
1321 }
1322 if (!isGuest && !isManagedProfile && isUserLimitReachedLocked()) {
1323 // If we're not adding a guest user or a managed profile and the limit has
1324 // been reached, cannot add a user.
Amith Yamasani95ab7842014-08-11 17:09:26 -07001325 return null;
1326 }
1327 // If we're adding a guest and there already exists one, bail.
Adam Lesinskieddeb492014-09-08 17:50:03 -07001328 if (isGuest && findCurrentGuestUserLocked() != null) {
Amith Yamasani95ab7842014-08-11 17:09:26 -07001329 return null;
1330 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001331 // In legacy mode, restricted profile's parent can only be the owner user
1332 if (isRestricted && !UserManager.isSplitSystemUser()
1333 && (parentId != UserHandle.USER_SYSTEM)) {
1334 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
1335 return null;
1336 }
1337 if (isRestricted && UserManager.isSplitSystemUser()) {
1338 if (parent == null) {
1339 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be "
1340 + "specified");
1341 return null;
1342 }
1343 if (!parent.canHaveProfile()) {
1344 Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be "
1345 + "created for the specified parent user id " + parentId);
1346 return null;
1347 }
1348 }
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001349 // In split system user mode, we assign the first human user the primary flag.
Xiaohui Chen203243a2015-07-16 11:55:47 -07001350 // And if there is no device owner, we also assign the admin flag to primary
1351 // user.
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001352 if (UserManager.isSplitSystemUser()
Xiaohui Chen203243a2015-07-16 11:55:47 -07001353 && !isGuest && !isManagedProfile && getPrimaryUser() == null) {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001354 flags |= UserInfo.FLAG_PRIMARY;
Xiaohui Chen203243a2015-07-16 11:55:47 -07001355 DevicePolicyManager devicePolicyManager = (DevicePolicyManager)
1356 mContext.getSystemService(Context.DEVICE_POLICY_SERVICE);
1357 if (devicePolicyManager == null
1358 || devicePolicyManager.getDeviceOwner() == null) {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001359 flags |= UserInfo.FLAG_ADMIN;
1360 }
1361 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07001362 userId = getNextAvailableIdLocked();
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001363 userInfo = new UserInfo(userId, name, null, flags);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001364 userInfo.serialNumber = mNextSerialNumber++;
Amith Yamasani920ace02012-09-20 22:15:37 -07001365 long now = System.currentTimeMillis();
1366 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001367 userInfo.partial = true;
Amith Yamasani16389312012-10-17 21:20:14 -07001368 Environment.getUserSystemDirectory(userInfo.id).mkdirs();
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001369 mUsers.put(userId, userInfo);
1370 writeUserListLocked();
Jessica Hummelbe81c802014-04-22 15:49:22 +01001371 if (parent != null) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001372 if (isManagedProfile) {
1373 if (parent.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
1374 parent.profileGroupId = parent.id;
1375 scheduleWriteUserLocked(parent);
1376 }
1377 userInfo.profileGroupId = parent.profileGroupId;
1378 } else if (isRestricted) {
1379 if (!parent.canHaveProfile()) {
1380 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
1381 }
1382 if (parent.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) {
1383 parent.restrictedProfileParentId = parent.id;
1384 scheduleWriteUserLocked(parent);
1385 }
1386 userInfo.restrictedProfileParentId = parent.restrictedProfileParentId;
Kenny Guya52dc3e2014-02-11 15:33:14 +00001387 }
Kenny Guya52dc3e2014-02-11 15:33:14 +00001388 }
Jeff Sharkey6dce4962015-07-03 18:08:41 -07001389 final StorageManager storage = mContext.getSystemService(StorageManager.class);
1390 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
1391 final String volumeUuid = vol.getFsUuid();
1392 try {
1393 final File userDir = Environment.getDataUserDirectory(volumeUuid,
1394 userId);
Jeff Sharkey3bb8c852015-07-06 16:44:23 -07001395 prepareUserDirectory(mContext, volumeUuid, userId);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07001396 enforceSerialNumber(userDir, userInfo.serialNumber);
1397 } catch (IOException e) {
1398 Log.wtf(LOG_TAG, "Failed to create user directory on " + volumeUuid, e);
1399 }
1400 }
1401 mPm.createNewUserLILPw(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001402 userInfo.partial = false;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001403 scheduleWriteUserLocked(userInfo);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001404 updateUserIdsLocked();
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001405 Bundle restrictions = new Bundle();
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001406 mUserRestrictions.append(userId, restrictions);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001407 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07001408 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07001409 mPm.newUserCreated(userId);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001410 if (userInfo != null) {
1411 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
1412 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userInfo.id);
1413 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
1414 android.Manifest.permission.MANAGE_USERS);
1415 }
1416 } finally {
1417 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07001418 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001419 return userInfo;
1420 }
1421
Amith Yamasani0b285492011-04-14 17:35:23 -07001422 /**
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07001423 * @hide
1424 */
1425 public UserInfo createRestrictedProfile(String name, int parentUserId) {
1426 checkManageUsersPermission("setupRestrictedProfile");
1427 final UserInfo user = createProfileForUser(name, UserInfo.FLAG_RESTRICTED, parentUserId);
1428 if (user == null) {
1429 return null;
1430 }
1431 setUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, true, user.id);
1432 // Change the setting before applying the DISALLOW_SHARE_LOCATION restriction, otherwise
1433 // the putIntForUser() will fail.
1434 android.provider.Settings.Secure.putIntForUser(mContext.getContentResolver(),
1435 android.provider.Settings.Secure.LOCATION_MODE,
1436 android.provider.Settings.Secure.LOCATION_MODE_OFF, user.id);
1437 setUserRestriction(UserManager.DISALLOW_SHARE_LOCATION, true, user.id);
1438 return user;
1439 }
1440
1441 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07001442 * Find the current guest user. If the Guest user is partial,
1443 * then do not include it in the results as it is about to die.
Adam Lesinskieddeb492014-09-08 17:50:03 -07001444 */
1445 private UserInfo findCurrentGuestUserLocked() {
1446 final int size = mUsers.size();
1447 for (int i = 0; i < size; i++) {
1448 final UserInfo user = mUsers.valueAt(i);
1449 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
1450 return user;
1451 }
1452 }
1453 return null;
1454 }
1455
1456 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07001457 * Mark this guest user for deletion to allow us to create another guest
1458 * and switch to that user before actually removing this guest.
1459 * @param userHandle the userid of the current guest
1460 * @return whether the user could be marked for deletion
1461 */
1462 public boolean markGuestForDeletion(int userHandle) {
1463 checkManageUsersPermission("Only the system can remove users");
1464 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1465 UserManager.DISALLOW_REMOVE_USER, false)) {
1466 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1467 return false;
1468 }
1469
1470 long ident = Binder.clearCallingIdentity();
1471 try {
1472 final UserInfo user;
1473 synchronized (mPackagesLock) {
1474 user = mUsers.get(userHandle);
1475 if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
1476 return false;
1477 }
1478 if (!user.isGuest()) {
1479 return false;
1480 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001481 // We set this to a guest user that is to be removed. This is a temporary state
1482 // where we are allowed to add new Guest users, even if this one is still not
1483 // removed. This user will still show up in getUserInfo() calls.
1484 // If we don't get around to removing this Guest user, it will be purged on next
1485 // startup.
1486 user.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07001487 // Mark it as disabled, so that it isn't returned any more when
1488 // profiles are queried.
1489 user.flags |= UserInfo.FLAG_DISABLED;
Amith Yamasani1df14732014-08-29 21:37:27 -07001490 writeUserLocked(user);
1491 }
1492 } finally {
1493 Binder.restoreCallingIdentity(ident);
1494 }
1495 return true;
1496 }
1497
1498 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07001499 * Removes a user and all data directories created for that user. This method should be called
1500 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001501 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07001502 */
Amith Yamasani258848d2012-08-10 17:06:33 -07001503 public boolean removeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001504 checkManageUsersPermission("Only the system can remove users");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04001505 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1506 UserManager.DISALLOW_REMOVE_USER, false)) {
1507 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1508 return false;
1509 }
1510
Kenny Guyee58b4f2014-05-23 15:19:53 +01001511 long ident = Binder.clearCallingIdentity();
1512 try {
1513 final UserInfo user;
1514 synchronized (mPackagesLock) {
1515 user = mUsers.get(userHandle);
Kenny Guy17c9d692014-06-13 13:51:42 +01001516 if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01001517 return false;
1518 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08001519
1520 // We remember deleted user IDs to prevent them from being
1521 // reused during the current boot; they can still be reused
1522 // after a reboot.
Kenny Guyee58b4f2014-05-23 15:19:53 +01001523 mRemovingUserIds.put(userHandle, true);
Jeff Sharkey6eb09392014-11-14 15:57:59 -08001524
Kenny Guyee58b4f2014-05-23 15:19:53 +01001525 try {
1526 mAppOpsService.removeUser(userHandle);
1527 } catch (RemoteException e) {
1528 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
1529 }
1530 // Set this to a partially created user, so that the user will be purged
1531 // on next startup, in case the runtime stops now before stopping and
1532 // removing the user completely.
1533 user.partial = true;
1534 // Mark it as disabled, so that it isn't returned any more when
1535 // profiles are queried.
1536 user.flags |= UserInfo.FLAG_DISABLED;
1537 writeUserLocked(user);
1538 }
1539
1540 if (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
1541 && user.isManagedProfile()) {
1542 // Send broadcast to notify system that the user removed was a
1543 // managed user.
1544 sendProfileRemovedBroadcast(user.profileGroupId, user.id);
1545 }
1546
1547 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
1548 int res;
1549 try {
1550 res = ActivityManagerNative.getDefault().stopUser(userHandle,
1551 new IStopUserCallback.Stub() {
1552 @Override
1553 public void userStopped(int userId) {
1554 finishRemoveUser(userId);
1555 }
1556 @Override
1557 public void userStopAborted(int userId) {
1558 }
1559 });
1560 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001561 return false;
1562 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01001563 return res == ActivityManager.USER_OP_SUCCESS;
1564 } finally {
1565 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001566 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001567 }
1568
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001569 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07001570 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001571 // Let other services shutdown any activity and clean up their state before completely
1572 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001573 long ident = Binder.clearCallingIdentity();
1574 try {
1575 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
1576 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001577 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
1578 android.Manifest.permission.MANAGE_USERS,
1579
1580 new BroadcastReceiver() {
1581 @Override
1582 public void onReceive(Context context, Intent intent) {
1583 if (DBG) {
1584 Slog.i(LOG_TAG,
1585 "USER_REMOVED broadcast sent, cleaning up user data "
1586 + userHandle);
1587 }
1588 new Thread() {
1589 public void run() {
1590 synchronized (mInstallLock) {
1591 synchronized (mPackagesLock) {
1592 removeUserStateLocked(userHandle);
1593 }
1594 }
1595 }
1596 }.start();
1597 }
1598 },
1599
1600 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001601 } finally {
1602 Binder.restoreCallingIdentity(ident);
1603 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001604 }
1605
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001606 private void removeUserStateLocked(final int userHandle) {
Paul Crowley85e4e812015-05-19 12:42:00 +01001607 mContext.getSystemService(StorageManager.class)
1608 .deleteUserKey(userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001609 // Cleanup package manager settings
Amith Yamasanidda003f2014-08-28 18:06:51 -07001610 mPm.cleanUpUserLILPw(this, userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001611
1612 // Remove this user from the list
1613 mUsers.remove(userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001614 // Remove user file
Amith Yamasanifc95e702013-09-26 13:20:17 -07001615 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001616 userFile.delete();
1617 // Update the user list
1618 writeUserListLocked();
1619 updateUserIdsLocked();
1620 removeDirectoryRecursive(Environment.getUserSystemDirectory(userHandle));
1621 }
1622
Amith Yamasani61f57372012-08-31 12:12:28 -07001623 private void removeDirectoryRecursive(File parent) {
1624 if (parent.isDirectory()) {
1625 String[] files = parent.list();
1626 for (String filename : files) {
1627 File child = new File(parent, filename);
1628 removeDirectoryRecursive(child);
1629 }
1630 }
1631 parent.delete();
1632 }
1633
Kenny Guyf8d3a232014-05-15 16:09:52 +01001634 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01001635 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01001636 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
1637 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01001638 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
1639 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01001640 }
1641
Amith Yamasani2a003292012-08-14 18:25:45 -07001642 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001643 public Bundle getApplicationRestrictions(String packageName) {
1644 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
1645 }
1646
1647 @Override
1648 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001649 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07001650 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001651 checkManageUsersPermission("Only system can get restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001652 }
1653 synchronized (mPackagesLock) {
1654 // Read the restrictions from XML
1655 return readApplicationRestrictionsLocked(packageName, userId);
1656 }
1657 }
1658
1659 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001660 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001661 int userId) {
1662 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07001663 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001664 checkManageUsersPermission("Only system can set restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001665 }
1666 synchronized (mPackagesLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01001667 if (restrictions == null || restrictions.isEmpty()) {
1668 cleanAppRestrictionsForPackage(packageName, userId);
1669 } else {
1670 // Write the restrictions to XML
1671 writeApplicationRestrictionsLocked(packageName, restrictions, userId);
1672 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001673 }
Robin Lee66e5d962014-04-09 16:44:21 +01001674
Kenny Guyd21b2182014-07-17 16:38:55 +01001675 if (isPackageInstalled(packageName, userId)) {
1676 // Notify package of changes via an intent - only sent to explicitly registered receivers.
1677 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
1678 changeIntent.setPackage(packageName);
1679 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
1680 mContext.sendBroadcastAsUser(changeIntent, new UserHandle(userId));
1681 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001682 }
1683
Amith Yamasani655d0e22013-06-12 14:19:10 -07001684 @Override
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001685 public void removeRestrictions() {
Amith Yamasanibe465322014-04-24 13:45:17 -07001686 checkManageUsersPermission("Only system can remove restrictions");
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001687 final int userHandle = UserHandle.getCallingUserId();
Amith Yamasani5e486f52013-08-07 11:06:44 -07001688 removeRestrictionsForUser(userHandle, true);
Amith Yamasani350962c2013-08-06 11:18:53 -07001689 }
1690
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001691 private void removeRestrictionsForUser(final int userHandle, boolean unhideApps) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001692 synchronized (mPackagesLock) {
1693 // Remove all user restrictions
1694 setUserRestrictions(new Bundle(), userHandle);
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001695 // Remove any app restrictions
Kenny Guyd21b2182014-07-17 16:38:55 +01001696 cleanAppRestrictions(userHandle);
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001697 }
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001698 if (unhideApps) {
1699 unhideAllInstalledAppsForUser(userHandle);
Amith Yamasani5e486f52013-08-07 11:06:44 -07001700 }
1701 }
1702
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001703 private void unhideAllInstalledAppsForUser(final int userHandle) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001704 mHandler.post(new Runnable() {
1705 @Override
1706 public void run() {
1707 List<ApplicationInfo> apps =
1708 mPm.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES,
1709 userHandle).getList();
1710 final long ident = Binder.clearCallingIdentity();
1711 try {
1712 for (ApplicationInfo appInfo : apps) {
1713 if ((appInfo.flags & ApplicationInfo.FLAG_INSTALLED) != 0
Alex Klyubinb9f8a522015-02-03 11:12:59 -08001714 && (appInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HIDDEN)
1715 != 0) {
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001716 mPm.setApplicationHiddenSettingAsUser(appInfo.packageName, false,
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001717 userHandle);
1718 }
1719 }
1720 } finally {
1721 Binder.restoreCallingIdentity(ident);
1722 }
1723 }
1724 });
1725 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001726 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07001727 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001728 try {
1729 return mContext.getPackageManager().getApplicationInfo(packageName,
1730 PackageManager.GET_UNINSTALLED_PACKAGES).uid;
1731 } catch (NameNotFoundException nnfe) {
1732 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07001733 } finally {
1734 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001735 }
1736 }
1737
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001738 private Bundle readApplicationRestrictionsLocked(String packageName,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001739 int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001740 AtomicFile restrictionsFile =
1741 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
1742 packageToRestrictionsFileName(packageName)));
1743 return readApplicationRestrictionsLocked(restrictionsFile);
1744 }
1745
1746 @VisibleForTesting
1747 static Bundle readApplicationRestrictionsLocked(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001748 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001749 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07001750 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07001751 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07001752 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001753
1754 FileInputStream fis = null;
1755 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001756 fis = restrictionsFile.openRead();
1757 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001758 parser.setInput(fis, StandardCharsets.UTF_8.name());
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001759 XmlUtils.nextElement(parser);
1760 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001761 Slog.e(LOG_TAG, "Unable to read restrictions file "
1762 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001763 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001764 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001765 while (parser.next() != XmlPullParser.END_DOCUMENT) {
1766 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001767 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001768 } catch (IOException|XmlPullParserException e) {
1769 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001770 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001771 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001772 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001773 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001774 }
1775
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001776 private static void readEntry(Bundle restrictions, ArrayList<String> values,
1777 XmlPullParser parser) throws XmlPullParserException, IOException {
1778 int type = parser.getEventType();
1779 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
1780 String key = parser.getAttributeValue(null, ATTR_KEY);
1781 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
1782 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
1783 if (multiple != null) {
1784 values.clear();
1785 int count = Integer.parseInt(multiple);
1786 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1787 if (type == XmlPullParser.START_TAG
1788 && parser.getName().equals(TAG_VALUE)) {
1789 values.add(parser.nextText().trim());
1790 count--;
1791 }
1792 }
1793 String [] valueStrings = new String[values.size()];
1794 values.toArray(valueStrings);
1795 restrictions.putStringArray(key, valueStrings);
1796 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
1797 restrictions.putBundle(key, readBundleEntry(parser, values));
1798 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
1799 final int outerDepth = parser.getDepth();
1800 ArrayList<Bundle> bundleList = new ArrayList<>();
1801 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
1802 Bundle childBundle = readBundleEntry(parser, values);
1803 bundleList.add(childBundle);
1804 }
1805 restrictions.putParcelableArray(key,
1806 bundleList.toArray(new Bundle[bundleList.size()]));
1807 } else {
1808 String value = parser.nextText().trim();
1809 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
1810 restrictions.putBoolean(key, Boolean.parseBoolean(value));
1811 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
1812 restrictions.putInt(key, Integer.parseInt(value));
1813 } else {
1814 restrictions.putString(key, value);
1815 }
1816 }
1817 }
1818 }
1819
1820 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
1821 throws IOException, XmlPullParserException {
1822 Bundle childBundle = new Bundle();
1823 final int outerDepth = parser.getDepth();
1824 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
1825 readEntry(childBundle, values, parser);
1826 }
1827 return childBundle;
1828 }
1829
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001830 private void writeApplicationRestrictionsLocked(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001831 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001832 AtomicFile restrictionsFile = new AtomicFile(
1833 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07001834 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001835 writeApplicationRestrictionsLocked(restrictions, restrictionsFile);
1836 }
1837
1838 @VisibleForTesting
1839 static void writeApplicationRestrictionsLocked(Bundle restrictions,
1840 AtomicFile restrictionsFile) {
1841 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001842 try {
1843 fos = restrictionsFile.startWrite();
1844 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1845
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001846 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001847 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001848 serializer.startDocument(null, true);
1849 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1850
1851 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001852 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001853 serializer.endTag(null, TAG_RESTRICTIONS);
1854
1855 serializer.endDocument();
1856 restrictionsFile.finishWrite(fos);
1857 } catch (Exception e) {
1858 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001859 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
1860 }
1861 }
1862
1863 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
1864 throws IOException {
1865 for (String key : restrictions.keySet()) {
1866 Object value = restrictions.get(key);
1867 serializer.startTag(null, TAG_ENTRY);
1868 serializer.attribute(null, ATTR_KEY, key);
1869
1870 if (value instanceof Boolean) {
1871 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
1872 serializer.text(value.toString());
1873 } else if (value instanceof Integer) {
1874 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
1875 serializer.text(value.toString());
1876 } else if (value == null || value instanceof String) {
1877 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
1878 serializer.text(value != null ? (String) value : "");
1879 } else if (value instanceof Bundle) {
1880 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
1881 writeBundle((Bundle) value, serializer);
1882 } else if (value instanceof Parcelable[]) {
1883 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
1884 Parcelable[] array = (Parcelable[]) value;
1885 for (Parcelable parcelable : array) {
1886 if (!(parcelable instanceof Bundle)) {
1887 throw new IllegalArgumentException("bundle-array can only hold Bundles");
1888 }
1889 serializer.startTag(null, TAG_ENTRY);
1890 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
1891 writeBundle((Bundle) parcelable, serializer);
1892 serializer.endTag(null, TAG_ENTRY);
1893 }
1894 } else {
1895 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
1896 String[] values = (String[]) value;
1897 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
1898 for (String choice : values) {
1899 serializer.startTag(null, TAG_VALUE);
1900 serializer.text(choice != null ? choice : "");
1901 serializer.endTag(null, TAG_VALUE);
1902 }
1903 }
1904 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001905 }
1906 }
1907
1908 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07001909 public int getUserSerialNumber(int userHandle) {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001910 synchronized (mPackagesLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001911 if (!exists(userHandle)) return -1;
Amith Yamasani195263742012-08-21 15:40:12 -07001912 return getUserInfoLocked(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07001913 }
1914 }
1915
1916 @Override
1917 public int getUserHandle(int userSerialNumber) {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001918 synchronized (mPackagesLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001919 for (int userId : mUserIds) {
Kenny Guy945f8832015-02-10 15:17:26 +00001920 UserInfo info = getUserInfoLocked(userId);
1921 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07001922 }
1923 // Not found
1924 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07001925 }
1926 }
1927
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07001928 @Override
1929 public long getUserCreationTime(int userHandle) {
1930 int callingUserId = UserHandle.getCallingUserId();
1931 UserInfo userInfo = null;
1932 synchronized (mPackagesLock) {
1933 if (callingUserId == userHandle) {
1934 userInfo = getUserInfoLocked(userHandle);
1935 } else {
1936 UserInfo parent = getProfileParentLocked(userHandle);
1937 if (parent != null && parent.id == callingUserId) {
1938 userInfo = getUserInfoLocked(userHandle);
1939 }
1940 }
1941 }
1942 if (userInfo == null) {
1943 throw new SecurityException("userHandle can only be the calling user or a managed "
1944 + "profile associated with this user");
1945 }
1946 return userInfo.creationTime;
1947 }
1948
Amith Yamasani0b285492011-04-14 17:35:23 -07001949 /**
1950 * Caches the list of user ids in an array, adjusting the array size when necessary.
1951 */
Amith Yamasani13593602012-03-22 16:16:17 -07001952 private void updateUserIdsLocked() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001953 int num = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -07001954 for (int i = 0; i < mUsers.size(); i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001955 if (!mUsers.valueAt(i).partial) {
1956 num++;
1957 }
1958 }
Amith Yamasani16389312012-10-17 21:20:14 -07001959 final int[] newUsers = new int[num];
1960 int n = 0;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001961 for (int i = 0; i < mUsers.size(); i++) {
1962 if (!mUsers.valueAt(i).partial) {
Amith Yamasani16389312012-10-17 21:20:14 -07001963 newUsers[n++] = mUsers.keyAt(i);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001964 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001965 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001966 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07001967 }
1968
1969 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001970 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasani920ace02012-09-20 22:15:37 -07001971 * @param userId the user that was just foregrounded
1972 */
Amith Yamasani06bf8242015-05-08 16:36:21 -07001973 public void onUserForeground(int userId) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001974 synchronized (mPackagesLock) {
1975 UserInfo user = mUsers.get(userId);
1976 long now = System.currentTimeMillis();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001977 if (user == null || user.partial) {
1978 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
1979 return;
1980 }
1981 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001982 user.lastLoggedInTime = now;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001983 scheduleWriteUserLocked(user);
Amith Yamasani920ace02012-09-20 22:15:37 -07001984 }
1985 }
1986 }
1987
1988 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07001989 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani742a6712011-05-04 14:49:28 -07001990 * TODO: May not be a good idea to recycle ids, in case it results in confusion
1991 * for data and battery stats collection, or unexpected cross-talk.
Amith Yamasani0b285492011-04-14 17:35:23 -07001992 * @return
1993 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001994 private int getNextAvailableIdLocked() {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001995 synchronized (mPackagesLock) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001996 int i = MIN_USER_ID;
Amith Yamasani195263742012-08-21 15:40:12 -07001997 while (i < Integer.MAX_VALUE) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001998 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
Amith Yamasani195263742012-08-21 15:40:12 -07001999 break;
2000 }
2001 i++;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002002 }
Amith Yamasani195263742012-08-21 15:40:12 -07002003 return i;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002004 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002005 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002006
Amith Yamasanifc95e702013-09-26 13:20:17 -07002007 private String packageToRestrictionsFileName(String packageName) {
2008 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
2009 }
2010
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002011 /**
2012 * Create new {@code /data/user/[id]} directory and sets default
2013 * permissions.
2014 */
Jeff Sharkey3bb8c852015-07-06 16:44:23 -07002015 public static void prepareUserDirectory(Context context, String volumeUuid, int userId) {
2016 final StorageManager storage = context.getSystemService(StorageManager.class);
2017 final File userDir = Environment.getDataUserDirectory(volumeUuid, userId);
2018 storage.createNewUserDir(userId, userDir);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002019 }
2020
2021 /**
2022 * Enforce that serial number stored in user directory inode matches the
2023 * given expected value. Gracefully sets the serial number if currently
2024 * undefined.
2025 *
2026 * @throws IOException when problem extracting serial number, or serial
2027 * number is mismatched.
2028 */
2029 public static void enforceSerialNumber(File file, int serialNumber) throws IOException {
2030 final int foundSerial = getSerialNumber(file);
2031 Slog.v(LOG_TAG, "Found " + file + " with serial number " + foundSerial);
2032
2033 if (foundSerial == -1) {
2034 Slog.d(LOG_TAG, "Serial number missing on " + file + "; assuming current is valid");
2035 try {
2036 setSerialNumber(file, serialNumber);
2037 } catch (IOException e) {
2038 Slog.w(LOG_TAG, "Failed to set serial number on " + file, e);
2039 }
2040
2041 } else if (foundSerial != serialNumber) {
2042 throw new IOException("Found serial number " + foundSerial
2043 + " doesn't match expected " + serialNumber);
2044 }
2045 }
2046
2047 /**
2048 * Set serial number stored in user directory inode.
2049 *
2050 * @throws IOException if serial number was already set
2051 */
2052 private static void setSerialNumber(File file, int serialNumber)
2053 throws IOException {
2054 try {
2055 final byte[] buf = Integer.toString(serialNumber).getBytes(StandardCharsets.UTF_8);
2056 Os.setxattr(file.getAbsolutePath(), XATTR_SERIAL, buf, OsConstants.XATTR_CREATE);
2057 } catch (ErrnoException e) {
2058 throw e.rethrowAsIOException();
2059 }
2060 }
2061
2062 /**
2063 * Return serial number stored in user directory inode.
2064 *
2065 * @return parsed serial number, or -1 if not set
2066 */
2067 private static int getSerialNumber(File file) throws IOException {
2068 try {
2069 final byte[] buf = new byte[256];
2070 final int len = Os.getxattr(file.getAbsolutePath(), XATTR_SERIAL, buf);
2071 final String serial = new String(buf, 0, len);
2072 try {
2073 return Integer.parseInt(serial);
2074 } catch (NumberFormatException e) {
2075 throw new IOException("Bad serial number: " + serial);
2076 }
2077 } catch (ErrnoException e) {
2078 if (e.errno == OsConstants.ENODATA) {
2079 return -1;
2080 } else {
2081 throw e.rethrowAsIOException();
2082 }
2083 }
2084 }
2085
Amith Yamasani920ace02012-09-20 22:15:37 -07002086 @Override
2087 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2088 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2089 != PackageManager.PERMISSION_GRANTED) {
2090 pw.println("Permission Denial: can't dump UserManager from from pid="
2091 + Binder.getCallingPid()
2092 + ", uid=" + Binder.getCallingUid()
2093 + " without permission "
2094 + android.Manifest.permission.DUMP);
2095 return;
2096 }
2097
2098 long now = System.currentTimeMillis();
2099 StringBuilder sb = new StringBuilder();
2100 synchronized (mPackagesLock) {
2101 pw.println("Users:");
2102 for (int i = 0; i < mUsers.size(); i++) {
2103 UserInfo user = mUsers.valueAt(i);
2104 if (user == null) continue;
Amith Yamasani634cf312012-10-04 17:34:21 -07002105 pw.print(" "); pw.print(user); pw.print(" serialNo="); pw.print(user.serialNumber);
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002106 if (mRemovingUserIds.get(mUsers.keyAt(i))) pw.print(" <removing> ");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002107 if (user.partial) pw.print(" <partial>");
2108 pw.println();
Amith Yamasani920ace02012-09-20 22:15:37 -07002109 pw.print(" Created: ");
2110 if (user.creationTime == 0) {
2111 pw.println("<unknown>");
2112 } else {
2113 sb.setLength(0);
2114 TimeUtils.formatDuration(now - user.creationTime, sb);
2115 sb.append(" ago");
2116 pw.println(sb);
2117 }
2118 pw.print(" Last logged in: ");
2119 if (user.lastLoggedInTime == 0) {
2120 pw.println("<unknown>");
2121 } else {
2122 sb.setLength(0);
2123 TimeUtils.formatDuration(now - user.lastLoggedInTime, sb);
2124 sb.append(" ago");
2125 pw.println(sb);
2126 }
2127 }
2128 }
2129 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002130
2131 final class MainHandler extends Handler {
2132
2133 @Override
2134 public void handleMessage(Message msg) {
2135 switch (msg.what) {
2136 case WRITE_USER_MSG:
2137 removeMessages(WRITE_USER_MSG, msg.obj);
2138 synchronized (mPackagesLock) {
2139 int userId = ((UserInfo) msg.obj).id;
2140 UserInfo userInfo = mUsers.get(userId);
2141 if (userInfo != null) {
2142 writeUserLocked(userInfo);
2143 }
2144 }
2145 }
2146 }
2147 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07002148
2149 /**
2150 * @param userId
2151 * @return whether the user has been initialized yet
2152 */
2153 boolean isInitialized(int userId) {
2154 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
2155 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002156}