blob: 87a8540c4b1c2673185cc084b4af85d58899e771 [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;
Amith Yamasani515d4062015-09-28 11:30:06 -070023import android.app.ActivityManagerInternal;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070024import android.app.ActivityManagerNative;
25import android.app.IStopUserCallback;
Xiaohui Chen203243a2015-07-16 11:55:47 -070026import android.app.admin.DevicePolicyManager;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070027import android.content.BroadcastReceiver;
Amith Yamasani258848d2012-08-10 17:06:33 -070028import android.content.Context;
29import android.content.Intent;
Amith Yamasani1a7472e2013-07-02 11:17:30 -070030import android.content.pm.ApplicationInfo;
Amith Yamasani0b285492011-04-14 17:35:23 -070031import android.content.pm.PackageManager;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -080032import android.content.pm.PackageManager.NameNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070033import android.content.pm.UserInfo;
Amith Yamasanie928d7d2012-09-17 21:46:51 -070034import android.graphics.Bitmap;
Amith Yamasani258848d2012-08-10 17:06:33 -070035import android.os.Binder;
Amith Yamasanie4cf7342012-12-17 11:12:09 -080036import android.os.Bundle;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070037import android.os.Environment;
38import android.os.FileUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080039import android.os.Handler;
Amith Yamasani258848d2012-08-10 17:06:33 -070040import android.os.IUserManager;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -080041import android.os.Message;
Adrian Roos1bdff912015-02-17 15:51:35 +010042import android.os.ParcelFileDescriptor;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070043import android.os.Parcelable;
Amith Yamasani258848d2012-08-10 17:06:33 -070044import android.os.Process;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070045import android.os.RemoteException;
Jason Monk62062992014-05-06 09:55:28 -040046import android.os.ServiceManager;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070047import android.os.UserHandle;
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070048import android.os.UserManager;
Paul Crowley85e4e812015-05-19 12:42:00 +010049import android.os.storage.StorageManager;
Jeff Sharkey6dce4962015-07-03 18:08:41 -070050import android.os.storage.VolumeInfo;
51import android.system.ErrnoException;
52import android.system.Os;
53import android.system.OsConstants;
Amith Yamasani2a003292012-08-14 18:25:45 -070054import android.util.AtomicFile;
Amith Yamasani655d0e22013-06-12 14:19:10 -070055import android.util.Log;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070056import android.util.Slog;
57import android.util.SparseArray;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080058import android.util.SparseBooleanArray;
Amith Yamasani920ace02012-09-20 22:15:37 -070059import android.util.TimeUtils;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070060import android.util.Xml;
61
Fyodor Kupolovb5013302015-04-17 17:59:14 -070062import com.google.android.collect.Sets;
63
Fyodor Kupolov262f9952015-03-23 18:55:11 -070064import com.android.internal.annotations.VisibleForTesting;
Jason Monk62062992014-05-06 09:55:28 -040065import com.android.internal.app.IAppOpsService;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080066import com.android.internal.util.FastXmlSerializer;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070067import com.android.internal.util.XmlUtils;
Amith Yamasani515d4062015-09-28 11:30:06 -070068import com.android.server.LocalServices;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080069
70import org.xmlpull.v1.XmlPullParser;
71import org.xmlpull.v1.XmlPullParserException;
72import org.xmlpull.v1.XmlSerializer;
73
Amith Yamasani4b2e9342011-03-31 12:38:53 -070074import java.io.BufferedOutputStream;
75import java.io.File;
Amith Yamasani920ace02012-09-20 22:15:37 -070076import java.io.FileDescriptor;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070077import java.io.FileInputStream;
Amith Yamasanib8151ec2012-04-18 18:02:48 -070078import java.io.FileNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070079import java.io.FileOutputStream;
80import java.io.IOException;
Amith Yamasani920ace02012-09-20 22:15:37 -070081import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +010082import java.nio.charset.StandardCharsets;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070083import java.util.ArrayList;
84import java.util.List;
Fyodor Kupolovb5013302015-04-17 17:59:14 -070085import java.util.Set;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070086
Fyodor Kupolov262f9952015-03-23 18:55:11 -070087import libcore.io.IoUtils;
88
Amith Yamasani258848d2012-08-10 17:06:33 -070089public class UserManagerService extends IUserManager.Stub {
Amith Yamasanib8151ec2012-04-18 18:02:48 -070090
Amith Yamasani2a003292012-08-14 18:25:45 -070091 private static final String LOG_TAG = "UserManagerService";
Amith Yamasanib8151ec2012-04-18 18:02:48 -070092
Amith Yamasani16389312012-10-17 21:20:14 -070093 private static final boolean DBG = false;
94
Amith Yamasani4b2e9342011-03-31 12:38:53 -070095 private static final String TAG_NAME = "name";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070096 private static final String ATTR_FLAGS = "flags";
Amith Yamasanib8151ec2012-04-18 18:02:48 -070097 private static final String ATTR_ICON_PATH = "icon";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070098 private static final String ATTR_ID = "id";
Amith Yamasani920ace02012-09-20 22:15:37 -070099 private static final String ATTR_CREATION_TIME = "created";
100 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
Amith Yamasani2a003292012-08-14 18:25:45 -0700101 private static final String ATTR_SERIAL_NO = "serialNumber";
102 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700103 private static final String ATTR_PARTIAL = "partial";
Adam Lesinskieddeb492014-09-08 17:50:03 -0700104 private static final String ATTR_GUEST_TO_REMOVE = "guestToRemove";
Amith Yamasani6f34b412012-10-22 18:19:27 -0700105 private static final String ATTR_USER_VERSION = "version";
Kenny Guy2a764942014-04-02 13:29:20 +0100106 private static final String ATTR_PROFILE_GROUP_ID = "profileGroupId";
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700107 private static final String ATTR_RESTRICTED_PROFILE_PARENT_ID = "restrictedProfileParentId";
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530108 private static final String TAG_GUEST_RESTRICTIONS = "guestRestrictions";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700109 private static final String TAG_USERS = "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700110 private static final String TAG_USER = "user";
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800111 private static final String TAG_RESTRICTIONS = "restrictions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800112 private static final String TAG_ENTRY = "entry";
113 private static final String TAG_VALUE = "value";
114 private static final String ATTR_KEY = "key";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700115 private static final String ATTR_VALUE_TYPE = "type";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800116 private static final String ATTR_MULTIPLE = "m";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700117
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700118 private static final String ATTR_TYPE_STRING_ARRAY = "sa";
119 private static final String ATTR_TYPE_STRING = "s";
120 private static final String ATTR_TYPE_BOOLEAN = "b";
Amith Yamasani5b5aa402014-06-01 20:10:14 -0700121 private static final String ATTR_TYPE_INTEGER = "i";
Fyodor Kupolov262f9952015-03-23 18:55:11 -0700122 private static final String ATTR_TYPE_BUNDLE = "B";
123 private static final String ATTR_TYPE_BUNDLE_ARRAY = "BA";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700124
Amith Yamasani0b285492011-04-14 17:35:23 -0700125 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700126 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700127 private static final String USER_PHOTO_FILENAME = "photo.png";
Adrian Roos1bdff912015-02-17 15:51:35 +0100128 private static final String USER_PHOTO_FILENAME_TMP = USER_PHOTO_FILENAME + ".tmp";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700129
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800130 private static final String RESTRICTIONS_FILE_PREFIX = "res_";
Amith Yamasanifc95e702013-09-26 13:20:17 -0700131 private static final String XML_SUFFIX = ".xml";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800132
Amith Yamasani634cf312012-10-04 17:34:21 -0700133 private static final int MIN_USER_ID = 10;
134
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700135 private static final int USER_VERSION = 6;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700136
Amith Yamasani920ace02012-09-20 22:15:37 -0700137 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
138
Nicolas Prevotb8186812015-08-06 15:00:03 +0100139 // Maximum number of managed profiles permitted per user is 1. This cannot be increased
Amith Yamasani95ab7842014-08-11 17:09:26 -0700140 // without first making sure that the rest of the framework is prepared for it.
141 private static final int MAX_MANAGED_PROFILES = 1;
142
Andres Moralesc5548c02015-08-05 10:23:12 -0700143 /**
144 * Flag indicating whether device credentials are shared among same-user profiles.
145 */
146 private static final boolean CONFIG_PROFILES_SHARE_CREDENTIAL = true;
147
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700148 // Set of user restrictions, which can only be enforced by the system
149 private static final Set<String> SYSTEM_CONTROLLED_RESTRICTIONS = Sets.newArraySet(
150 UserManager.DISALLOW_RECORD_AUDIO);
151
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800152 static final int WRITE_USER_MSG = 1;
153 static final int WRITE_USER_DELAY = 2*1000; // 2 seconds
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530154
Jeff Sharkey6dce4962015-07-03 18:08:41 -0700155 private static final String XATTR_SERIAL = "user.serial";
156
Dianne Hackborn4428e172012-08-24 17:43:05 -0700157 private final Context mContext;
158 private final PackageManagerService mPm;
159 private final Object mInstallLock;
160 private final Object mPackagesLock;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700161
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800162 private final Handler mHandler;
163
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700164 private final File mUsersDir;
165 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700166
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800167 private final SparseArray<UserInfo> mUsers = new SparseArray<UserInfo>();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800168 private final SparseArray<Bundle> mUserRestrictions = new SparseArray<Bundle>();
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530169 private final Bundle mGuestRestrictions = new Bundle();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800170
171 /**
172 * Set of user IDs being actively removed. Removed IDs linger in this set
173 * for several seconds to work around a VFS caching issue.
174 */
175 // @GuardedBy("mPackagesLock")
176 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700177
Amith Yamasani0b285492011-04-14 17:35:23 -0700178 private int[] mUserIds;
Amith Yamasani2a003292012-08-14 18:25:45 -0700179 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700180 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700181
Jason Monk62062992014-05-06 09:55:28 -0400182 private IAppOpsService mAppOpsService;
183
Amith Yamasani258848d2012-08-10 17:06:33 -0700184 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700185
Dianne Hackborn4428e172012-08-24 17:43:05 -0700186 public static UserManagerService getInstance() {
187 synchronized (UserManagerService.class) {
188 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700189 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700190 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700191
192 /**
193 * Available for testing purposes.
194 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700195 UserManagerService(File dataDir, File baseUserPath) {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700196 this(null, null, new Object(), new Object(), dataDir, baseUserPath);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700197 }
198
Dianne Hackborn4428e172012-08-24 17:43:05 -0700199 /**
200 * Called by package manager to create the service. This is closely
201 * associated with the package manager, and the given lock is the
202 * package manager's own lock.
203 */
204 UserManagerService(Context context, PackageManagerService pm,
205 Object installLock, Object packagesLock) {
206 this(context, pm, installLock, packagesLock,
207 Environment.getDataDirectory(),
208 new File(Environment.getDataDirectory(), "user"));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700209 }
210
Dianne Hackborn4428e172012-08-24 17:43:05 -0700211 /**
212 * Available for testing purposes.
213 */
214 private UserManagerService(Context context, PackageManagerService pm,
215 Object installLock, Object packagesLock,
216 File dataDir, File baseUserPath) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700217 mContext = context;
218 mPm = pm;
219 mInstallLock = installLock;
220 mPackagesLock = packagesLock;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800221 mHandler = new MainHandler();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700222 synchronized (mInstallLock) {
223 synchronized (mPackagesLock) {
224 mUsersDir = new File(dataDir, USER_INFO_DIR);
225 mUsersDir.mkdirs();
226 // Make zeroth user directory, for services to migrate their files to that location
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700227 File userZeroDir = new File(mUsersDir, String.valueOf(UserHandle.USER_SYSTEM));
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700228 userZeroDir.mkdirs();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700229 FileUtils.setPermissions(mUsersDir.toString(),
230 FileUtils.S_IRWXU|FileUtils.S_IRWXG
231 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
232 -1, -1);
233 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
Amith Yamasanida0b1682014-11-21 12:58:17 -0800234 initDefaultGuestRestrictions();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700235 readUserListLocked();
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700236 sInstance = this;
237 }
238 }
239 }
240
241 void systemReady() {
242 synchronized (mInstallLock) {
243 synchronized (mPackagesLock) {
Amith Yamasani756901d2012-10-12 12:30:07 -0700244 // Prune out any partially created/partially removed users.
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700245 ArrayList<UserInfo> partials = new ArrayList<UserInfo>();
Amith Yamasani515d4062015-09-28 11:30:06 -0700246 final int userSize = mUsers.size();
247 for (int i = 0; i < userSize; i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700248 UserInfo ui = mUsers.valueAt(i);
Adam Lesinskieddeb492014-09-08 17:50:03 -0700249 if ((ui.partial || ui.guestToRemove) && i != 0) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700250 partials.add(ui);
251 }
252 }
Amith Yamasani515d4062015-09-28 11:30:06 -0700253 final int partialsSize = partials.size();
254 for (int i = 0; i < partialsSize; i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700255 UserInfo ui = partials.get(i);
Amith Yamasania7892482015-08-07 11:09:05 -0700256 Slog.w(LOG_TAG, "Removing partially created user " + ui.id
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700257 + " (name=" + ui.name + ")");
258 removeUserStateLocked(ui.id);
259 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700260 }
Dianne Hackborn4428e172012-08-24 17:43:05 -0700261 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700262 onUserForeground(UserHandle.USER_SYSTEM);
Jason Monk62062992014-05-06 09:55:28 -0400263 mAppOpsService = IAppOpsService.Stub.asInterface(
264 ServiceManager.getService(Context.APP_OPS_SERVICE));
265 for (int i = 0; i < mUserIds.length; ++i) {
266 try {
267 mAppOpsService.setUserRestrictions(mUserRestrictions.get(mUserIds[i]), mUserIds[i]);
268 } catch (RemoteException e) {
269 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
270 }
271 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700272 }
273
274 @Override
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700275 public UserInfo getPrimaryUser() {
276 checkManageUsersPermission("query users");
277 synchronized (mPackagesLock) {
Amith Yamasani515d4062015-09-28 11:30:06 -0700278 final int userSize = mUsers.size();
279 for (int i = 0; i < userSize; i++) {
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700280 UserInfo ui = mUsers.valueAt(i);
281 if (ui.isPrimary()) {
282 return ui;
283 }
284 }
285 }
286 return null;
287 }
288
289 @Override
Xiaohui Chen594f2082015-08-18 11:04:20 -0700290 public @NonNull List<UserInfo> getUsers(boolean excludeDying) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700291 checkManageUsersPermission("query users");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700292 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700293 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasani515d4062015-09-28 11:30:06 -0700294 final int userSize = mUsers.size();
295 for (int i = 0; i < userSize; i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700296 UserInfo ui = mUsers.valueAt(i);
297 if (ui.partial) {
298 continue;
299 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800300 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700301 users.add(ui);
Amith Yamasani920ace02012-09-20 22:15:37 -0700302 }
Amith Yamasani13593602012-03-22 16:16:17 -0700303 }
304 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700305 }
Amith Yamasani13593602012-03-22 16:16:17 -0700306 }
307
Amith Yamasani258848d2012-08-10 17:06:33 -0700308 @Override
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100309 public List<UserInfo> getProfiles(int userId, boolean enabledOnly) {
Amith Yamasani4f582632014-02-19 14:31:52 -0800310 if (userId != UserHandle.getCallingUserId()) {
311 checkManageUsersPermission("getting profiles related to user " + userId);
312 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700313 final long ident = Binder.clearCallingIdentity();
314 try {
315 synchronized (mPackagesLock) {
316 return getProfilesLocked(userId, enabledOnly);
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100317 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700318 } finally {
319 Binder.restoreCallingIdentity(ident);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000320 }
321 }
322
Amith Yamasanibe465322014-04-24 13:45:17 -0700323 /** Assume permissions already checked and caller's identity cleared */
324 private List<UserInfo> getProfilesLocked(int userId, boolean enabledOnly) {
Amith Yamasanibe465322014-04-24 13:45:17 -0700325 UserInfo user = getUserInfoLocked(userId);
326 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasanidda003f2014-08-28 18:06:51 -0700327 if (user == null) {
328 // Probably a dying user
329 return users;
330 }
Amith Yamasani515d4062015-09-28 11:30:06 -0700331 final int userSize = mUsers.size();
332 for (int i = 0; i < userSize; i++) {
Amith Yamasanibe465322014-04-24 13:45:17 -0700333 UserInfo profile = mUsers.valueAt(i);
334 if (!isProfileOf(user, profile)) {
335 continue;
336 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100337 if (enabledOnly && !profile.isEnabled()) {
338 continue;
Amith Yamasanibe465322014-04-24 13:45:17 -0700339 }
Amith Yamasani70fcf0c2014-07-11 08:40:19 -0700340 if (mRemovingUserIds.get(profile.id)) {
341 continue;
342 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700343 users.add(profile);
344 }
345 return users;
346 }
347
Jessica Hummelbe81c802014-04-22 15:49:22 +0100348 @Override
Andres Moralesc5548c02015-08-05 10:23:12 -0700349 public int getCredentialOwnerProfile(int userHandle) {
350 checkManageUsersPermission("get the credential owner");
351 if (CONFIG_PROFILES_SHARE_CREDENTIAL) {
352 synchronized (mPackagesLock) {
353 UserInfo profileParent = getProfileParentLocked(userHandle);
354 if (profileParent != null) {
355 return profileParent.id;
356 }
357 }
358 }
359
360 return userHandle;
361 }
362
363 @Override
Jessica Hummelbe81c802014-04-22 15:49:22 +0100364 public UserInfo getProfileParent(int userHandle) {
365 checkManageUsersPermission("get the profile parent");
366 synchronized (mPackagesLock) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700367 return getProfileParentLocked(userHandle);
368 }
369 }
370
371 private UserInfo getProfileParentLocked(int userHandle) {
372 UserInfo profile = getUserInfoLocked(userHandle);
373 if (profile == null) {
374 return null;
375 }
376 int parentUserId = profile.profileGroupId;
377 if (parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
378 return null;
379 } else {
380 return getUserInfoLocked(parentUserId);
Jessica Hummelbe81c802014-04-22 15:49:22 +0100381 }
382 }
383
Kenny Guy2a764942014-04-02 13:29:20 +0100384 private boolean isProfileOf(UserInfo user, UserInfo profile) {
385 return user.id == profile.id ||
386 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
387 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000388 }
389
390 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100391 public void setUserEnabled(int userId) {
392 checkManageUsersPermission("enable user");
393 synchronized (mPackagesLock) {
394 UserInfo info = getUserInfoLocked(userId);
395 if (info != null && !info.isEnabled()) {
396 info.flags ^= UserInfo.FLAG_DISABLED;
397 writeUserLocked(info);
398 }
399 }
400 }
401
402 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700403 public UserInfo getUserInfo(int userId) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700404 checkManageUsersPermission("query user");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700405 synchronized (mPackagesLock) {
Amith Yamasani195263742012-08-21 15:40:12 -0700406 return getUserInfoLocked(userId);
Amith Yamasani13593602012-03-22 16:16:17 -0700407 }
408 }
409
Amith Yamasani71e6c692013-03-24 17:39:28 -0700410 @Override
411 public boolean isRestricted() {
412 synchronized (mPackagesLock) {
413 return getUserInfoLocked(UserHandle.getCallingUserId()).isRestricted();
414 }
415 }
416
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700417 @Override
418 public boolean canHaveRestrictedProfile(int userId) {
419 checkManageUsersPermission("canHaveRestrictedProfile");
420 synchronized (mPackagesLock) {
421 final UserInfo userInfo = getUserInfoLocked(userId);
422 if (userInfo == null || !userInfo.canHaveProfile()) {
423 return false;
424 }
425 if (!userInfo.isAdmin()) {
426 return false;
427 }
428 }
429 DevicePolicyManager dpm = (DevicePolicyManager) mContext.getSystemService(
430 Context.DEVICE_POLICY_SERVICE);
431 // restricted profile can be created if there is no DO set and the admin user has no PO
432 return dpm.getDeviceOwner() == null && dpm.getProfileOwnerAsUser(userId) == null;
433 }
434
Amith Yamasani195263742012-08-21 15:40:12 -0700435 /*
436 * Should be locked on mUsers before calling this.
437 */
438 private UserInfo getUserInfoLocked(int userId) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700439 UserInfo ui = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -0700440 // If it is partial and not in the process of being removed, return as unknown user.
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800441 if (ui != null && ui.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700442 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
443 return null;
444 }
445 return ui;
Amith Yamasani195263742012-08-21 15:40:12 -0700446 }
447
Amith Yamasani236b2b52015-08-18 14:32:14 -0700448 /** Called by PackageManagerService */
Amith Yamasani13593602012-03-22 16:16:17 -0700449 public boolean exists(int userId) {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700450 synchronized (mPackagesLock) {
Amith Yamasani236b2b52015-08-18 14:32:14 -0700451 return mUsers.get(userId) != null;
Amith Yamasani13593602012-03-22 16:16:17 -0700452 }
453 }
454
Amith Yamasani258848d2012-08-10 17:06:33 -0700455 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700456 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700457 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700458 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700459 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700460 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700461 if (info == null || info.partial) {
462 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
463 return;
464 }
Amith Yamasani13593602012-03-22 16:16:17 -0700465 if (name != null && !name.equals(info.name)) {
466 info.name = name;
467 writeUserLocked(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700468 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -0700469 }
470 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700471 if (changed) {
472 sendUserInfoChangedBroadcast(userId);
473 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700474 }
475
Amith Yamasani258848d2012-08-10 17:06:33 -0700476 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700477 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700478 checkManageUsersPermission("update users");
Jason Monk9a944532014-07-08 09:31:21 -0400479 long ident = Binder.clearCallingIdentity();
480 try {
481 synchronized (mPackagesLock) {
482 UserInfo info = mUsers.get(userId);
483 if (info == null || info.partial) {
484 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
485 return;
486 }
487 writeBitmapLocked(info, bitmap);
488 writeUserLocked(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700489 }
Jason Monk9a944532014-07-08 09:31:21 -0400490 sendUserInfoChangedBroadcast(userId);
491 } finally {
492 Binder.restoreCallingIdentity(ident);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700493 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700494 }
495
496 private void sendUserInfoChangedBroadcast(int userId) {
497 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
498 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
499 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -0700500 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700501 }
502
Amith Yamasani258848d2012-08-10 17:06:33 -0700503 @Override
Adrian Roos1bdff912015-02-17 15:51:35 +0100504 public ParcelFileDescriptor getUserIcon(int userId) {
505 String iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700506 synchronized (mPackagesLock) {
507 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700508 if (info == null || info.partial) {
509 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + userId);
510 return null;
511 }
Nicolas Prevot88cc3462014-05-14 14:51:48 +0100512 int callingGroupId = mUsers.get(UserHandle.getCallingUserId()).profileGroupId;
513 if (callingGroupId == UserInfo.NO_PROFILE_GROUP_ID
514 || callingGroupId != info.profileGroupId) {
515 checkManageUsersPermission("get the icon of a user who is not related");
516 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700517 if (info.iconPath == null) {
518 return null;
519 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100520 iconPath = info.iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700521 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100522
523 try {
524 return ParcelFileDescriptor.open(
525 new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
526 } catch (FileNotFoundException e) {
527 Log.e(LOG_TAG, "Couldn't find icon file", e);
528 }
529 return null;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700530 }
531
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700532 public void makeInitialized(int userId) {
533 checkManageUsersPermission("makeInitialized");
534 synchronized (mPackagesLock) {
535 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700536 if (info == null || info.partial) {
537 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
538 }
539 if ((info.flags&UserInfo.FLAG_INITIALIZED) == 0) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700540 info.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800541 scheduleWriteUserLocked(info);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700542 }
543 }
544 }
545
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700546 /**
547 * If default guest restrictions haven't been initialized yet, add the basic
548 * restrictions.
549 */
550 private void initDefaultGuestRestrictions() {
551 if (mGuestRestrictions.isEmpty()) {
552 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
Amith Yamasanida0b1682014-11-21 12:58:17 -0800553 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700554 }
555 }
556
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800557 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530558 public Bundle getDefaultGuestRestrictions() {
559 checkManageUsersPermission("getDefaultGuestRestrictions");
560 synchronized (mPackagesLock) {
561 return new Bundle(mGuestRestrictions);
562 }
563 }
564
565 @Override
566 public void setDefaultGuestRestrictions(Bundle restrictions) {
567 checkManageUsersPermission("setDefaultGuestRestrictions");
568 synchronized (mPackagesLock) {
569 mGuestRestrictions.clear();
570 mGuestRestrictions.putAll(restrictions);
571 writeUserListLocked();
572 }
573 }
574
575 @Override
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700576 public boolean hasUserRestriction(String restrictionKey, int userId) {
577 synchronized (mPackagesLock) {
578 Bundle restrictions = mUserRestrictions.get(userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700579 return restrictions != null && restrictions.getBoolean(restrictionKey);
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700580 }
581 }
582
583 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800584 public Bundle getUserRestrictions(int userId) {
585 // checkManageUsersPermission("getUserRestrictions");
586
587 synchronized (mPackagesLock) {
588 Bundle restrictions = mUserRestrictions.get(userId);
Amith Yamasanibe465322014-04-24 13:45:17 -0700589 return restrictions != null ? new Bundle(restrictions) : new Bundle();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800590 }
591 }
592
593 @Override
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700594 public void setUserRestriction(String key, boolean value, int userId) {
Fyodor Kupolovd4b26042015-07-27 14:30:59 -0700595 checkManageUsersPermission("setUserRestriction");
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700596 synchronized (mPackagesLock) {
597 if (!SYSTEM_CONTROLLED_RESTRICTIONS.contains(key)) {
598 Bundle restrictions = getUserRestrictions(userId);
599 restrictions.putBoolean(key, value);
600 setUserRestrictionsInternalLocked(restrictions, userId);
601 }
602 }
603 }
604
605 @Override
606 public void setSystemControlledUserRestriction(String key, boolean value, int userId) {
607 checkSystemOrRoot("setSystemControlledUserRestriction");
608 synchronized (mPackagesLock) {
609 Bundle restrictions = getUserRestrictions(userId);
610 restrictions.putBoolean(key, value);
611 setUserRestrictionsInternalLocked(restrictions, userId);
612 }
613 }
614
615 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800616 public void setUserRestrictions(Bundle restrictions, int userId) {
Amith Yamasanibe465322014-04-24 13:45:17 -0700617 checkManageUsersPermission("setUserRestrictions");
Amith Yamasani0343ec32013-07-22 14:52:06 -0700618 if (restrictions == null) return;
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800619
620 synchronized (mPackagesLock) {
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700621 final Bundle oldUserRestrictions = mUserRestrictions.get(userId);
622 // Restore the original state of system controlled restrictions from oldUserRestrictions
623 for (String key : SYSTEM_CONTROLLED_RESTRICTIONS) {
624 restrictions.remove(key);
625 if (oldUserRestrictions.containsKey(key)) {
626 restrictions.putBoolean(key, oldUserRestrictions.getBoolean(key));
627 }
Jason Monk62062992014-05-06 09:55:28 -0400628 }
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700629 setUserRestrictionsInternalLocked(restrictions, userId);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800630 }
631 }
632
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700633 private void setUserRestrictionsInternalLocked(Bundle restrictions, int userId) {
634 final Bundle userRestrictions = mUserRestrictions.get(userId);
635 userRestrictions.clear();
636 userRestrictions.putAll(restrictions);
637 long token = Binder.clearCallingIdentity();
638 try {
639 mAppOpsService.setUserRestrictions(userRestrictions, userId);
640 } catch (RemoteException e) {
641 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
642 } finally {
643 Binder.restoreCallingIdentity(token);
644 }
645 scheduleWriteUserLocked(mUsers.get(userId));
646 }
647
Amith Yamasani258848d2012-08-10 17:06:33 -0700648 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700649 * Check if we've hit the limit of how many users can be created.
650 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700651 private boolean isUserLimitReachedLocked() {
Nicolas Prevot12678a92015-05-13 12:15:03 -0700652 return getAliveUsersExcludingGuestsCountLocked() >= UserManager.getMaxSupportedUsers();
653 }
654
655 @Override
Nicolas Prevotb8186812015-08-06 15:00:03 +0100656 public boolean canAddMoreManagedProfiles(int userId) {
Nicolas Prevot12678a92015-05-13 12:15:03 -0700657 checkManageUsersPermission("check if more managed profiles can be added.");
658 if (ActivityManager.isLowRamDeviceStatic()) {
659 return false;
660 }
Fyodor Kupolovb6157992015-06-05 15:32:28 -0700661 if (!mContext.getPackageManager().hasSystemFeature(
662 PackageManager.FEATURE_MANAGED_USERS)) {
663 return false;
664 }
Nicolas Prevotb8186812015-08-06 15:00:03 +0100665 // Limit number of managed profiles that can be created
666 int managedProfilesCount = getProfiles(userId, true).size() - 1;
667 if (managedProfilesCount >= MAX_MANAGED_PROFILES) {
668 return false;
669 }
Nicolas Prevot12678a92015-05-13 12:15:03 -0700670 synchronized(mPackagesLock) {
Nicolas Prevotb8186812015-08-06 15:00:03 +0100671 UserInfo userInfo = getUserInfoLocked(userId);
672 if (!userInfo.canHaveProfile()) {
Nicolas Prevot12678a92015-05-13 12:15:03 -0700673 return false;
674 }
675 int usersCount = getAliveUsersExcludingGuestsCountLocked();
676 // We allow creating a managed profile in the special case where there is only one user.
677 return usersCount == 1 || usersCount < UserManager.getMaxSupportedUsers();
678 }
679 }
680
681 private int getAliveUsersExcludingGuestsCountLocked() {
Amith Yamasanif584f012014-05-19 17:57:25 -0700682 int aliveUserCount = 0;
683 final int totalUserCount = mUsers.size();
684 // Skip over users being removed
685 for (int i = 0; i < totalUserCount; i++) {
686 UserInfo user = mUsers.valueAt(i);
Amith Yamasani95ab7842014-08-11 17:09:26 -0700687 if (!mRemovingUserIds.get(user.id)
Amith Yamasani1df14732014-08-29 21:37:27 -0700688 && !user.isGuest() && !user.partial) {
Amith Yamasanif584f012014-05-19 17:57:25 -0700689 aliveUserCount++;
690 }
691 }
Nicolas Prevot12678a92015-05-13 12:15:03 -0700692 return aliveUserCount;
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700693 }
694
695 /**
Amith Yamasani195263742012-08-21 15:40:12 -0700696 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -0700697 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -0700698 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -0700699 *
700 * @param message used as message if SecurityException is thrown
701 * @throws SecurityException if the caller is not system or root
702 */
Amith Yamasanibe465322014-04-24 13:45:17 -0700703 private static final void checkManageUsersPermission(String message) {
Amith Yamasani258848d2012-08-10 17:06:33 -0700704 final int uid = Binder.getCallingUid();
Amith Yamasanibe465322014-04-24 13:45:17 -0700705 if (uid != Process.SYSTEM_UID && uid != 0
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400706 && ActivityManager.checkComponentPermission(
707 android.Manifest.permission.MANAGE_USERS,
Amith Yamasanibe465322014-04-24 13:45:17 -0700708 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
709 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
710 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400711 }
712
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700713 private static void checkSystemOrRoot(String message) {
714 final int uid = Binder.getCallingUid();
715 if (uid != Process.SYSTEM_UID && uid != 0) {
716 throw new SecurityException("Only system may call: " + message);
717 }
718 }
719
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700720 private void writeBitmapLocked(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700721 try {
722 File dir = new File(mUsersDir, Integer.toString(info.id));
723 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +0100724 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700725 if (!dir.exists()) {
726 dir.mkdir();
727 FileUtils.setPermissions(
728 dir.getPath(),
729 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
730 -1, -1);
731 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700732 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +0100733 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
734 && tmp.renameTo(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -0700735 info.iconPath = file.getAbsolutePath();
736 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700737 try {
738 os.close();
739 } catch (IOException ioe) {
740 // What the ... !
741 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100742 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700743 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700744 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700745 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700746 }
747
Amith Yamasani0b285492011-04-14 17:35:23 -0700748 /**
749 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
750 * cache it elsewhere.
751 * @return the array of user ids.
752 */
Dianne Hackborn1676c852012-09-10 14:52:30 -0700753 public int[] getUserIds() {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700754 synchronized (mPackagesLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700755 return mUserIds;
756 }
Amith Yamasani0b285492011-04-14 17:35:23 -0700757 }
758
Dianne Hackborn4428e172012-08-24 17:43:05 -0700759 int[] getUserIdsLPr() {
760 return mUserIds;
761 }
762
Amith Yamasani13593602012-03-22 16:16:17 -0700763 private void readUserListLocked() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700764 if (!mUserListFile.exists()) {
Amith Yamasani13593602012-03-22 16:16:17 -0700765 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700766 return;
767 }
768 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700769 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700770 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700771 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700772 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100773 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700774 int type;
775 while ((type = parser.next()) != XmlPullParser.START_TAG
776 && type != XmlPullParser.END_DOCUMENT) {
777 ;
778 }
779
780 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700781 Slog.e(LOG_TAG, "Unable to read user list");
Amith Yamasani13593602012-03-22 16:16:17 -0700782 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700783 return;
784 }
785
Amith Yamasani2a003292012-08-14 18:25:45 -0700786 mNextSerialNumber = -1;
787 if (parser.getName().equals(TAG_USERS)) {
788 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
789 if (lastSerialNumber != null) {
790 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
791 }
Amith Yamasani6f34b412012-10-22 18:19:27 -0700792 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
793 if (versionNumber != null) {
794 mUserVersion = Integer.parseInt(versionNumber);
795 }
Amith Yamasani2a003292012-08-14 18:25:45 -0700796 }
797
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700798 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530799 if (type == XmlPullParser.START_TAG) {
800 final String name = parser.getName();
801 if (name.equals(TAG_USER)) {
802 String id = parser.getAttributeValue(null, ATTR_ID);
803 UserInfo user = readUserLocked(Integer.parseInt(id));
Amith Yamasani6f34b412012-10-22 18:19:27 -0700804
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530805 if (user != null) {
806 mUsers.put(user.id, user);
807 if (mNextSerialNumber < 0 || mNextSerialNumber <= user.id) {
808 mNextSerialNumber = user.id + 1;
809 }
Amith Yamasani2a003292012-08-14 18:25:45 -0700810 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530811 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -0800812 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
813 && type != XmlPullParser.END_TAG) {
814 if (type == XmlPullParser.START_TAG) {
815 if (parser.getName().equals(TAG_RESTRICTIONS)) {
816 readRestrictionsLocked(parser, mGuestRestrictions);
817 }
818 break;
819 }
820 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700821 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700822 }
823 }
Amith Yamasani13593602012-03-22 16:16:17 -0700824 updateUserIdsLocked();
Amith Yamasani350962c2013-08-06 11:18:53 -0700825 upgradeIfNecessaryLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700826 } catch (IOException ioe) {
Amith Yamasani13593602012-03-22 16:16:17 -0700827 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700828 } catch (XmlPullParserException pe) {
Amith Yamasani13593602012-03-22 16:16:17 -0700829 fallbackToSingleUserLocked();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -0800830 } finally {
831 if (fis != null) {
832 try {
833 fis.close();
834 } catch (IOException e) {
835 }
836 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700837 }
838 }
839
Amith Yamasani6f34b412012-10-22 18:19:27 -0700840 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -0800841 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -0700842 */
Amith Yamasani350962c2013-08-06 11:18:53 -0700843 private void upgradeIfNecessaryLocked() {
Amith Yamasani6f34b412012-10-22 18:19:27 -0700844 int userVersion = mUserVersion;
845 if (userVersion < 1) {
846 // Assign a proper name for the owner, if not initialized correctly before
847 UserInfo user = mUsers.get(UserHandle.USER_OWNER);
848 if ("Primary".equals(user.name)) {
849 user.name = mContext.getResources().getString(com.android.internal.R.string.owner_name);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800850 scheduleWriteUserLocked(user);
Amith Yamasani6f34b412012-10-22 18:19:27 -0700851 }
852 userVersion = 1;
853 }
854
Amith Yamasanibc9625052012-11-15 14:39:18 -0800855 if (userVersion < 2) {
856 // Owner should be marked as initialized
857 UserInfo user = mUsers.get(UserHandle.USER_OWNER);
858 if ((user.flags & UserInfo.FLAG_INITIALIZED) == 0) {
859 user.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800860 scheduleWriteUserLocked(user);
Amith Yamasanibc9625052012-11-15 14:39:18 -0800861 }
862 userVersion = 2;
863 }
864
Amith Yamasani350962c2013-08-06 11:18:53 -0700865
Amith Yamasani5e486f52013-08-07 11:06:44 -0700866 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -0700867 userVersion = 4;
868 }
869
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700870 if (userVersion < 5) {
871 initDefaultGuestRestrictions();
872 userVersion = 5;
873 }
874
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700875 if (userVersion < 6) {
876 final boolean splitSystemUser = UserManager.isSplitSystemUser();
877 for (int i = 0; i < mUsers.size(); i++) {
878 UserInfo user = mUsers.valueAt(i);
879 // In non-split mode, only user 0 can have restricted profiles
880 if (!splitSystemUser && user.isRestricted()
881 && (user.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID)) {
882 user.restrictedProfileParentId = UserHandle.USER_SYSTEM;
883 scheduleWriteUserLocked(user);
884 }
885 }
886 userVersion = 6;
887 }
888
Amith Yamasani6f34b412012-10-22 18:19:27 -0700889 if (userVersion < USER_VERSION) {
890 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
891 + USER_VERSION);
892 } else {
893 mUserVersion = userVersion;
894 writeUserListLocked();
895 }
896 }
897
Amith Yamasani13593602012-03-22 16:16:17 -0700898 private void fallbackToSingleUserLocked() {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -0700899 int flags = UserInfo.FLAG_INITIALIZED;
900 // In split system user mode, the admin and primary flags are assigned to the first human
901 // user.
902 if (!UserManager.isSplitSystemUser()) {
903 flags |= UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY;
904 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700905 // Create the system user
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700906 UserInfo system = new UserInfo(UserHandle.USER_SYSTEM,
Amith Yamasani6f34b412012-10-22 18:19:27 -0700907 mContext.getResources().getString(com.android.internal.R.string.owner_name), null,
Xiaohui Chenb31e14a2015-07-13 16:04:55 -0700908 flags);
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700909 mUsers.put(system.id, system);
Amith Yamasani634cf312012-10-04 17:34:21 -0700910 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -0400911 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -0800912
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -0500913 Bundle restrictions = new Bundle();
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700914 mUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions);
Amith Yamasani67df64b2012-12-14 12:09:36 -0800915
Amith Yamasani13593602012-03-22 16:16:17 -0700916 updateUserIdsLocked();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700917 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700918
Amith Yamasani13593602012-03-22 16:16:17 -0700919 writeUserListLocked();
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700920 writeUserLocked(system);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700921 }
922
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800923 private void scheduleWriteUserLocked(UserInfo userInfo) {
924 if (!mHandler.hasMessages(WRITE_USER_MSG, userInfo)) {
925 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, userInfo);
926 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
927 }
928 }
929
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700930 /*
931 * Writes the user file in this format:
932 *
933 * <user flags="20039023" id="0">
934 * <name>Primary</name>
935 * </user>
936 */
Amith Yamasani13593602012-03-22 16:16:17 -0700937 private void writeUserLocked(UserInfo userInfo) {
Amith Yamasani742a6712011-05-04 14:49:28 -0700938 FileOutputStream fos = null;
Amith Yamasanifc95e702013-09-26 13:20:17 -0700939 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userInfo.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700940 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700941 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700942 final BufferedOutputStream bos = new BufferedOutputStream(fos);
943
944 // XmlSerializer serializer = XmlUtils.serializerInstance();
945 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100946 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700947 serializer.startDocument(null, true);
948 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
949
950 serializer.startTag(null, TAG_USER);
951 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
Amith Yamasani2a003292012-08-14 18:25:45 -0700952 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700953 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Amith Yamasani920ace02012-09-20 22:15:37 -0700954 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
955 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
956 Long.toString(userInfo.lastLoggedInTime));
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700957 if (userInfo.iconPath != null) {
958 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
959 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700960 if (userInfo.partial) {
961 serializer.attribute(null, ATTR_PARTIAL, "true");
962 }
Adam Lesinskieddeb492014-09-08 17:50:03 -0700963 if (userInfo.guestToRemove) {
964 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
965 }
Kenny Guy2a764942014-04-02 13:29:20 +0100966 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
967 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
968 Integer.toString(userInfo.profileGroupId));
Kenny Guya52dc3e2014-02-11 15:33:14 +0000969 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700970 if (userInfo.restrictedProfileParentId != UserInfo.NO_PROFILE_GROUP_ID) {
971 serializer.attribute(null, ATTR_RESTRICTED_PROFILE_PARENT_ID,
972 Integer.toString(userInfo.restrictedProfileParentId));
973 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700974 serializer.startTag(null, TAG_NAME);
975 serializer.text(userInfo.name);
976 serializer.endTag(null, TAG_NAME);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800977 Bundle restrictions = mUserRestrictions.get(userInfo.id);
978 if (restrictions != null) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530979 writeRestrictionsLocked(serializer, restrictions);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800980 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700981 serializer.endTag(null, TAG_USER);
982
983 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -0700984 userFile.finishWrite(fos);
985 } catch (Exception ioe) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700986 Slog.e(LOG_TAG, "Error writing user info " + userInfo.id + "\n" + ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -0700987 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700988 }
989 }
990
991 /*
992 * Writes the user list file in this format:
993 *
Amith Yamasani2a003292012-08-14 18:25:45 -0700994 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700995 * <user id="0"></user>
996 * <user id="2"></user>
997 * </users>
998 */
Amith Yamasani13593602012-03-22 16:16:17 -0700999 private void writeUserListLocked() {
Amith Yamasani742a6712011-05-04 14:49:28 -07001000 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001001 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001002 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001003 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001004 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1005
1006 // XmlSerializer serializer = XmlUtils.serializerInstance();
1007 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001008 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001009 serializer.startDocument(null, true);
1010 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1011
1012 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -07001013 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -07001014 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001015
Adam Lesinskieddeb492014-09-08 17:50:03 -07001016 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301017 writeRestrictionsLocked(serializer, mGuestRestrictions);
1018 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Amith Yamasani515d4062015-09-28 11:30:06 -07001019 final int userSize = mUsers.size();
1020 for (int i = 0; i < userSize; i++) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001021 UserInfo user = mUsers.valueAt(i);
1022 serializer.startTag(null, TAG_USER);
1023 serializer.attribute(null, ATTR_ID, Integer.toString(user.id));
1024 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001025 }
1026
1027 serializer.endTag(null, TAG_USERS);
1028
1029 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001030 userListFile.finishWrite(fos);
1031 } catch (Exception e) {
1032 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -07001033 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001034 }
1035 }
1036
Andres Moralesc5548c02015-08-05 10:23:12 -07001037 private void writeRestrictionsLocked(XmlSerializer serializer, Bundle restrictions)
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301038 throws IOException {
1039 serializer.startTag(null, TAG_RESTRICTIONS);
1040 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_WIFI);
1041 writeBoolean(serializer, restrictions, UserManager.DISALLOW_MODIFY_ACCOUNTS);
1042 writeBoolean(serializer, restrictions, UserManager.DISALLOW_INSTALL_APPS);
1043 writeBoolean(serializer, restrictions, UserManager.DISALLOW_UNINSTALL_APPS);
1044 writeBoolean(serializer, restrictions, UserManager.DISALLOW_SHARE_LOCATION);
1045 writeBoolean(serializer, restrictions,
1046 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
1047 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_BLUETOOTH);
1048 writeBoolean(serializer, restrictions, UserManager.DISALLOW_USB_FILE_TRANSFER);
1049 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_CREDENTIALS);
1050 writeBoolean(serializer, restrictions, UserManager.DISALLOW_REMOVE_USER);
1051 writeBoolean(serializer, restrictions, UserManager.DISALLOW_DEBUGGING_FEATURES);
1052 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_VPN);
1053 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_TETHERING);
Stuart Scott94b038b2015-04-20 14:07:45 -07001054 writeBoolean(serializer, restrictions, UserManager.DISALLOW_NETWORK_RESET);
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301055 writeBoolean(serializer, restrictions, UserManager.DISALLOW_FACTORY_RESET);
1056 writeBoolean(serializer, restrictions, UserManager.DISALLOW_ADD_USER);
1057 writeBoolean(serializer, restrictions, UserManager.ENSURE_VERIFY_APPS);
1058 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_CELL_BROADCASTS);
1059 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS);
1060 writeBoolean(serializer, restrictions, UserManager.DISALLOW_APPS_CONTROL);
1061 writeBoolean(serializer, restrictions, UserManager.DISALLOW_MOUNT_PHYSICAL_MEDIA);
1062 writeBoolean(serializer, restrictions, UserManager.DISALLOW_UNMUTE_MICROPHONE);
1063 writeBoolean(serializer, restrictions, UserManager.DISALLOW_ADJUST_VOLUME);
Amith Yamasani390989d2014-07-17 10:52:03 -07001064 writeBoolean(serializer, restrictions, UserManager.DISALLOW_OUTGOING_CALLS);
1065 writeBoolean(serializer, restrictions, UserManager.DISALLOW_SMS);
Jeff Sharkey2cc03e52015-03-20 11:24:04 -07001066 writeBoolean(serializer, restrictions, UserManager.DISALLOW_FUN);
Jason Monk1c7c3192014-06-26 12:52:18 -04001067 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CREATE_WINDOWS);
Amith Yamasani26af8292014-09-09 09:57:27 -07001068 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CROSS_PROFILE_COPY_PASTE);
1069 writeBoolean(serializer, restrictions, UserManager.DISALLOW_OUTGOING_BEAM);
Benjamin Franzf3ece362015-02-11 10:51:10 +00001070 writeBoolean(serializer, restrictions, UserManager.DISALLOW_WALLPAPER);
Benjamin Franzbff46ba2015-03-05 18:33:51 +00001071 writeBoolean(serializer, restrictions, UserManager.DISALLOW_SAFE_BOOT);
Nicolas Prevotf0029c12015-06-25 14:25:41 -07001072 writeBoolean(serializer, restrictions, UserManager.ALLOW_PARENT_PROFILE_APP_LINKING);
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301073 serializer.endTag(null, TAG_RESTRICTIONS);
1074 }
1075
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001076 private UserInfo readUserLocked(int id) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001077 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -07001078 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001079 String name = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001080 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -07001081 long creationTime = 0L;
1082 long lastLoggedInTime = 0L;
Kenny Guy2a764942014-04-02 13:29:20 +01001083 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001084 int restrictedProfileParentId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001085 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001086 boolean guestToRemove = false;
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001087 Bundle restrictions = new Bundle();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001088
1089 FileInputStream fis = null;
1090 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001091 AtomicFile userFile =
Amith Yamasanifc95e702013-09-26 13:20:17 -07001092 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
Amith Yamasani2a003292012-08-14 18:25:45 -07001093 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001094 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001095 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001096 int type;
1097 while ((type = parser.next()) != XmlPullParser.START_TAG
1098 && type != XmlPullParser.END_DOCUMENT) {
1099 ;
1100 }
1101
1102 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001103 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001104 return null;
1105 }
1106
1107 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001108 int storedId = readIntAttribute(parser, ATTR_ID, -1);
1109 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001110 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001111 return null;
1112 }
Amith Yamasani920ace02012-09-20 22:15:37 -07001113 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
1114 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001115 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -07001116 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
1117 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Kenny Guy2a764942014-04-02 13:29:20 +01001118 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
1119 UserInfo.NO_PROFILE_GROUP_ID);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001120 restrictedProfileParentId = readIntAttribute(parser,
1121 ATTR_RESTRICTED_PROFILE_PARENT_ID, UserInfo.NO_PROFILE_GROUP_ID);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001122 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
1123 if ("true".equals(valueString)) {
1124 partial = true;
1125 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001126 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
1127 if ("true".equals(valueString)) {
1128 guestToRemove = true;
1129 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001130
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001131 int outerDepth = parser.getDepth();
1132 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1133 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1134 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1135 continue;
1136 }
1137 String tag = parser.getName();
1138 if (TAG_NAME.equals(tag)) {
1139 type = parser.next();
1140 if (type == XmlPullParser.TEXT) {
1141 name = parser.getText();
1142 }
1143 } else if (TAG_RESTRICTIONS.equals(tag)) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301144 readRestrictionsLocked(parser, restrictions);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001145 }
1146 }
1147 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001148
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001149 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -07001150 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -07001151 userInfo.creationTime = creationTime;
1152 userInfo.lastLoggedInTime = lastLoggedInTime;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001153 userInfo.partial = partial;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001154 userInfo.guestToRemove = guestToRemove;
Kenny Guy2a764942014-04-02 13:29:20 +01001155 userInfo.profileGroupId = profileGroupId;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001156 userInfo.restrictedProfileParentId = restrictedProfileParentId;
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001157 mUserRestrictions.append(id, restrictions);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001158 return userInfo;
1159
1160 } catch (IOException ioe) {
1161 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001162 } finally {
1163 if (fis != null) {
1164 try {
1165 fis.close();
1166 } catch (IOException e) {
1167 }
1168 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001169 }
1170 return null;
1171 }
1172
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301173 private void readRestrictionsLocked(XmlPullParser parser, Bundle restrictions)
1174 throws IOException {
1175 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_WIFI);
1176 readBoolean(parser, restrictions, UserManager.DISALLOW_MODIFY_ACCOUNTS);
1177 readBoolean(parser, restrictions, UserManager.DISALLOW_INSTALL_APPS);
1178 readBoolean(parser, restrictions, UserManager.DISALLOW_UNINSTALL_APPS);
1179 readBoolean(parser, restrictions, UserManager.DISALLOW_SHARE_LOCATION);
1180 readBoolean(parser, restrictions,
1181 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
1182 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_BLUETOOTH);
1183 readBoolean(parser, restrictions, UserManager.DISALLOW_USB_FILE_TRANSFER);
1184 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_CREDENTIALS);
1185 readBoolean(parser, restrictions, UserManager.DISALLOW_REMOVE_USER);
1186 readBoolean(parser, restrictions, UserManager.DISALLOW_DEBUGGING_FEATURES);
1187 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_VPN);
1188 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_TETHERING);
Stuart Scott94b038b2015-04-20 14:07:45 -07001189 readBoolean(parser, restrictions, UserManager.DISALLOW_NETWORK_RESET);
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301190 readBoolean(parser, restrictions, UserManager.DISALLOW_FACTORY_RESET);
1191 readBoolean(parser, restrictions, UserManager.DISALLOW_ADD_USER);
1192 readBoolean(parser, restrictions, UserManager.ENSURE_VERIFY_APPS);
1193 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_CELL_BROADCASTS);
1194 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS);
1195 readBoolean(parser, restrictions, UserManager.DISALLOW_APPS_CONTROL);
1196 readBoolean(parser, restrictions,
1197 UserManager.DISALLOW_MOUNT_PHYSICAL_MEDIA);
1198 readBoolean(parser, restrictions, UserManager.DISALLOW_UNMUTE_MICROPHONE);
1199 readBoolean(parser, restrictions, UserManager.DISALLOW_ADJUST_VOLUME);
Amith Yamasani390989d2014-07-17 10:52:03 -07001200 readBoolean(parser, restrictions, UserManager.DISALLOW_OUTGOING_CALLS);
1201 readBoolean(parser, restrictions, UserManager.DISALLOW_SMS);
Jeff Sharkey2cc03e52015-03-20 11:24:04 -07001202 readBoolean(parser, restrictions, UserManager.DISALLOW_FUN);
Jason Monk1c7c3192014-06-26 12:52:18 -04001203 readBoolean(parser, restrictions, UserManager.DISALLOW_CREATE_WINDOWS);
Amith Yamasani26af8292014-09-09 09:57:27 -07001204 readBoolean(parser, restrictions, UserManager.DISALLOW_CROSS_PROFILE_COPY_PASTE);
1205 readBoolean(parser, restrictions, UserManager.DISALLOW_OUTGOING_BEAM);
Benjamin Franzf3ece362015-02-11 10:51:10 +00001206 readBoolean(parser, restrictions, UserManager.DISALLOW_WALLPAPER);
Benjamin Franzbff46ba2015-03-05 18:33:51 +00001207 readBoolean(parser, restrictions, UserManager.DISALLOW_SAFE_BOOT);
Nicolas Prevotf0029c12015-06-25 14:25:41 -07001208 readBoolean(parser, restrictions, UserManager.ALLOW_PARENT_PROFILE_APP_LINKING);
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301209 }
1210
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001211 private void readBoolean(XmlPullParser parser, Bundle restrictions,
1212 String restrictionKey) {
1213 String value = parser.getAttributeValue(null, restrictionKey);
Amith Yamasani71e6c692013-03-24 17:39:28 -07001214 if (value != null) {
1215 restrictions.putBoolean(restrictionKey, Boolean.parseBoolean(value));
1216 }
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001217 }
1218
1219 private void writeBoolean(XmlSerializer xml, Bundle restrictions, String restrictionKey)
1220 throws IOException {
1221 if (restrictions.containsKey(restrictionKey)) {
1222 xml.attribute(null, restrictionKey,
1223 Boolean.toString(restrictions.getBoolean(restrictionKey)));
1224 }
1225 }
1226
Amith Yamasani920ace02012-09-20 22:15:37 -07001227 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
1228 String valueString = parser.getAttributeValue(null, attr);
1229 if (valueString == null) return defaultValue;
1230 try {
1231 return Integer.parseInt(valueString);
1232 } catch (NumberFormatException nfe) {
1233 return defaultValue;
1234 }
1235 }
1236
1237 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
1238 String valueString = parser.getAttributeValue(null, attr);
1239 if (valueString == null) return defaultValue;
1240 try {
1241 return Long.parseLong(valueString);
1242 } catch (NumberFormatException nfe) {
1243 return defaultValue;
1244 }
1245 }
1246
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001247 private boolean isPackageInstalled(String pkg, int userId) {
1248 final ApplicationInfo info = mPm.getApplicationInfo(pkg,
1249 PackageManager.GET_UNINSTALLED_PACKAGES,
1250 userId);
1251 if (info == null || (info.flags&ApplicationInfo.FLAG_INSTALLED) == 0) {
1252 return false;
1253 }
1254 return true;
1255 }
1256
Amith Yamasanib82add22013-07-09 11:24:44 -07001257 /**
Kenny Guyd21b2182014-07-17 16:38:55 +01001258 * Removes all the restrictions files (res_<packagename>) for a given user.
Amith Yamasanib82add22013-07-09 11:24:44 -07001259 * Does not do any permissions checking.
1260 */
Kenny Guyd21b2182014-07-17 16:38:55 +01001261 private void cleanAppRestrictions(int userId) {
Amith Yamasanib82add22013-07-09 11:24:44 -07001262 synchronized (mPackagesLock) {
1263 File dir = Environment.getUserSystemDirectory(userId);
1264 String[] files = dir.list();
1265 if (files == null) return;
1266 for (String fileName : files) {
1267 if (fileName.startsWith(RESTRICTIONS_FILE_PREFIX)) {
1268 File resFile = new File(dir, fileName);
1269 if (resFile.exists()) {
Kenny Guyd21b2182014-07-17 16:38:55 +01001270 resFile.delete();
Amith Yamasanib82add22013-07-09 11:24:44 -07001271 }
1272 }
1273 }
1274 }
1275 }
1276
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001277 /**
1278 * Removes the app restrictions file for a specific package and user id, if it exists.
1279 */
1280 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
1281 synchronized (mPackagesLock) {
1282 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07001283 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001284 if (resFile.exists()) {
1285 resFile.delete();
1286 }
1287 }
1288 }
1289
Kenny Guya52dc3e2014-02-11 15:33:14 +00001290 @Override
Kenny Guy2a764942014-04-02 13:29:20 +01001291 public UserInfo createProfileForUser(String name, int flags, int userId) {
Kenny Guya52dc3e2014-02-11 15:33:14 +00001292 checkManageUsersPermission("Only the system can create users");
Kenny Guy2a764942014-04-02 13:29:20 +01001293 return createUserInternal(name, flags, userId);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001294 }
1295
Amith Yamasani258848d2012-08-10 17:06:33 -07001296 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07001297 public UserInfo createUser(String name, int flags) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001298 checkManageUsersPermission("Only the system can create users");
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001299 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001300 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001301
Jessica Hummelbe81c802014-04-22 15:49:22 +01001302 private UserInfo createUserInternal(String name, int flags, int parentId) {
Julia Reynolds75175022014-06-26 16:35:00 -04001303 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1304 UserManager.DISALLOW_ADD_USER, false)) {
1305 Log.w(LOG_TAG, "Cannot add user. DISALLOW_ADD_USER is enabled.");
1306 return null;
1307 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001308 if (ActivityManager.isLowRamDeviceStatic()) {
1309 return null;
1310 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07001311 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001312 final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001313 final boolean isRestricted = (flags & UserInfo.FLAG_RESTRICTED) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001314 final long ident = Binder.clearCallingIdentity();
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001315 UserInfo userInfo = null;
Amith Yamasanibb054c92015-07-09 14:16:27 -07001316 final int userId;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001317 try {
1318 synchronized (mInstallLock) {
1319 synchronized (mPackagesLock) {
Jessica Hummelbe81c802014-04-22 15:49:22 +01001320 UserInfo parent = null;
1321 if (parentId != UserHandle.USER_NULL) {
1322 parent = getUserInfoLocked(parentId);
1323 if (parent == null) return null;
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001324 }
Nicolas Prevotb8186812015-08-06 15:00:03 +01001325 if (isManagedProfile && !canAddMoreManagedProfiles(parentId)) {
1326 Log.e(LOG_TAG, "Cannot add more managed profiles for user " + parentId);
Nicolas Prevot12678a92015-05-13 12:15:03 -07001327 return null;
1328 }
1329 if (!isGuest && !isManagedProfile && isUserLimitReachedLocked()) {
1330 // If we're not adding a guest user or a managed profile and the limit has
1331 // been reached, cannot add a user.
Amith Yamasani95ab7842014-08-11 17:09:26 -07001332 return null;
1333 }
1334 // If we're adding a guest and there already exists one, bail.
Adam Lesinskieddeb492014-09-08 17:50:03 -07001335 if (isGuest && findCurrentGuestUserLocked() != null) {
Amith Yamasani95ab7842014-08-11 17:09:26 -07001336 return null;
1337 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001338 // In legacy mode, restricted profile's parent can only be the owner user
1339 if (isRestricted && !UserManager.isSplitSystemUser()
1340 && (parentId != UserHandle.USER_SYSTEM)) {
1341 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
1342 return null;
1343 }
1344 if (isRestricted && UserManager.isSplitSystemUser()) {
1345 if (parent == null) {
1346 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be "
1347 + "specified");
1348 return null;
1349 }
1350 if (!parent.canHaveProfile()) {
1351 Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be "
1352 + "created for the specified parent user id " + parentId);
1353 return null;
1354 }
1355 }
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001356 // In split system user mode, we assign the first human user the primary flag.
Xiaohui Chen203243a2015-07-16 11:55:47 -07001357 // And if there is no device owner, we also assign the admin flag to primary
1358 // user.
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001359 if (UserManager.isSplitSystemUser()
Xiaohui Chen203243a2015-07-16 11:55:47 -07001360 && !isGuest && !isManagedProfile && getPrimaryUser() == null) {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001361 flags |= UserInfo.FLAG_PRIMARY;
Xiaohui Chen203243a2015-07-16 11:55:47 -07001362 DevicePolicyManager devicePolicyManager = (DevicePolicyManager)
1363 mContext.getSystemService(Context.DEVICE_POLICY_SERVICE);
1364 if (devicePolicyManager == null
1365 || devicePolicyManager.getDeviceOwner() == null) {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001366 flags |= UserInfo.FLAG_ADMIN;
1367 }
1368 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07001369 userId = getNextAvailableIdLocked();
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001370 userInfo = new UserInfo(userId, name, null, flags);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001371 userInfo.serialNumber = mNextSerialNumber++;
Amith Yamasani920ace02012-09-20 22:15:37 -07001372 long now = System.currentTimeMillis();
1373 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001374 userInfo.partial = true;
Amith Yamasani16389312012-10-17 21:20:14 -07001375 Environment.getUserSystemDirectory(userInfo.id).mkdirs();
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001376 mUsers.put(userId, userInfo);
1377 writeUserListLocked();
Jessica Hummelbe81c802014-04-22 15:49:22 +01001378 if (parent != null) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001379 if (isManagedProfile) {
1380 if (parent.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
1381 parent.profileGroupId = parent.id;
1382 scheduleWriteUserLocked(parent);
1383 }
1384 userInfo.profileGroupId = parent.profileGroupId;
1385 } else if (isRestricted) {
1386 if (!parent.canHaveProfile()) {
1387 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
1388 }
1389 if (parent.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) {
1390 parent.restrictedProfileParentId = parent.id;
1391 scheduleWriteUserLocked(parent);
1392 }
1393 userInfo.restrictedProfileParentId = parent.restrictedProfileParentId;
Kenny Guya52dc3e2014-02-11 15:33:14 +00001394 }
Kenny Guya52dc3e2014-02-11 15:33:14 +00001395 }
Jeff Sharkey6dce4962015-07-03 18:08:41 -07001396 final StorageManager storage = mContext.getSystemService(StorageManager.class);
1397 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
1398 final String volumeUuid = vol.getFsUuid();
1399 try {
1400 final File userDir = Environment.getDataUserDirectory(volumeUuid,
1401 userId);
Jeff Sharkey3bb8c852015-07-06 16:44:23 -07001402 prepareUserDirectory(mContext, volumeUuid, userId);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07001403 enforceSerialNumber(userDir, userInfo.serialNumber);
1404 } catch (IOException e) {
1405 Log.wtf(LOG_TAG, "Failed to create user directory on " + volumeUuid, e);
1406 }
1407 }
1408 mPm.createNewUserLILPw(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001409 userInfo.partial = false;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001410 scheduleWriteUserLocked(userInfo);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001411 updateUserIdsLocked();
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001412 Bundle restrictions = new Bundle();
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001413 mUserRestrictions.append(userId, restrictions);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001414 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07001415 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07001416 mPm.newUserCreated(userId);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001417 if (userInfo != null) {
1418 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
1419 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userInfo.id);
1420 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
1421 android.Manifest.permission.MANAGE_USERS);
1422 }
1423 } finally {
1424 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07001425 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001426 return userInfo;
1427 }
1428
Amith Yamasani0b285492011-04-14 17:35:23 -07001429 /**
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07001430 * @hide
1431 */
1432 public UserInfo createRestrictedProfile(String name, int parentUserId) {
1433 checkManageUsersPermission("setupRestrictedProfile");
1434 final UserInfo user = createProfileForUser(name, UserInfo.FLAG_RESTRICTED, parentUserId);
1435 if (user == null) {
1436 return null;
1437 }
1438 setUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, true, user.id);
1439 // Change the setting before applying the DISALLOW_SHARE_LOCATION restriction, otherwise
1440 // the putIntForUser() will fail.
1441 android.provider.Settings.Secure.putIntForUser(mContext.getContentResolver(),
1442 android.provider.Settings.Secure.LOCATION_MODE,
1443 android.provider.Settings.Secure.LOCATION_MODE_OFF, user.id);
1444 setUserRestriction(UserManager.DISALLOW_SHARE_LOCATION, true, user.id);
1445 return user;
1446 }
1447
1448 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07001449 * Find the current guest user. If the Guest user is partial,
1450 * then do not include it in the results as it is about to die.
Adam Lesinskieddeb492014-09-08 17:50:03 -07001451 */
1452 private UserInfo findCurrentGuestUserLocked() {
1453 final int size = mUsers.size();
1454 for (int i = 0; i < size; i++) {
1455 final UserInfo user = mUsers.valueAt(i);
1456 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
1457 return user;
1458 }
1459 }
1460 return null;
1461 }
1462
1463 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07001464 * Mark this guest user for deletion to allow us to create another guest
1465 * and switch to that user before actually removing this guest.
1466 * @param userHandle the userid of the current guest
1467 * @return whether the user could be marked for deletion
1468 */
1469 public boolean markGuestForDeletion(int userHandle) {
1470 checkManageUsersPermission("Only the system can remove users");
1471 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1472 UserManager.DISALLOW_REMOVE_USER, false)) {
1473 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1474 return false;
1475 }
1476
1477 long ident = Binder.clearCallingIdentity();
1478 try {
1479 final UserInfo user;
1480 synchronized (mPackagesLock) {
1481 user = mUsers.get(userHandle);
1482 if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
1483 return false;
1484 }
1485 if (!user.isGuest()) {
1486 return false;
1487 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001488 // We set this to a guest user that is to be removed. This is a temporary state
1489 // where we are allowed to add new Guest users, even if this one is still not
1490 // removed. This user will still show up in getUserInfo() calls.
1491 // If we don't get around to removing this Guest user, it will be purged on next
1492 // startup.
1493 user.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07001494 // Mark it as disabled, so that it isn't returned any more when
1495 // profiles are queried.
1496 user.flags |= UserInfo.FLAG_DISABLED;
Amith Yamasani1df14732014-08-29 21:37:27 -07001497 writeUserLocked(user);
1498 }
1499 } finally {
1500 Binder.restoreCallingIdentity(ident);
1501 }
1502 return true;
1503 }
1504
1505 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07001506 * Removes a user and all data directories created for that user. This method should be called
1507 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001508 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07001509 */
Amith Yamasani258848d2012-08-10 17:06:33 -07001510 public boolean removeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001511 checkManageUsersPermission("Only the system can remove users");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04001512 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1513 UserManager.DISALLOW_REMOVE_USER, false)) {
1514 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1515 return false;
1516 }
1517
Kenny Guyee58b4f2014-05-23 15:19:53 +01001518 long ident = Binder.clearCallingIdentity();
1519 try {
1520 final UserInfo user;
Fyodor Kupolov0df68cd2015-10-01 13:54:22 -07001521 int currentUser = ActivityManager.getCurrentUser();
1522 if (currentUser == userHandle) {
1523 Log.w(LOG_TAG, "Current user cannot be removed");
1524 return false;
1525 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01001526 synchronized (mPackagesLock) {
1527 user = mUsers.get(userHandle);
Kenny Guy17c9d692014-06-13 13:51:42 +01001528 if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01001529 return false;
1530 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08001531
1532 // We remember deleted user IDs to prevent them from being
1533 // reused during the current boot; they can still be reused
1534 // after a reboot.
Kenny Guyee58b4f2014-05-23 15:19:53 +01001535 mRemovingUserIds.put(userHandle, true);
Jeff Sharkey6eb09392014-11-14 15:57:59 -08001536
Kenny Guyee58b4f2014-05-23 15:19:53 +01001537 try {
1538 mAppOpsService.removeUser(userHandle);
1539 } catch (RemoteException e) {
1540 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
1541 }
1542 // Set this to a partially created user, so that the user will be purged
1543 // on next startup, in case the runtime stops now before stopping and
1544 // removing the user completely.
1545 user.partial = true;
1546 // Mark it as disabled, so that it isn't returned any more when
1547 // profiles are queried.
1548 user.flags |= UserInfo.FLAG_DISABLED;
1549 writeUserLocked(user);
1550 }
1551
1552 if (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
1553 && user.isManagedProfile()) {
1554 // Send broadcast to notify system that the user removed was a
1555 // managed user.
1556 sendProfileRemovedBroadcast(user.profileGroupId, user.id);
1557 }
1558
1559 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
1560 int res;
1561 try {
1562 res = ActivityManagerNative.getDefault().stopUser(userHandle,
1563 new IStopUserCallback.Stub() {
1564 @Override
1565 public void userStopped(int userId) {
1566 finishRemoveUser(userId);
1567 }
1568 @Override
1569 public void userStopAborted(int userId) {
1570 }
1571 });
1572 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001573 return false;
1574 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01001575 return res == ActivityManager.USER_OP_SUCCESS;
1576 } finally {
1577 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001578 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001579 }
1580
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001581 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07001582 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001583 // Let other services shutdown any activity and clean up their state before completely
1584 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001585 long ident = Binder.clearCallingIdentity();
1586 try {
1587 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
1588 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001589 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
1590 android.Manifest.permission.MANAGE_USERS,
1591
1592 new BroadcastReceiver() {
1593 @Override
1594 public void onReceive(Context context, Intent intent) {
1595 if (DBG) {
1596 Slog.i(LOG_TAG,
1597 "USER_REMOVED broadcast sent, cleaning up user data "
1598 + userHandle);
1599 }
1600 new Thread() {
1601 public void run() {
Amith Yamasani515d4062015-09-28 11:30:06 -07001602 // Clean up any ActivityManager state
1603 LocalServices.getService(ActivityManagerInternal.class)
1604 .onUserRemoved(userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001605 synchronized (mInstallLock) {
1606 synchronized (mPackagesLock) {
1607 removeUserStateLocked(userHandle);
1608 }
1609 }
1610 }
1611 }.start();
1612 }
1613 },
1614
1615 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001616 } finally {
1617 Binder.restoreCallingIdentity(ident);
1618 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001619 }
1620
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001621 private void removeUserStateLocked(final int userHandle) {
Paul Crowley85e4e812015-05-19 12:42:00 +01001622 mContext.getSystemService(StorageManager.class)
1623 .deleteUserKey(userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001624 // Cleanup package manager settings
Amith Yamasanidda003f2014-08-28 18:06:51 -07001625 mPm.cleanUpUserLILPw(this, userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001626
1627 // Remove this user from the list
1628 mUsers.remove(userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001629 // Remove user file
Amith Yamasanifc95e702013-09-26 13:20:17 -07001630 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001631 userFile.delete();
1632 // Update the user list
1633 writeUserListLocked();
1634 updateUserIdsLocked();
1635 removeDirectoryRecursive(Environment.getUserSystemDirectory(userHandle));
1636 }
1637
Amith Yamasani61f57372012-08-31 12:12:28 -07001638 private void removeDirectoryRecursive(File parent) {
1639 if (parent.isDirectory()) {
1640 String[] files = parent.list();
1641 for (String filename : files) {
1642 File child = new File(parent, filename);
1643 removeDirectoryRecursive(child);
1644 }
1645 }
1646 parent.delete();
1647 }
1648
Kenny Guyf8d3a232014-05-15 16:09:52 +01001649 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01001650 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01001651 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
1652 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01001653 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
1654 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01001655 }
1656
Amith Yamasani2a003292012-08-14 18:25:45 -07001657 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001658 public Bundle getApplicationRestrictions(String packageName) {
1659 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
1660 }
1661
1662 @Override
1663 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001664 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07001665 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001666 checkManageUsersPermission("Only system can get restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001667 }
1668 synchronized (mPackagesLock) {
1669 // Read the restrictions from XML
1670 return readApplicationRestrictionsLocked(packageName, userId);
1671 }
1672 }
1673
1674 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001675 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001676 int userId) {
1677 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07001678 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001679 checkManageUsersPermission("Only system can set restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001680 }
1681 synchronized (mPackagesLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01001682 if (restrictions == null || restrictions.isEmpty()) {
1683 cleanAppRestrictionsForPackage(packageName, userId);
1684 } else {
1685 // Write the restrictions to XML
1686 writeApplicationRestrictionsLocked(packageName, restrictions, userId);
1687 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001688 }
Robin Lee66e5d962014-04-09 16:44:21 +01001689
Kenny Guyd21b2182014-07-17 16:38:55 +01001690 if (isPackageInstalled(packageName, userId)) {
1691 // Notify package of changes via an intent - only sent to explicitly registered receivers.
1692 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
1693 changeIntent.setPackage(packageName);
1694 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
1695 mContext.sendBroadcastAsUser(changeIntent, new UserHandle(userId));
1696 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001697 }
1698
Amith Yamasani655d0e22013-06-12 14:19:10 -07001699 @Override
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001700 public void removeRestrictions() {
Amith Yamasanibe465322014-04-24 13:45:17 -07001701 checkManageUsersPermission("Only system can remove restrictions");
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001702 final int userHandle = UserHandle.getCallingUserId();
Amith Yamasani5e486f52013-08-07 11:06:44 -07001703 removeRestrictionsForUser(userHandle, true);
Amith Yamasani350962c2013-08-06 11:18:53 -07001704 }
1705
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001706 private void removeRestrictionsForUser(final int userHandle, boolean unhideApps) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001707 synchronized (mPackagesLock) {
1708 // Remove all user restrictions
1709 setUserRestrictions(new Bundle(), userHandle);
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001710 // Remove any app restrictions
Kenny Guyd21b2182014-07-17 16:38:55 +01001711 cleanAppRestrictions(userHandle);
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001712 }
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001713 if (unhideApps) {
1714 unhideAllInstalledAppsForUser(userHandle);
Amith Yamasani5e486f52013-08-07 11:06:44 -07001715 }
1716 }
1717
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001718 private void unhideAllInstalledAppsForUser(final int userHandle) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001719 mHandler.post(new Runnable() {
1720 @Override
1721 public void run() {
1722 List<ApplicationInfo> apps =
1723 mPm.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES,
1724 userHandle).getList();
1725 final long ident = Binder.clearCallingIdentity();
1726 try {
1727 for (ApplicationInfo appInfo : apps) {
1728 if ((appInfo.flags & ApplicationInfo.FLAG_INSTALLED) != 0
Alex Klyubinb9f8a522015-02-03 11:12:59 -08001729 && (appInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HIDDEN)
1730 != 0) {
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001731 mPm.setApplicationHiddenSettingAsUser(appInfo.packageName, false,
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001732 userHandle);
1733 }
1734 }
1735 } finally {
1736 Binder.restoreCallingIdentity(ident);
1737 }
1738 }
1739 });
1740 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001741 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07001742 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001743 try {
1744 return mContext.getPackageManager().getApplicationInfo(packageName,
1745 PackageManager.GET_UNINSTALLED_PACKAGES).uid;
1746 } catch (NameNotFoundException nnfe) {
1747 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07001748 } finally {
1749 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001750 }
1751 }
1752
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001753 private Bundle readApplicationRestrictionsLocked(String packageName,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001754 int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001755 AtomicFile restrictionsFile =
1756 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
1757 packageToRestrictionsFileName(packageName)));
1758 return readApplicationRestrictionsLocked(restrictionsFile);
1759 }
1760
1761 @VisibleForTesting
1762 static Bundle readApplicationRestrictionsLocked(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001763 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001764 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07001765 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07001766 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07001767 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001768
1769 FileInputStream fis = null;
1770 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001771 fis = restrictionsFile.openRead();
1772 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001773 parser.setInput(fis, StandardCharsets.UTF_8.name());
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001774 XmlUtils.nextElement(parser);
1775 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001776 Slog.e(LOG_TAG, "Unable to read restrictions file "
1777 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001778 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001779 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001780 while (parser.next() != XmlPullParser.END_DOCUMENT) {
1781 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001782 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001783 } catch (IOException|XmlPullParserException e) {
1784 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001785 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001786 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001787 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001788 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001789 }
1790
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001791 private static void readEntry(Bundle restrictions, ArrayList<String> values,
1792 XmlPullParser parser) throws XmlPullParserException, IOException {
1793 int type = parser.getEventType();
1794 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
1795 String key = parser.getAttributeValue(null, ATTR_KEY);
1796 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
1797 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
1798 if (multiple != null) {
1799 values.clear();
1800 int count = Integer.parseInt(multiple);
1801 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1802 if (type == XmlPullParser.START_TAG
1803 && parser.getName().equals(TAG_VALUE)) {
1804 values.add(parser.nextText().trim());
1805 count--;
1806 }
1807 }
1808 String [] valueStrings = new String[values.size()];
1809 values.toArray(valueStrings);
1810 restrictions.putStringArray(key, valueStrings);
1811 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
1812 restrictions.putBundle(key, readBundleEntry(parser, values));
1813 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
1814 final int outerDepth = parser.getDepth();
1815 ArrayList<Bundle> bundleList = new ArrayList<>();
1816 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
1817 Bundle childBundle = readBundleEntry(parser, values);
1818 bundleList.add(childBundle);
1819 }
1820 restrictions.putParcelableArray(key,
1821 bundleList.toArray(new Bundle[bundleList.size()]));
1822 } else {
1823 String value = parser.nextText().trim();
1824 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
1825 restrictions.putBoolean(key, Boolean.parseBoolean(value));
1826 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
1827 restrictions.putInt(key, Integer.parseInt(value));
1828 } else {
1829 restrictions.putString(key, value);
1830 }
1831 }
1832 }
1833 }
1834
1835 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
1836 throws IOException, XmlPullParserException {
1837 Bundle childBundle = new Bundle();
1838 final int outerDepth = parser.getDepth();
1839 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
1840 readEntry(childBundle, values, parser);
1841 }
1842 return childBundle;
1843 }
1844
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001845 private void writeApplicationRestrictionsLocked(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001846 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001847 AtomicFile restrictionsFile = new AtomicFile(
1848 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07001849 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001850 writeApplicationRestrictionsLocked(restrictions, restrictionsFile);
1851 }
1852
1853 @VisibleForTesting
1854 static void writeApplicationRestrictionsLocked(Bundle restrictions,
1855 AtomicFile restrictionsFile) {
1856 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001857 try {
1858 fos = restrictionsFile.startWrite();
1859 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1860
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001861 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001862 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001863 serializer.startDocument(null, true);
1864 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1865
1866 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001867 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001868 serializer.endTag(null, TAG_RESTRICTIONS);
1869
1870 serializer.endDocument();
1871 restrictionsFile.finishWrite(fos);
1872 } catch (Exception e) {
1873 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001874 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
1875 }
1876 }
1877
1878 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
1879 throws IOException {
1880 for (String key : restrictions.keySet()) {
1881 Object value = restrictions.get(key);
1882 serializer.startTag(null, TAG_ENTRY);
1883 serializer.attribute(null, ATTR_KEY, key);
1884
1885 if (value instanceof Boolean) {
1886 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
1887 serializer.text(value.toString());
1888 } else if (value instanceof Integer) {
1889 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
1890 serializer.text(value.toString());
1891 } else if (value == null || value instanceof String) {
1892 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
1893 serializer.text(value != null ? (String) value : "");
1894 } else if (value instanceof Bundle) {
1895 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
1896 writeBundle((Bundle) value, serializer);
1897 } else if (value instanceof Parcelable[]) {
1898 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
1899 Parcelable[] array = (Parcelable[]) value;
1900 for (Parcelable parcelable : array) {
1901 if (!(parcelable instanceof Bundle)) {
1902 throw new IllegalArgumentException("bundle-array can only hold Bundles");
1903 }
1904 serializer.startTag(null, TAG_ENTRY);
1905 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
1906 writeBundle((Bundle) parcelable, serializer);
1907 serializer.endTag(null, TAG_ENTRY);
1908 }
1909 } else {
1910 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
1911 String[] values = (String[]) value;
1912 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
1913 for (String choice : values) {
1914 serializer.startTag(null, TAG_VALUE);
1915 serializer.text(choice != null ? choice : "");
1916 serializer.endTag(null, TAG_VALUE);
1917 }
1918 }
1919 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001920 }
1921 }
1922
1923 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07001924 public int getUserSerialNumber(int userHandle) {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001925 synchronized (mPackagesLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001926 if (!exists(userHandle)) return -1;
Amith Yamasani195263742012-08-21 15:40:12 -07001927 return getUserInfoLocked(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07001928 }
1929 }
1930
1931 @Override
1932 public int getUserHandle(int userSerialNumber) {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001933 synchronized (mPackagesLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001934 for (int userId : mUserIds) {
Kenny Guy945f8832015-02-10 15:17:26 +00001935 UserInfo info = getUserInfoLocked(userId);
1936 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07001937 }
1938 // Not found
1939 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07001940 }
1941 }
1942
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07001943 @Override
1944 public long getUserCreationTime(int userHandle) {
1945 int callingUserId = UserHandle.getCallingUserId();
1946 UserInfo userInfo = null;
1947 synchronized (mPackagesLock) {
1948 if (callingUserId == userHandle) {
1949 userInfo = getUserInfoLocked(userHandle);
1950 } else {
1951 UserInfo parent = getProfileParentLocked(userHandle);
1952 if (parent != null && parent.id == callingUserId) {
1953 userInfo = getUserInfoLocked(userHandle);
1954 }
1955 }
1956 }
1957 if (userInfo == null) {
1958 throw new SecurityException("userHandle can only be the calling user or a managed "
1959 + "profile associated with this user");
1960 }
1961 return userInfo.creationTime;
1962 }
1963
Amith Yamasani0b285492011-04-14 17:35:23 -07001964 /**
1965 * Caches the list of user ids in an array, adjusting the array size when necessary.
1966 */
Amith Yamasani13593602012-03-22 16:16:17 -07001967 private void updateUserIdsLocked() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001968 int num = 0;
Amith Yamasani515d4062015-09-28 11:30:06 -07001969 final int userSize = mUsers.size();
1970 for (int i = 0; i < userSize; i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001971 if (!mUsers.valueAt(i).partial) {
1972 num++;
1973 }
1974 }
Amith Yamasani16389312012-10-17 21:20:14 -07001975 final int[] newUsers = new int[num];
1976 int n = 0;
Amith Yamasani515d4062015-09-28 11:30:06 -07001977 for (int i = 0; i < userSize; i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001978 if (!mUsers.valueAt(i).partial) {
Amith Yamasani16389312012-10-17 21:20:14 -07001979 newUsers[n++] = mUsers.keyAt(i);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001980 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001981 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001982 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07001983 }
1984
1985 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001986 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasani920ace02012-09-20 22:15:37 -07001987 * @param userId the user that was just foregrounded
1988 */
Amith Yamasani06bf8242015-05-08 16:36:21 -07001989 public void onUserForeground(int userId) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001990 synchronized (mPackagesLock) {
1991 UserInfo user = mUsers.get(userId);
1992 long now = System.currentTimeMillis();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001993 if (user == null || user.partial) {
1994 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
1995 return;
1996 }
1997 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001998 user.lastLoggedInTime = now;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001999 scheduleWriteUserLocked(user);
Amith Yamasani920ace02012-09-20 22:15:37 -07002000 }
2001 }
2002 }
2003
2004 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002005 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani742a6712011-05-04 14:49:28 -07002006 * TODO: May not be a good idea to recycle ids, in case it results in confusion
2007 * for data and battery stats collection, or unexpected cross-talk.
Amith Yamasani0b285492011-04-14 17:35:23 -07002008 * @return
2009 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002010 private int getNextAvailableIdLocked() {
Dianne Hackborn4428e172012-08-24 17:43:05 -07002011 synchronized (mPackagesLock) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002012 int i = MIN_USER_ID;
Amith Yamasani195263742012-08-21 15:40:12 -07002013 while (i < Integer.MAX_VALUE) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002014 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
Amith Yamasani195263742012-08-21 15:40:12 -07002015 break;
2016 }
2017 i++;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002018 }
Amith Yamasani195263742012-08-21 15:40:12 -07002019 return i;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002020 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002021 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002022
Amith Yamasanifc95e702013-09-26 13:20:17 -07002023 private String packageToRestrictionsFileName(String packageName) {
2024 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
2025 }
2026
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002027 /**
2028 * Create new {@code /data/user/[id]} directory and sets default
2029 * permissions.
2030 */
Jeff Sharkey3bb8c852015-07-06 16:44:23 -07002031 public static void prepareUserDirectory(Context context, String volumeUuid, int userId) {
2032 final StorageManager storage = context.getSystemService(StorageManager.class);
2033 final File userDir = Environment.getDataUserDirectory(volumeUuid, userId);
2034 storage.createNewUserDir(userId, userDir);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002035 }
2036
2037 /**
2038 * Enforce that serial number stored in user directory inode matches the
2039 * given expected value. Gracefully sets the serial number if currently
2040 * undefined.
2041 *
2042 * @throws IOException when problem extracting serial number, or serial
2043 * number is mismatched.
2044 */
2045 public static void enforceSerialNumber(File file, int serialNumber) throws IOException {
2046 final int foundSerial = getSerialNumber(file);
2047 Slog.v(LOG_TAG, "Found " + file + " with serial number " + foundSerial);
2048
2049 if (foundSerial == -1) {
2050 Slog.d(LOG_TAG, "Serial number missing on " + file + "; assuming current is valid");
2051 try {
2052 setSerialNumber(file, serialNumber);
2053 } catch (IOException e) {
2054 Slog.w(LOG_TAG, "Failed to set serial number on " + file, e);
2055 }
2056
2057 } else if (foundSerial != serialNumber) {
2058 throw new IOException("Found serial number " + foundSerial
2059 + " doesn't match expected " + serialNumber);
2060 }
2061 }
2062
2063 /**
2064 * Set serial number stored in user directory inode.
2065 *
2066 * @throws IOException if serial number was already set
2067 */
2068 private static void setSerialNumber(File file, int serialNumber)
2069 throws IOException {
2070 try {
2071 final byte[] buf = Integer.toString(serialNumber).getBytes(StandardCharsets.UTF_8);
2072 Os.setxattr(file.getAbsolutePath(), XATTR_SERIAL, buf, OsConstants.XATTR_CREATE);
2073 } catch (ErrnoException e) {
2074 throw e.rethrowAsIOException();
2075 }
2076 }
2077
2078 /**
2079 * Return serial number stored in user directory inode.
2080 *
2081 * @return parsed serial number, or -1 if not set
2082 */
2083 private static int getSerialNumber(File file) throws IOException {
2084 try {
2085 final byte[] buf = new byte[256];
2086 final int len = Os.getxattr(file.getAbsolutePath(), XATTR_SERIAL, buf);
2087 final String serial = new String(buf, 0, len);
2088 try {
2089 return Integer.parseInt(serial);
2090 } catch (NumberFormatException e) {
2091 throw new IOException("Bad serial number: " + serial);
2092 }
2093 } catch (ErrnoException e) {
2094 if (e.errno == OsConstants.ENODATA) {
2095 return -1;
2096 } else {
2097 throw e.rethrowAsIOException();
2098 }
2099 }
2100 }
2101
Amith Yamasani920ace02012-09-20 22:15:37 -07002102 @Override
2103 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2104 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2105 != PackageManager.PERMISSION_GRANTED) {
2106 pw.println("Permission Denial: can't dump UserManager from from pid="
2107 + Binder.getCallingPid()
2108 + ", uid=" + Binder.getCallingUid()
2109 + " without permission "
2110 + android.Manifest.permission.DUMP);
2111 return;
2112 }
2113
2114 long now = System.currentTimeMillis();
2115 StringBuilder sb = new StringBuilder();
2116 synchronized (mPackagesLock) {
2117 pw.println("Users:");
2118 for (int i = 0; i < mUsers.size(); i++) {
2119 UserInfo user = mUsers.valueAt(i);
2120 if (user == null) continue;
Amith Yamasani634cf312012-10-04 17:34:21 -07002121 pw.print(" "); pw.print(user); pw.print(" serialNo="); pw.print(user.serialNumber);
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002122 if (mRemovingUserIds.get(mUsers.keyAt(i))) pw.print(" <removing> ");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002123 if (user.partial) pw.print(" <partial>");
2124 pw.println();
Amith Yamasani920ace02012-09-20 22:15:37 -07002125 pw.print(" Created: ");
2126 if (user.creationTime == 0) {
2127 pw.println("<unknown>");
2128 } else {
2129 sb.setLength(0);
2130 TimeUtils.formatDuration(now - user.creationTime, sb);
2131 sb.append(" ago");
2132 pw.println(sb);
2133 }
2134 pw.print(" Last logged in: ");
2135 if (user.lastLoggedInTime == 0) {
2136 pw.println("<unknown>");
2137 } else {
2138 sb.setLength(0);
2139 TimeUtils.formatDuration(now - user.lastLoggedInTime, sb);
2140 sb.append(" ago");
2141 pw.println(sb);
2142 }
2143 }
2144 }
2145 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002146
2147 final class MainHandler extends Handler {
2148
2149 @Override
2150 public void handleMessage(Message msg) {
2151 switch (msg.what) {
2152 case WRITE_USER_MSG:
2153 removeMessages(WRITE_USER_MSG, msg.obj);
2154 synchronized (mPackagesLock) {
2155 int userId = ((UserInfo) msg.obj).id;
2156 UserInfo userInfo = mUsers.get(userId);
2157 if (userInfo != null) {
2158 writeUserLocked(userInfo);
2159 }
2160 }
2161 }
2162 }
2163 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07002164
2165 /**
2166 * @param userId
2167 * @return whether the user has been initialized yet
2168 */
2169 boolean isInitialized(int userId) {
2170 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
2171 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002172}