blob: 84fc3836d4c730109b8011313b770bf1499d14a3 [file] [log] [blame]
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -070019import android.accounts.Account;
Xiaohui Chen594f2082015-08-18 11:04:20 -070020import android.annotation.NonNull;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070021import android.app.Activity;
Amith Yamasani2a003292012-08-14 18:25:45 -070022import android.app.ActivityManager;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070023import android.app.ActivityManagerNative;
24import android.app.IStopUserCallback;
Xiaohui Chen203243a2015-07-16 11:55:47 -070025import android.app.admin.DevicePolicyManager;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070026import android.content.BroadcastReceiver;
Amith Yamasani258848d2012-08-10 17:06:33 -070027import android.content.Context;
28import android.content.Intent;
Amith Yamasani1a7472e2013-07-02 11:17:30 -070029import android.content.pm.ApplicationInfo;
Amith Yamasani0b285492011-04-14 17:35:23 -070030import android.content.pm.PackageManager;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -080031import android.content.pm.PackageManager.NameNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070032import android.content.pm.UserInfo;
Amith Yamasanie928d7d2012-09-17 21:46:51 -070033import android.graphics.Bitmap;
Amith Yamasani258848d2012-08-10 17:06:33 -070034import android.os.Binder;
Amith Yamasanie4cf7342012-12-17 11:12:09 -080035import android.os.Bundle;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070036import android.os.Environment;
37import android.os.FileUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080038import android.os.Handler;
Amith Yamasani258848d2012-08-10 17:06:33 -070039import android.os.IUserManager;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -080040import android.os.Message;
Adrian Roos1bdff912015-02-17 15:51:35 +010041import android.os.ParcelFileDescriptor;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070042import android.os.Parcelable;
Amith Yamasani258848d2012-08-10 17:06:33 -070043import android.os.Process;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070044import android.os.RemoteException;
Jason Monk62062992014-05-06 09:55:28 -040045import android.os.ServiceManager;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070046import android.os.UserHandle;
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070047import android.os.UserManager;
Paul Crowley85e4e812015-05-19 12:42:00 +010048import android.os.storage.StorageManager;
Jeff Sharkey6dce4962015-07-03 18:08:41 -070049import android.os.storage.VolumeInfo;
50import android.system.ErrnoException;
51import android.system.Os;
52import android.system.OsConstants;
Amith Yamasani2a003292012-08-14 18:25:45 -070053import android.util.AtomicFile;
Amith Yamasani655d0e22013-06-12 14:19:10 -070054import android.util.Log;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070055import android.util.Slog;
56import android.util.SparseArray;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080057import android.util.SparseBooleanArray;
Amith Yamasani920ace02012-09-20 22:15:37 -070058import android.util.TimeUtils;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070059import android.util.Xml;
60
Fyodor Kupolovb5013302015-04-17 17:59:14 -070061import com.google.android.collect.Sets;
62
Fyodor Kupolov262f9952015-03-23 18:55:11 -070063import com.android.internal.annotations.VisibleForTesting;
Jason Monk62062992014-05-06 09:55:28 -040064import com.android.internal.app.IAppOpsService;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080065import com.android.internal.util.FastXmlSerializer;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070066import com.android.internal.util.XmlUtils;
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -070067import com.android.server.accounts.AccountManagerService;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080068
69import org.xmlpull.v1.XmlPullParser;
70import org.xmlpull.v1.XmlPullParserException;
71import org.xmlpull.v1.XmlSerializer;
72
Amith Yamasani4b2e9342011-03-31 12:38:53 -070073import java.io.BufferedOutputStream;
74import java.io.File;
Amith Yamasani920ace02012-09-20 22:15:37 -070075import java.io.FileDescriptor;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070076import java.io.FileInputStream;
Amith Yamasanib8151ec2012-04-18 18:02:48 -070077import java.io.FileNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070078import java.io.FileOutputStream;
79import java.io.IOException;
Amith Yamasani920ace02012-09-20 22:15:37 -070080import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +010081import java.nio.charset.StandardCharsets;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070082import java.util.ArrayList;
83import java.util.List;
Fyodor Kupolovb5013302015-04-17 17:59:14 -070084import java.util.Set;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070085
Fyodor Kupolov262f9952015-03-23 18:55:11 -070086import libcore.io.IoUtils;
87
Amith Yamasani258848d2012-08-10 17:06:33 -070088public class UserManagerService extends IUserManager.Stub {
Amith Yamasanib8151ec2012-04-18 18:02:48 -070089
Amith Yamasani2a003292012-08-14 18:25:45 -070090 private static final String LOG_TAG = "UserManagerService";
Amith Yamasanib8151ec2012-04-18 18:02:48 -070091
Amith Yamasani16389312012-10-17 21:20:14 -070092 private static final boolean DBG = false;
93
Amith Yamasani4b2e9342011-03-31 12:38:53 -070094 private static final String TAG_NAME = "name";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070095 private static final String ATTR_FLAGS = "flags";
Amith Yamasanib8151ec2012-04-18 18:02:48 -070096 private static final String ATTR_ICON_PATH = "icon";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070097 private static final String ATTR_ID = "id";
Amith Yamasani920ace02012-09-20 22:15:37 -070098 private static final String ATTR_CREATION_TIME = "created";
99 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
Amith Yamasani2a003292012-08-14 18:25:45 -0700100 private static final String ATTR_SERIAL_NO = "serialNumber";
101 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700102 private static final String ATTR_PARTIAL = "partial";
Adam Lesinskieddeb492014-09-08 17:50:03 -0700103 private static final String ATTR_GUEST_TO_REMOVE = "guestToRemove";
Amith Yamasani6f34b412012-10-22 18:19:27 -0700104 private static final String ATTR_USER_VERSION = "version";
Kenny Guy2a764942014-04-02 13:29:20 +0100105 private static final String ATTR_PROFILE_GROUP_ID = "profileGroupId";
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700106 private static final String ATTR_RESTRICTED_PROFILE_PARENT_ID = "restrictedProfileParentId";
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530107 private static final String TAG_GUEST_RESTRICTIONS = "guestRestrictions";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700108 private static final String TAG_USERS = "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700109 private static final String TAG_USER = "user";
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800110 private static final String TAG_RESTRICTIONS = "restrictions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800111 private static final String TAG_ENTRY = "entry";
112 private static final String TAG_VALUE = "value";
113 private static final String ATTR_KEY = "key";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700114 private static final String ATTR_VALUE_TYPE = "type";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800115 private static final String ATTR_MULTIPLE = "m";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700116
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700117 private static final String ATTR_TYPE_STRING_ARRAY = "sa";
118 private static final String ATTR_TYPE_STRING = "s";
119 private static final String ATTR_TYPE_BOOLEAN = "b";
Amith Yamasani5b5aa402014-06-01 20:10:14 -0700120 private static final String ATTR_TYPE_INTEGER = "i";
Fyodor Kupolov262f9952015-03-23 18:55:11 -0700121 private static final String ATTR_TYPE_BUNDLE = "B";
122 private static final String ATTR_TYPE_BUNDLE_ARRAY = "BA";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700123
Amith Yamasani0b285492011-04-14 17:35:23 -0700124 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700125 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700126 private static final String USER_PHOTO_FILENAME = "photo.png";
Adrian Roos1bdff912015-02-17 15:51:35 +0100127 private static final String USER_PHOTO_FILENAME_TMP = USER_PHOTO_FILENAME + ".tmp";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700128
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800129 private static final String RESTRICTIONS_FILE_PREFIX = "res_";
Amith Yamasanifc95e702013-09-26 13:20:17 -0700130 private static final String XML_SUFFIX = ".xml";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800131
Amith Yamasani634cf312012-10-04 17:34:21 -0700132 private static final int MIN_USER_ID = 10;
133
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700134 private static final int USER_VERSION = 6;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700135
Amith Yamasani920ace02012-09-20 22:15:37 -0700136 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
137
Nicolas Prevotb8186812015-08-06 15:00:03 +0100138 // Maximum number of managed profiles permitted per user is 1. This cannot be increased
Amith Yamasani95ab7842014-08-11 17:09:26 -0700139 // without first making sure that the rest of the framework is prepared for it.
140 private static final int MAX_MANAGED_PROFILES = 1;
141
Andres Moralesc5548c02015-08-05 10:23:12 -0700142 /**
143 * Flag indicating whether device credentials are shared among same-user profiles.
144 */
145 private static final boolean CONFIG_PROFILES_SHARE_CREDENTIAL = true;
146
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700147 // Set of user restrictions, which can only be enforced by the system
148 private static final Set<String> SYSTEM_CONTROLLED_RESTRICTIONS = Sets.newArraySet(
149 UserManager.DISALLOW_RECORD_AUDIO);
150
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800151 static final int WRITE_USER_MSG = 1;
152 static final int WRITE_USER_DELAY = 2*1000; // 2 seconds
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530153
Jeff Sharkey6dce4962015-07-03 18:08:41 -0700154 private static final String XATTR_SERIAL = "user.serial";
155
Dianne Hackborn4428e172012-08-24 17:43:05 -0700156 private final Context mContext;
157 private final PackageManagerService mPm;
158 private final Object mInstallLock;
159 private final Object mPackagesLock;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700160
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800161 private final Handler mHandler;
162
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700163 private final File mUsersDir;
164 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700165
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800166 private final SparseArray<UserInfo> mUsers = new SparseArray<UserInfo>();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800167 private final SparseArray<Bundle> mUserRestrictions = new SparseArray<Bundle>();
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530168 private final Bundle mGuestRestrictions = new Bundle();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800169
170 /**
171 * Set of user IDs being actively removed. Removed IDs linger in this set
172 * for several seconds to work around a VFS caching issue.
173 */
174 // @GuardedBy("mPackagesLock")
175 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700176
Amith Yamasani0b285492011-04-14 17:35:23 -0700177 private int[] mUserIds;
Amith Yamasani2a003292012-08-14 18:25:45 -0700178 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700179 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700180
Jason Monk62062992014-05-06 09:55:28 -0400181 private IAppOpsService mAppOpsService;
182
Amith Yamasani258848d2012-08-10 17:06:33 -0700183 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700184
Dianne Hackborn4428e172012-08-24 17:43:05 -0700185 public static UserManagerService getInstance() {
186 synchronized (UserManagerService.class) {
187 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700188 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700189 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700190
191 /**
192 * Available for testing purposes.
193 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700194 UserManagerService(File dataDir, File baseUserPath) {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700195 this(null, null, new Object(), new Object(), dataDir, baseUserPath);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700196 }
197
Dianne Hackborn4428e172012-08-24 17:43:05 -0700198 /**
199 * Called by package manager to create the service. This is closely
200 * associated with the package manager, and the given lock is the
201 * package manager's own lock.
202 */
203 UserManagerService(Context context, PackageManagerService pm,
204 Object installLock, Object packagesLock) {
205 this(context, pm, installLock, packagesLock,
206 Environment.getDataDirectory(),
207 new File(Environment.getDataDirectory(), "user"));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700208 }
209
Dianne Hackborn4428e172012-08-24 17:43:05 -0700210 /**
211 * Available for testing purposes.
212 */
213 private UserManagerService(Context context, PackageManagerService pm,
214 Object installLock, Object packagesLock,
215 File dataDir, File baseUserPath) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700216 mContext = context;
217 mPm = pm;
218 mInstallLock = installLock;
219 mPackagesLock = packagesLock;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800220 mHandler = new MainHandler();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700221 synchronized (mInstallLock) {
222 synchronized (mPackagesLock) {
223 mUsersDir = new File(dataDir, USER_INFO_DIR);
224 mUsersDir.mkdirs();
225 // Make zeroth user directory, for services to migrate their files to that location
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700226 File userZeroDir = new File(mUsersDir, String.valueOf(UserHandle.USER_SYSTEM));
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700227 userZeroDir.mkdirs();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700228 FileUtils.setPermissions(mUsersDir.toString(),
229 FileUtils.S_IRWXU|FileUtils.S_IRWXG
230 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
231 -1, -1);
232 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
Amith Yamasanida0b1682014-11-21 12:58:17 -0800233 initDefaultGuestRestrictions();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700234 readUserListLocked();
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700235 sInstance = this;
236 }
237 }
238 }
239
240 void systemReady() {
241 synchronized (mInstallLock) {
242 synchronized (mPackagesLock) {
Amith Yamasani756901d2012-10-12 12:30:07 -0700243 // Prune out any partially created/partially removed users.
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700244 ArrayList<UserInfo> partials = new ArrayList<UserInfo>();
245 for (int i = 0; i < mUsers.size(); i++) {
246 UserInfo ui = mUsers.valueAt(i);
Adam Lesinskieddeb492014-09-08 17:50:03 -0700247 if ((ui.partial || ui.guestToRemove) && i != 0) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700248 partials.add(ui);
249 }
250 }
251 for (int i = 0; i < partials.size(); i++) {
252 UserInfo ui = partials.get(i);
Amith Yamasania7892482015-08-07 11:09:05 -0700253 Slog.w(LOG_TAG, "Removing partially created user " + ui.id
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700254 + " (name=" + ui.name + ")");
255 removeUserStateLocked(ui.id);
256 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700257 }
Dianne Hackborn4428e172012-08-24 17:43:05 -0700258 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700259 onUserForeground(UserHandle.USER_SYSTEM);
Jason Monk62062992014-05-06 09:55:28 -0400260 mAppOpsService = IAppOpsService.Stub.asInterface(
261 ServiceManager.getService(Context.APP_OPS_SERVICE));
262 for (int i = 0; i < mUserIds.length; ++i) {
263 try {
264 mAppOpsService.setUserRestrictions(mUserRestrictions.get(mUserIds[i]), mUserIds[i]);
265 } catch (RemoteException e) {
266 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
267 }
268 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700269 }
270
271 @Override
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700272 public UserInfo getPrimaryUser() {
273 checkManageUsersPermission("query users");
274 synchronized (mPackagesLock) {
275 for (int i = 0; i < mUsers.size(); i++) {
276 UserInfo ui = mUsers.valueAt(i);
277 if (ui.isPrimary()) {
278 return ui;
279 }
280 }
281 }
282 return null;
283 }
284
285 @Override
Xiaohui Chen594f2082015-08-18 11:04:20 -0700286 public @NonNull List<UserInfo> getUsers(boolean excludeDying) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700287 checkManageUsersPermission("query users");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700288 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700289 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
290 for (int i = 0; i < mUsers.size(); i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700291 UserInfo ui = mUsers.valueAt(i);
292 if (ui.partial) {
293 continue;
294 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800295 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700296 users.add(ui);
Amith Yamasani920ace02012-09-20 22:15:37 -0700297 }
Amith Yamasani13593602012-03-22 16:16:17 -0700298 }
299 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700300 }
Amith Yamasani13593602012-03-22 16:16:17 -0700301 }
302
Amith Yamasani258848d2012-08-10 17:06:33 -0700303 @Override
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100304 public List<UserInfo> getProfiles(int userId, boolean enabledOnly) {
Amith Yamasani4f582632014-02-19 14:31:52 -0800305 if (userId != UserHandle.getCallingUserId()) {
306 checkManageUsersPermission("getting profiles related to user " + userId);
307 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700308 final long ident = Binder.clearCallingIdentity();
309 try {
310 synchronized (mPackagesLock) {
311 return getProfilesLocked(userId, enabledOnly);
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100312 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700313 } finally {
314 Binder.restoreCallingIdentity(ident);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000315 }
316 }
317
Amith Yamasanibe465322014-04-24 13:45:17 -0700318 /** Assume permissions already checked and caller's identity cleared */
319 private List<UserInfo> getProfilesLocked(int userId, boolean enabledOnly) {
Amith Yamasanibe465322014-04-24 13:45:17 -0700320 UserInfo user = getUserInfoLocked(userId);
321 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasanidda003f2014-08-28 18:06:51 -0700322 if (user == null) {
323 // Probably a dying user
324 return users;
325 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700326 for (int i = 0; i < mUsers.size(); i++) {
327 UserInfo profile = mUsers.valueAt(i);
328 if (!isProfileOf(user, profile)) {
329 continue;
330 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100331 if (enabledOnly && !profile.isEnabled()) {
332 continue;
Amith Yamasanibe465322014-04-24 13:45:17 -0700333 }
Amith Yamasani70fcf0c2014-07-11 08:40:19 -0700334 if (mRemovingUserIds.get(profile.id)) {
335 continue;
336 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700337 users.add(profile);
338 }
339 return users;
340 }
341
Jessica Hummelbe81c802014-04-22 15:49:22 +0100342 @Override
Andres Moralesc5548c02015-08-05 10:23:12 -0700343 public int getCredentialOwnerProfile(int userHandle) {
344 checkManageUsersPermission("get the credential owner");
345 if (CONFIG_PROFILES_SHARE_CREDENTIAL) {
346 synchronized (mPackagesLock) {
347 UserInfo profileParent = getProfileParentLocked(userHandle);
348 if (profileParent != null) {
349 return profileParent.id;
350 }
351 }
352 }
353
354 return userHandle;
355 }
356
357 @Override
Jessica Hummelbe81c802014-04-22 15:49:22 +0100358 public UserInfo getProfileParent(int userHandle) {
359 checkManageUsersPermission("get the profile parent");
360 synchronized (mPackagesLock) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700361 return getProfileParentLocked(userHandle);
362 }
363 }
364
365 private UserInfo getProfileParentLocked(int userHandle) {
366 UserInfo profile = getUserInfoLocked(userHandle);
367 if (profile == null) {
368 return null;
369 }
370 int parentUserId = profile.profileGroupId;
371 if (parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
372 return null;
373 } else {
374 return getUserInfoLocked(parentUserId);
Jessica Hummelbe81c802014-04-22 15:49:22 +0100375 }
376 }
377
Kenny Guy2a764942014-04-02 13:29:20 +0100378 private boolean isProfileOf(UserInfo user, UserInfo profile) {
379 return user.id == profile.id ||
380 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
381 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000382 }
383
384 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100385 public void setUserEnabled(int userId) {
386 checkManageUsersPermission("enable user");
387 synchronized (mPackagesLock) {
388 UserInfo info = getUserInfoLocked(userId);
389 if (info != null && !info.isEnabled()) {
390 info.flags ^= UserInfo.FLAG_DISABLED;
391 writeUserLocked(info);
392 }
393 }
394 }
395
396 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700397 public UserInfo getUserInfo(int userId) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700398 checkManageUsersPermission("query user");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700399 synchronized (mPackagesLock) {
Amith Yamasani195263742012-08-21 15:40:12 -0700400 return getUserInfoLocked(userId);
Amith Yamasani13593602012-03-22 16:16:17 -0700401 }
402 }
403
Amith Yamasani71e6c692013-03-24 17:39:28 -0700404 @Override
405 public boolean isRestricted() {
406 synchronized (mPackagesLock) {
407 return getUserInfoLocked(UserHandle.getCallingUserId()).isRestricted();
408 }
409 }
410
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700411 @Override
412 public boolean canHaveRestrictedProfile(int userId) {
413 checkManageUsersPermission("canHaveRestrictedProfile");
414 synchronized (mPackagesLock) {
415 final UserInfo userInfo = getUserInfoLocked(userId);
416 if (userInfo == null || !userInfo.canHaveProfile()) {
417 return false;
418 }
419 if (!userInfo.isAdmin()) {
420 return false;
421 }
422 }
423 DevicePolicyManager dpm = (DevicePolicyManager) mContext.getSystemService(
424 Context.DEVICE_POLICY_SERVICE);
425 // restricted profile can be created if there is no DO set and the admin user has no PO
426 return dpm.getDeviceOwner() == null && dpm.getProfileOwnerAsUser(userId) == null;
427 }
428
Amith Yamasani195263742012-08-21 15:40:12 -0700429 /*
430 * Should be locked on mUsers before calling this.
431 */
432 private UserInfo getUserInfoLocked(int userId) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700433 UserInfo ui = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -0700434 // If it is partial and not in the process of being removed, return as unknown user.
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800435 if (ui != null && ui.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700436 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
437 return null;
438 }
439 return ui;
Amith Yamasani195263742012-08-21 15:40:12 -0700440 }
441
Amith Yamasani236b2b52015-08-18 14:32:14 -0700442 /** Called by PackageManagerService */
Amith Yamasani13593602012-03-22 16:16:17 -0700443 public boolean exists(int userId) {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700444 synchronized (mPackagesLock) {
Amith Yamasani236b2b52015-08-18 14:32:14 -0700445 return mUsers.get(userId) != null;
Amith Yamasani13593602012-03-22 16:16:17 -0700446 }
447 }
448
Amith Yamasani258848d2012-08-10 17:06:33 -0700449 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700450 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700451 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700452 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700453 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700454 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700455 if (info == null || info.partial) {
456 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
457 return;
458 }
Amith Yamasani13593602012-03-22 16:16:17 -0700459 if (name != null && !name.equals(info.name)) {
460 info.name = name;
461 writeUserLocked(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700462 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -0700463 }
464 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700465 if (changed) {
466 sendUserInfoChangedBroadcast(userId);
467 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700468 }
469
Amith Yamasani258848d2012-08-10 17:06:33 -0700470 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700471 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700472 checkManageUsersPermission("update users");
Jason Monk9a944532014-07-08 09:31:21 -0400473 long ident = Binder.clearCallingIdentity();
474 try {
475 synchronized (mPackagesLock) {
476 UserInfo info = mUsers.get(userId);
477 if (info == null || info.partial) {
478 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
479 return;
480 }
481 writeBitmapLocked(info, bitmap);
482 writeUserLocked(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700483 }
Jason Monk9a944532014-07-08 09:31:21 -0400484 sendUserInfoChangedBroadcast(userId);
485 } finally {
486 Binder.restoreCallingIdentity(ident);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700487 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700488 }
489
490 private void sendUserInfoChangedBroadcast(int userId) {
491 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
492 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
493 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -0700494 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700495 }
496
Amith Yamasani258848d2012-08-10 17:06:33 -0700497 @Override
Adrian Roos1bdff912015-02-17 15:51:35 +0100498 public ParcelFileDescriptor getUserIcon(int userId) {
499 String iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700500 synchronized (mPackagesLock) {
501 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700502 if (info == null || info.partial) {
503 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + userId);
504 return null;
505 }
Nicolas Prevot88cc3462014-05-14 14:51:48 +0100506 int callingGroupId = mUsers.get(UserHandle.getCallingUserId()).profileGroupId;
507 if (callingGroupId == UserInfo.NO_PROFILE_GROUP_ID
508 || callingGroupId != info.profileGroupId) {
509 checkManageUsersPermission("get the icon of a user who is not related");
510 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700511 if (info.iconPath == null) {
512 return null;
513 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100514 iconPath = info.iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700515 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100516
517 try {
518 return ParcelFileDescriptor.open(
519 new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
520 } catch (FileNotFoundException e) {
521 Log.e(LOG_TAG, "Couldn't find icon file", e);
522 }
523 return null;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700524 }
525
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700526 public void makeInitialized(int userId) {
527 checkManageUsersPermission("makeInitialized");
528 synchronized (mPackagesLock) {
529 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700530 if (info == null || info.partial) {
531 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
532 }
533 if ((info.flags&UserInfo.FLAG_INITIALIZED) == 0) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700534 info.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800535 scheduleWriteUserLocked(info);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700536 }
537 }
538 }
539
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700540 /**
541 * If default guest restrictions haven't been initialized yet, add the basic
542 * restrictions.
543 */
544 private void initDefaultGuestRestrictions() {
545 if (mGuestRestrictions.isEmpty()) {
546 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
Amith Yamasanida0b1682014-11-21 12:58:17 -0800547 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700548 }
549 }
550
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800551 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530552 public Bundle getDefaultGuestRestrictions() {
553 checkManageUsersPermission("getDefaultGuestRestrictions");
554 synchronized (mPackagesLock) {
555 return new Bundle(mGuestRestrictions);
556 }
557 }
558
559 @Override
560 public void setDefaultGuestRestrictions(Bundle restrictions) {
561 checkManageUsersPermission("setDefaultGuestRestrictions");
562 synchronized (mPackagesLock) {
563 mGuestRestrictions.clear();
564 mGuestRestrictions.putAll(restrictions);
565 writeUserListLocked();
566 }
567 }
568
569 @Override
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700570 public boolean hasUserRestriction(String restrictionKey, int userId) {
571 synchronized (mPackagesLock) {
572 Bundle restrictions = mUserRestrictions.get(userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700573 return restrictions != null && restrictions.getBoolean(restrictionKey);
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700574 }
575 }
576
577 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800578 public Bundle getUserRestrictions(int userId) {
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800579 synchronized (mPackagesLock) {
580 Bundle restrictions = mUserRestrictions.get(userId);
Amith Yamasanibe465322014-04-24 13:45:17 -0700581 return restrictions != null ? new Bundle(restrictions) : new Bundle();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800582 }
583 }
584
585 @Override
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700586 public void setUserRestriction(String key, boolean value, int userId) {
Fyodor Kupolovd4b26042015-07-27 14:30:59 -0700587 checkManageUsersPermission("setUserRestriction");
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700588 synchronized (mPackagesLock) {
589 if (!SYSTEM_CONTROLLED_RESTRICTIONS.contains(key)) {
590 Bundle restrictions = getUserRestrictions(userId);
591 restrictions.putBoolean(key, value);
592 setUserRestrictionsInternalLocked(restrictions, userId);
593 }
594 }
595 }
596
597 @Override
598 public void setSystemControlledUserRestriction(String key, boolean value, int userId) {
599 checkSystemOrRoot("setSystemControlledUserRestriction");
600 synchronized (mPackagesLock) {
601 Bundle restrictions = getUserRestrictions(userId);
602 restrictions.putBoolean(key, value);
603 setUserRestrictionsInternalLocked(restrictions, userId);
604 }
605 }
606
607 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800608 public void setUserRestrictions(Bundle restrictions, int userId) {
Amith Yamasanibe465322014-04-24 13:45:17 -0700609 checkManageUsersPermission("setUserRestrictions");
Amith Yamasani0343ec32013-07-22 14:52:06 -0700610 if (restrictions == null) return;
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800611
612 synchronized (mPackagesLock) {
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700613 final Bundle oldUserRestrictions = mUserRestrictions.get(userId);
614 // Restore the original state of system controlled restrictions from oldUserRestrictions
615 for (String key : SYSTEM_CONTROLLED_RESTRICTIONS) {
616 restrictions.remove(key);
617 if (oldUserRestrictions.containsKey(key)) {
618 restrictions.putBoolean(key, oldUserRestrictions.getBoolean(key));
619 }
Jason Monk62062992014-05-06 09:55:28 -0400620 }
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700621 setUserRestrictionsInternalLocked(restrictions, userId);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800622 }
623 }
624
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700625 private void setUserRestrictionsInternalLocked(Bundle restrictions, int userId) {
626 final Bundle userRestrictions = mUserRestrictions.get(userId);
627 userRestrictions.clear();
628 userRestrictions.putAll(restrictions);
629 long token = Binder.clearCallingIdentity();
630 try {
631 mAppOpsService.setUserRestrictions(userRestrictions, userId);
632 } catch (RemoteException e) {
633 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
634 } finally {
635 Binder.restoreCallingIdentity(token);
636 }
637 scheduleWriteUserLocked(mUsers.get(userId));
638 }
639
Amith Yamasani258848d2012-08-10 17:06:33 -0700640 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700641 * Check if we've hit the limit of how many users can be created.
642 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700643 private boolean isUserLimitReachedLocked() {
Nicolas Prevot12678a92015-05-13 12:15:03 -0700644 return getAliveUsersExcludingGuestsCountLocked() >= UserManager.getMaxSupportedUsers();
645 }
646
647 @Override
Nicolas Prevotb8186812015-08-06 15:00:03 +0100648 public boolean canAddMoreManagedProfiles(int userId) {
Nicolas Prevot12678a92015-05-13 12:15:03 -0700649 checkManageUsersPermission("check if more managed profiles can be added.");
650 if (ActivityManager.isLowRamDeviceStatic()) {
651 return false;
652 }
Fyodor Kupolovb6157992015-06-05 15:32:28 -0700653 if (!mContext.getPackageManager().hasSystemFeature(
654 PackageManager.FEATURE_MANAGED_USERS)) {
655 return false;
656 }
Nicolas Prevotb8186812015-08-06 15:00:03 +0100657 // Limit number of managed profiles that can be created
658 int managedProfilesCount = getProfiles(userId, true).size() - 1;
659 if (managedProfilesCount >= MAX_MANAGED_PROFILES) {
660 return false;
661 }
Nicolas Prevot12678a92015-05-13 12:15:03 -0700662 synchronized(mPackagesLock) {
Nicolas Prevotb8186812015-08-06 15:00:03 +0100663 UserInfo userInfo = getUserInfoLocked(userId);
664 if (!userInfo.canHaveProfile()) {
Nicolas Prevot12678a92015-05-13 12:15:03 -0700665 return false;
666 }
667 int usersCount = getAliveUsersExcludingGuestsCountLocked();
668 // We allow creating a managed profile in the special case where there is only one user.
669 return usersCount == 1 || usersCount < UserManager.getMaxSupportedUsers();
670 }
671 }
672
673 private int getAliveUsersExcludingGuestsCountLocked() {
Amith Yamasanif584f012014-05-19 17:57:25 -0700674 int aliveUserCount = 0;
675 final int totalUserCount = mUsers.size();
676 // Skip over users being removed
677 for (int i = 0; i < totalUserCount; i++) {
678 UserInfo user = mUsers.valueAt(i);
Amith Yamasani95ab7842014-08-11 17:09:26 -0700679 if (!mRemovingUserIds.get(user.id)
Amith Yamasani1df14732014-08-29 21:37:27 -0700680 && !user.isGuest() && !user.partial) {
Amith Yamasanif584f012014-05-19 17:57:25 -0700681 aliveUserCount++;
682 }
683 }
Nicolas Prevot12678a92015-05-13 12:15:03 -0700684 return aliveUserCount;
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700685 }
686
687 /**
Amith Yamasani195263742012-08-21 15:40:12 -0700688 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -0700689 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -0700690 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -0700691 *
692 * @param message used as message if SecurityException is thrown
693 * @throws SecurityException if the caller is not system or root
694 */
Amith Yamasanibe465322014-04-24 13:45:17 -0700695 private static final void checkManageUsersPermission(String message) {
Amith Yamasani258848d2012-08-10 17:06:33 -0700696 final int uid = Binder.getCallingUid();
Amith Yamasanibe465322014-04-24 13:45:17 -0700697 if (uid != Process.SYSTEM_UID && uid != 0
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400698 && ActivityManager.checkComponentPermission(
699 android.Manifest.permission.MANAGE_USERS,
Amith Yamasanibe465322014-04-24 13:45:17 -0700700 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
701 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
702 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400703 }
704
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700705 private static void checkSystemOrRoot(String message) {
706 final int uid = Binder.getCallingUid();
707 if (uid != Process.SYSTEM_UID && uid != 0) {
708 throw new SecurityException("Only system may call: " + message);
709 }
710 }
711
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700712 private void writeBitmapLocked(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700713 try {
714 File dir = new File(mUsersDir, Integer.toString(info.id));
715 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +0100716 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700717 if (!dir.exists()) {
718 dir.mkdir();
719 FileUtils.setPermissions(
720 dir.getPath(),
721 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
722 -1, -1);
723 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700724 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +0100725 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
726 && tmp.renameTo(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -0700727 info.iconPath = file.getAbsolutePath();
728 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700729 try {
730 os.close();
731 } catch (IOException ioe) {
732 // What the ... !
733 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100734 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700735 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700736 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700737 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700738 }
739
Amith Yamasani0b285492011-04-14 17:35:23 -0700740 /**
741 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
742 * cache it elsewhere.
743 * @return the array of user ids.
744 */
Dianne Hackborn1676c852012-09-10 14:52:30 -0700745 public int[] getUserIds() {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700746 synchronized (mPackagesLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700747 return mUserIds;
748 }
Amith Yamasani0b285492011-04-14 17:35:23 -0700749 }
750
Dianne Hackborn4428e172012-08-24 17:43:05 -0700751 int[] getUserIdsLPr() {
752 return mUserIds;
753 }
754
Amith Yamasani13593602012-03-22 16:16:17 -0700755 private void readUserListLocked() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700756 if (!mUserListFile.exists()) {
Amith Yamasani13593602012-03-22 16:16:17 -0700757 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700758 return;
759 }
760 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700761 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700762 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700763 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700764 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100765 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700766 int type;
767 while ((type = parser.next()) != XmlPullParser.START_TAG
768 && type != XmlPullParser.END_DOCUMENT) {
769 ;
770 }
771
772 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700773 Slog.e(LOG_TAG, "Unable to read user list");
Amith Yamasani13593602012-03-22 16:16:17 -0700774 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700775 return;
776 }
777
Amith Yamasani2a003292012-08-14 18:25:45 -0700778 mNextSerialNumber = -1;
779 if (parser.getName().equals(TAG_USERS)) {
780 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
781 if (lastSerialNumber != null) {
782 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
783 }
Amith Yamasani6f34b412012-10-22 18:19:27 -0700784 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
785 if (versionNumber != null) {
786 mUserVersion = Integer.parseInt(versionNumber);
787 }
Amith Yamasani2a003292012-08-14 18:25:45 -0700788 }
789
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700790 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530791 if (type == XmlPullParser.START_TAG) {
792 final String name = parser.getName();
793 if (name.equals(TAG_USER)) {
794 String id = parser.getAttributeValue(null, ATTR_ID);
795 UserInfo user = readUserLocked(Integer.parseInt(id));
Amith Yamasani6f34b412012-10-22 18:19:27 -0700796
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530797 if (user != null) {
798 mUsers.put(user.id, user);
799 if (mNextSerialNumber < 0 || mNextSerialNumber <= user.id) {
800 mNextSerialNumber = user.id + 1;
801 }
Amith Yamasani2a003292012-08-14 18:25:45 -0700802 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530803 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -0800804 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
805 && type != XmlPullParser.END_TAG) {
806 if (type == XmlPullParser.START_TAG) {
807 if (parser.getName().equals(TAG_RESTRICTIONS)) {
808 readRestrictionsLocked(parser, mGuestRestrictions);
809 }
810 break;
811 }
812 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700813 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700814 }
815 }
Amith Yamasani13593602012-03-22 16:16:17 -0700816 updateUserIdsLocked();
Amith Yamasani350962c2013-08-06 11:18:53 -0700817 upgradeIfNecessaryLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700818 } catch (IOException ioe) {
Amith Yamasani13593602012-03-22 16:16:17 -0700819 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700820 } catch (XmlPullParserException pe) {
Amith Yamasani13593602012-03-22 16:16:17 -0700821 fallbackToSingleUserLocked();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -0800822 } finally {
823 if (fis != null) {
824 try {
825 fis.close();
826 } catch (IOException e) {
827 }
828 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700829 }
830 }
831
Amith Yamasani6f34b412012-10-22 18:19:27 -0700832 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -0800833 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -0700834 */
Amith Yamasani350962c2013-08-06 11:18:53 -0700835 private void upgradeIfNecessaryLocked() {
Amith Yamasani6f34b412012-10-22 18:19:27 -0700836 int userVersion = mUserVersion;
837 if (userVersion < 1) {
838 // Assign a proper name for the owner, if not initialized correctly before
839 UserInfo user = mUsers.get(UserHandle.USER_OWNER);
840 if ("Primary".equals(user.name)) {
841 user.name = mContext.getResources().getString(com.android.internal.R.string.owner_name);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800842 scheduleWriteUserLocked(user);
Amith Yamasani6f34b412012-10-22 18:19:27 -0700843 }
844 userVersion = 1;
845 }
846
Amith Yamasanibc9625052012-11-15 14:39:18 -0800847 if (userVersion < 2) {
848 // Owner should be marked as initialized
849 UserInfo user = mUsers.get(UserHandle.USER_OWNER);
850 if ((user.flags & UserInfo.FLAG_INITIALIZED) == 0) {
851 user.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800852 scheduleWriteUserLocked(user);
Amith Yamasanibc9625052012-11-15 14:39:18 -0800853 }
854 userVersion = 2;
855 }
856
Amith Yamasani350962c2013-08-06 11:18:53 -0700857
Amith Yamasani5e486f52013-08-07 11:06:44 -0700858 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -0700859 userVersion = 4;
860 }
861
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700862 if (userVersion < 5) {
863 initDefaultGuestRestrictions();
864 userVersion = 5;
865 }
866
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700867 if (userVersion < 6) {
868 final boolean splitSystemUser = UserManager.isSplitSystemUser();
869 for (int i = 0; i < mUsers.size(); i++) {
870 UserInfo user = mUsers.valueAt(i);
871 // In non-split mode, only user 0 can have restricted profiles
872 if (!splitSystemUser && user.isRestricted()
873 && (user.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID)) {
874 user.restrictedProfileParentId = UserHandle.USER_SYSTEM;
875 scheduleWriteUserLocked(user);
876 }
877 }
878 userVersion = 6;
879 }
880
Amith Yamasani6f34b412012-10-22 18:19:27 -0700881 if (userVersion < USER_VERSION) {
882 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
883 + USER_VERSION);
884 } else {
885 mUserVersion = userVersion;
886 writeUserListLocked();
887 }
888 }
889
Amith Yamasani13593602012-03-22 16:16:17 -0700890 private void fallbackToSingleUserLocked() {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -0700891 int flags = UserInfo.FLAG_INITIALIZED;
892 // In split system user mode, the admin and primary flags are assigned to the first human
893 // user.
894 if (!UserManager.isSplitSystemUser()) {
895 flags |= UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY;
896 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700897 // Create the system user
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700898 UserInfo system = new UserInfo(UserHandle.USER_SYSTEM,
Amith Yamasani6f34b412012-10-22 18:19:27 -0700899 mContext.getResources().getString(com.android.internal.R.string.owner_name), null,
Xiaohui Chenb31e14a2015-07-13 16:04:55 -0700900 flags);
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700901 mUsers.put(system.id, system);
Amith Yamasani634cf312012-10-04 17:34:21 -0700902 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -0400903 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -0800904
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -0500905 Bundle restrictions = new Bundle();
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700906 mUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions);
Amith Yamasani67df64b2012-12-14 12:09:36 -0800907
Amith Yamasani13593602012-03-22 16:16:17 -0700908 updateUserIdsLocked();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700909 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700910
Amith Yamasani13593602012-03-22 16:16:17 -0700911 writeUserListLocked();
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700912 writeUserLocked(system);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700913 }
914
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800915 private void scheduleWriteUserLocked(UserInfo userInfo) {
916 if (!mHandler.hasMessages(WRITE_USER_MSG, userInfo)) {
917 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, userInfo);
918 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
919 }
920 }
921
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700922 /*
923 * Writes the user file in this format:
924 *
925 * <user flags="20039023" id="0">
926 * <name>Primary</name>
927 * </user>
928 */
Amith Yamasani13593602012-03-22 16:16:17 -0700929 private void writeUserLocked(UserInfo userInfo) {
Amith Yamasani742a6712011-05-04 14:49:28 -0700930 FileOutputStream fos = null;
Amith Yamasanifc95e702013-09-26 13:20:17 -0700931 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userInfo.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700932 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700933 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700934 final BufferedOutputStream bos = new BufferedOutputStream(fos);
935
936 // XmlSerializer serializer = XmlUtils.serializerInstance();
937 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100938 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700939 serializer.startDocument(null, true);
940 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
941
942 serializer.startTag(null, TAG_USER);
943 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
Amith Yamasani2a003292012-08-14 18:25:45 -0700944 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700945 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Amith Yamasani920ace02012-09-20 22:15:37 -0700946 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
947 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
948 Long.toString(userInfo.lastLoggedInTime));
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700949 if (userInfo.iconPath != null) {
950 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
951 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700952 if (userInfo.partial) {
953 serializer.attribute(null, ATTR_PARTIAL, "true");
954 }
Adam Lesinskieddeb492014-09-08 17:50:03 -0700955 if (userInfo.guestToRemove) {
956 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
957 }
Kenny Guy2a764942014-04-02 13:29:20 +0100958 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
959 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
960 Integer.toString(userInfo.profileGroupId));
Kenny Guya52dc3e2014-02-11 15:33:14 +0000961 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700962 if (userInfo.restrictedProfileParentId != UserInfo.NO_PROFILE_GROUP_ID) {
963 serializer.attribute(null, ATTR_RESTRICTED_PROFILE_PARENT_ID,
964 Integer.toString(userInfo.restrictedProfileParentId));
965 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700966 serializer.startTag(null, TAG_NAME);
967 serializer.text(userInfo.name);
968 serializer.endTag(null, TAG_NAME);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800969 Bundle restrictions = mUserRestrictions.get(userInfo.id);
970 if (restrictions != null) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530971 writeRestrictionsLocked(serializer, restrictions);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800972 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700973 serializer.endTag(null, TAG_USER);
974
975 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -0700976 userFile.finishWrite(fos);
977 } catch (Exception ioe) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700978 Slog.e(LOG_TAG, "Error writing user info " + userInfo.id + "\n" + ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -0700979 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700980 }
981 }
982
983 /*
984 * Writes the user list file in this format:
985 *
Amith Yamasani2a003292012-08-14 18:25:45 -0700986 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700987 * <user id="0"></user>
988 * <user id="2"></user>
989 * </users>
990 */
Amith Yamasani13593602012-03-22 16:16:17 -0700991 private void writeUserListLocked() {
Amith Yamasani742a6712011-05-04 14:49:28 -0700992 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700993 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700994 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700995 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700996 final BufferedOutputStream bos = new BufferedOutputStream(fos);
997
998 // XmlSerializer serializer = XmlUtils.serializerInstance();
999 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001000 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001001 serializer.startDocument(null, true);
1002 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1003
1004 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -07001005 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -07001006 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001007
Adam Lesinskieddeb492014-09-08 17:50:03 -07001008 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301009 writeRestrictionsLocked(serializer, mGuestRestrictions);
1010 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001011 for (int i = 0; i < mUsers.size(); i++) {
1012 UserInfo user = mUsers.valueAt(i);
1013 serializer.startTag(null, TAG_USER);
1014 serializer.attribute(null, ATTR_ID, Integer.toString(user.id));
1015 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001016 }
1017
1018 serializer.endTag(null, TAG_USERS);
1019
1020 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001021 userListFile.finishWrite(fos);
1022 } catch (Exception e) {
1023 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -07001024 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001025 }
1026 }
1027
Andres Moralesc5548c02015-08-05 10:23:12 -07001028 private void writeRestrictionsLocked(XmlSerializer serializer, Bundle restrictions)
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301029 throws IOException {
1030 serializer.startTag(null, TAG_RESTRICTIONS);
1031 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_WIFI);
1032 writeBoolean(serializer, restrictions, UserManager.DISALLOW_MODIFY_ACCOUNTS);
1033 writeBoolean(serializer, restrictions, UserManager.DISALLOW_INSTALL_APPS);
1034 writeBoolean(serializer, restrictions, UserManager.DISALLOW_UNINSTALL_APPS);
1035 writeBoolean(serializer, restrictions, UserManager.DISALLOW_SHARE_LOCATION);
1036 writeBoolean(serializer, restrictions,
1037 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
1038 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_BLUETOOTH);
1039 writeBoolean(serializer, restrictions, UserManager.DISALLOW_USB_FILE_TRANSFER);
1040 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_CREDENTIALS);
1041 writeBoolean(serializer, restrictions, UserManager.DISALLOW_REMOVE_USER);
1042 writeBoolean(serializer, restrictions, UserManager.DISALLOW_DEBUGGING_FEATURES);
1043 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_VPN);
1044 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_TETHERING);
Stuart Scott94b038b2015-04-20 14:07:45 -07001045 writeBoolean(serializer, restrictions, UserManager.DISALLOW_NETWORK_RESET);
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301046 writeBoolean(serializer, restrictions, UserManager.DISALLOW_FACTORY_RESET);
1047 writeBoolean(serializer, restrictions, UserManager.DISALLOW_ADD_USER);
1048 writeBoolean(serializer, restrictions, UserManager.ENSURE_VERIFY_APPS);
1049 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_CELL_BROADCASTS);
1050 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS);
1051 writeBoolean(serializer, restrictions, UserManager.DISALLOW_APPS_CONTROL);
1052 writeBoolean(serializer, restrictions, UserManager.DISALLOW_MOUNT_PHYSICAL_MEDIA);
1053 writeBoolean(serializer, restrictions, UserManager.DISALLOW_UNMUTE_MICROPHONE);
1054 writeBoolean(serializer, restrictions, UserManager.DISALLOW_ADJUST_VOLUME);
Amith Yamasani390989d2014-07-17 10:52:03 -07001055 writeBoolean(serializer, restrictions, UserManager.DISALLOW_OUTGOING_CALLS);
1056 writeBoolean(serializer, restrictions, UserManager.DISALLOW_SMS);
Jeff Sharkey2cc03e52015-03-20 11:24:04 -07001057 writeBoolean(serializer, restrictions, UserManager.DISALLOW_FUN);
Jason Monk1c7c3192014-06-26 12:52:18 -04001058 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CREATE_WINDOWS);
Amith Yamasani26af8292014-09-09 09:57:27 -07001059 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CROSS_PROFILE_COPY_PASTE);
1060 writeBoolean(serializer, restrictions, UserManager.DISALLOW_OUTGOING_BEAM);
Benjamin Franzf3ece362015-02-11 10:51:10 +00001061 writeBoolean(serializer, restrictions, UserManager.DISALLOW_WALLPAPER);
Benjamin Franzbff46ba2015-03-05 18:33:51 +00001062 writeBoolean(serializer, restrictions, UserManager.DISALLOW_SAFE_BOOT);
Nicolas Prevotf0029c12015-06-25 14:25:41 -07001063 writeBoolean(serializer, restrictions, UserManager.ALLOW_PARENT_PROFILE_APP_LINKING);
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301064 serializer.endTag(null, TAG_RESTRICTIONS);
1065 }
1066
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001067 private UserInfo readUserLocked(int id) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001068 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -07001069 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001070 String name = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001071 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -07001072 long creationTime = 0L;
1073 long lastLoggedInTime = 0L;
Kenny Guy2a764942014-04-02 13:29:20 +01001074 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001075 int restrictedProfileParentId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001076 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001077 boolean guestToRemove = false;
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001078 Bundle restrictions = new Bundle();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001079
1080 FileInputStream fis = null;
1081 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001082 AtomicFile userFile =
Amith Yamasanifc95e702013-09-26 13:20:17 -07001083 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
Amith Yamasani2a003292012-08-14 18:25:45 -07001084 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001085 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001086 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001087 int type;
1088 while ((type = parser.next()) != XmlPullParser.START_TAG
1089 && type != XmlPullParser.END_DOCUMENT) {
1090 ;
1091 }
1092
1093 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001094 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001095 return null;
1096 }
1097
1098 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001099 int storedId = readIntAttribute(parser, ATTR_ID, -1);
1100 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001101 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001102 return null;
1103 }
Amith Yamasani920ace02012-09-20 22:15:37 -07001104 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
1105 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001106 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -07001107 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
1108 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Kenny Guy2a764942014-04-02 13:29:20 +01001109 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
1110 UserInfo.NO_PROFILE_GROUP_ID);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001111 restrictedProfileParentId = readIntAttribute(parser,
1112 ATTR_RESTRICTED_PROFILE_PARENT_ID, UserInfo.NO_PROFILE_GROUP_ID);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001113 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
1114 if ("true".equals(valueString)) {
1115 partial = true;
1116 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001117 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
1118 if ("true".equals(valueString)) {
1119 guestToRemove = true;
1120 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001121
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001122 int outerDepth = parser.getDepth();
1123 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1124 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1125 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1126 continue;
1127 }
1128 String tag = parser.getName();
1129 if (TAG_NAME.equals(tag)) {
1130 type = parser.next();
1131 if (type == XmlPullParser.TEXT) {
1132 name = parser.getText();
1133 }
1134 } else if (TAG_RESTRICTIONS.equals(tag)) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301135 readRestrictionsLocked(parser, restrictions);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001136 }
1137 }
1138 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001139
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001140 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -07001141 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -07001142 userInfo.creationTime = creationTime;
1143 userInfo.lastLoggedInTime = lastLoggedInTime;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001144 userInfo.partial = partial;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001145 userInfo.guestToRemove = guestToRemove;
Kenny Guy2a764942014-04-02 13:29:20 +01001146 userInfo.profileGroupId = profileGroupId;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001147 userInfo.restrictedProfileParentId = restrictedProfileParentId;
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001148 mUserRestrictions.append(id, restrictions);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001149 return userInfo;
1150
1151 } catch (IOException ioe) {
1152 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001153 } finally {
1154 if (fis != null) {
1155 try {
1156 fis.close();
1157 } catch (IOException e) {
1158 }
1159 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001160 }
1161 return null;
1162 }
1163
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301164 private void readRestrictionsLocked(XmlPullParser parser, Bundle restrictions)
1165 throws IOException {
1166 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_WIFI);
1167 readBoolean(parser, restrictions, UserManager.DISALLOW_MODIFY_ACCOUNTS);
1168 readBoolean(parser, restrictions, UserManager.DISALLOW_INSTALL_APPS);
1169 readBoolean(parser, restrictions, UserManager.DISALLOW_UNINSTALL_APPS);
1170 readBoolean(parser, restrictions, UserManager.DISALLOW_SHARE_LOCATION);
1171 readBoolean(parser, restrictions,
1172 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
1173 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_BLUETOOTH);
1174 readBoolean(parser, restrictions, UserManager.DISALLOW_USB_FILE_TRANSFER);
1175 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_CREDENTIALS);
1176 readBoolean(parser, restrictions, UserManager.DISALLOW_REMOVE_USER);
1177 readBoolean(parser, restrictions, UserManager.DISALLOW_DEBUGGING_FEATURES);
1178 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_VPN);
1179 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_TETHERING);
Stuart Scott94b038b2015-04-20 14:07:45 -07001180 readBoolean(parser, restrictions, UserManager.DISALLOW_NETWORK_RESET);
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301181 readBoolean(parser, restrictions, UserManager.DISALLOW_FACTORY_RESET);
1182 readBoolean(parser, restrictions, UserManager.DISALLOW_ADD_USER);
1183 readBoolean(parser, restrictions, UserManager.ENSURE_VERIFY_APPS);
1184 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_CELL_BROADCASTS);
1185 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS);
1186 readBoolean(parser, restrictions, UserManager.DISALLOW_APPS_CONTROL);
1187 readBoolean(parser, restrictions,
1188 UserManager.DISALLOW_MOUNT_PHYSICAL_MEDIA);
1189 readBoolean(parser, restrictions, UserManager.DISALLOW_UNMUTE_MICROPHONE);
1190 readBoolean(parser, restrictions, UserManager.DISALLOW_ADJUST_VOLUME);
Amith Yamasani390989d2014-07-17 10:52:03 -07001191 readBoolean(parser, restrictions, UserManager.DISALLOW_OUTGOING_CALLS);
1192 readBoolean(parser, restrictions, UserManager.DISALLOW_SMS);
Jeff Sharkey2cc03e52015-03-20 11:24:04 -07001193 readBoolean(parser, restrictions, UserManager.DISALLOW_FUN);
Jason Monk1c7c3192014-06-26 12:52:18 -04001194 readBoolean(parser, restrictions, UserManager.DISALLOW_CREATE_WINDOWS);
Amith Yamasani26af8292014-09-09 09:57:27 -07001195 readBoolean(parser, restrictions, UserManager.DISALLOW_CROSS_PROFILE_COPY_PASTE);
1196 readBoolean(parser, restrictions, UserManager.DISALLOW_OUTGOING_BEAM);
Benjamin Franzf3ece362015-02-11 10:51:10 +00001197 readBoolean(parser, restrictions, UserManager.DISALLOW_WALLPAPER);
Benjamin Franzbff46ba2015-03-05 18:33:51 +00001198 readBoolean(parser, restrictions, UserManager.DISALLOW_SAFE_BOOT);
Nicolas Prevotf0029c12015-06-25 14:25:41 -07001199 readBoolean(parser, restrictions, UserManager.ALLOW_PARENT_PROFILE_APP_LINKING);
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301200 }
1201
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001202 private void readBoolean(XmlPullParser parser, Bundle restrictions,
1203 String restrictionKey) {
1204 String value = parser.getAttributeValue(null, restrictionKey);
Amith Yamasani71e6c692013-03-24 17:39:28 -07001205 if (value != null) {
1206 restrictions.putBoolean(restrictionKey, Boolean.parseBoolean(value));
1207 }
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001208 }
1209
1210 private void writeBoolean(XmlSerializer xml, Bundle restrictions, String restrictionKey)
1211 throws IOException {
1212 if (restrictions.containsKey(restrictionKey)) {
1213 xml.attribute(null, restrictionKey,
1214 Boolean.toString(restrictions.getBoolean(restrictionKey)));
1215 }
1216 }
1217
Amith Yamasani920ace02012-09-20 22:15:37 -07001218 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
1219 String valueString = parser.getAttributeValue(null, attr);
1220 if (valueString == null) return defaultValue;
1221 try {
1222 return Integer.parseInt(valueString);
1223 } catch (NumberFormatException nfe) {
1224 return defaultValue;
1225 }
1226 }
1227
1228 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
1229 String valueString = parser.getAttributeValue(null, attr);
1230 if (valueString == null) return defaultValue;
1231 try {
1232 return Long.parseLong(valueString);
1233 } catch (NumberFormatException nfe) {
1234 return defaultValue;
1235 }
1236 }
1237
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001238 private boolean isPackageInstalled(String pkg, int userId) {
1239 final ApplicationInfo info = mPm.getApplicationInfo(pkg,
1240 PackageManager.GET_UNINSTALLED_PACKAGES,
1241 userId);
1242 if (info == null || (info.flags&ApplicationInfo.FLAG_INSTALLED) == 0) {
1243 return false;
1244 }
1245 return true;
1246 }
1247
Amith Yamasanib82add22013-07-09 11:24:44 -07001248 /**
Kenny Guyd21b2182014-07-17 16:38:55 +01001249 * Removes all the restrictions files (res_<packagename>) for a given user.
Amith Yamasanib82add22013-07-09 11:24:44 -07001250 * Does not do any permissions checking.
1251 */
Kenny Guyd21b2182014-07-17 16:38:55 +01001252 private void cleanAppRestrictions(int userId) {
Amith Yamasanib82add22013-07-09 11:24:44 -07001253 synchronized (mPackagesLock) {
1254 File dir = Environment.getUserSystemDirectory(userId);
1255 String[] files = dir.list();
1256 if (files == null) return;
1257 for (String fileName : files) {
1258 if (fileName.startsWith(RESTRICTIONS_FILE_PREFIX)) {
1259 File resFile = new File(dir, fileName);
1260 if (resFile.exists()) {
Kenny Guyd21b2182014-07-17 16:38:55 +01001261 resFile.delete();
Amith Yamasanib82add22013-07-09 11:24:44 -07001262 }
1263 }
1264 }
1265 }
1266 }
1267
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001268 /**
1269 * Removes the app restrictions file for a specific package and user id, if it exists.
1270 */
1271 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
1272 synchronized (mPackagesLock) {
1273 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07001274 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001275 if (resFile.exists()) {
1276 resFile.delete();
1277 }
1278 }
1279 }
1280
Kenny Guya52dc3e2014-02-11 15:33:14 +00001281 @Override
Kenny Guy2a764942014-04-02 13:29:20 +01001282 public UserInfo createProfileForUser(String name, int flags, int userId) {
Kenny Guya52dc3e2014-02-11 15:33:14 +00001283 checkManageUsersPermission("Only the system can create users");
Kenny Guy2a764942014-04-02 13:29:20 +01001284 return createUserInternal(name, flags, userId);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001285 }
1286
Amith Yamasani258848d2012-08-10 17:06:33 -07001287 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07001288 public UserInfo createUser(String name, int flags) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001289 checkManageUsersPermission("Only the system can create users");
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001290 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001291 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001292
Jessica Hummelbe81c802014-04-22 15:49:22 +01001293 private UserInfo createUserInternal(String name, int flags, int parentId) {
Julia Reynolds75175022014-06-26 16:35:00 -04001294 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1295 UserManager.DISALLOW_ADD_USER, false)) {
1296 Log.w(LOG_TAG, "Cannot add user. DISALLOW_ADD_USER is enabled.");
1297 return null;
1298 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001299 if (ActivityManager.isLowRamDeviceStatic()) {
1300 return null;
1301 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07001302 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001303 final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001304 final boolean isRestricted = (flags & UserInfo.FLAG_RESTRICTED) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001305 final long ident = Binder.clearCallingIdentity();
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001306 UserInfo userInfo = null;
Amith Yamasanibb054c92015-07-09 14:16:27 -07001307 final int userId;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001308 try {
1309 synchronized (mInstallLock) {
1310 synchronized (mPackagesLock) {
Jessica Hummelbe81c802014-04-22 15:49:22 +01001311 UserInfo parent = null;
1312 if (parentId != UserHandle.USER_NULL) {
1313 parent = getUserInfoLocked(parentId);
1314 if (parent == null) return null;
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001315 }
Nicolas Prevotb8186812015-08-06 15:00:03 +01001316 if (isManagedProfile && !canAddMoreManagedProfiles(parentId)) {
1317 Log.e(LOG_TAG, "Cannot add more managed profiles for user " + parentId);
Nicolas Prevot12678a92015-05-13 12:15:03 -07001318 return null;
1319 }
1320 if (!isGuest && !isManagedProfile && isUserLimitReachedLocked()) {
1321 // If we're not adding a guest user or a managed profile and the limit has
1322 // been reached, cannot add a user.
Amith Yamasani95ab7842014-08-11 17:09:26 -07001323 return null;
1324 }
1325 // If we're adding a guest and there already exists one, bail.
Adam Lesinskieddeb492014-09-08 17:50:03 -07001326 if (isGuest && findCurrentGuestUserLocked() != null) {
Amith Yamasani95ab7842014-08-11 17:09:26 -07001327 return null;
1328 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001329 // In legacy mode, restricted profile's parent can only be the owner user
1330 if (isRestricted && !UserManager.isSplitSystemUser()
1331 && (parentId != UserHandle.USER_SYSTEM)) {
1332 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
1333 return null;
1334 }
1335 if (isRestricted && UserManager.isSplitSystemUser()) {
1336 if (parent == null) {
1337 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be "
1338 + "specified");
1339 return null;
1340 }
1341 if (!parent.canHaveProfile()) {
1342 Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be "
1343 + "created for the specified parent user id " + parentId);
1344 return null;
1345 }
1346 }
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001347 // In split system user mode, we assign the first human user the primary flag.
Xiaohui Chen203243a2015-07-16 11:55:47 -07001348 // And if there is no device owner, we also assign the admin flag to primary
1349 // user.
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001350 if (UserManager.isSplitSystemUser()
Xiaohui Chen203243a2015-07-16 11:55:47 -07001351 && !isGuest && !isManagedProfile && getPrimaryUser() == null) {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001352 flags |= UserInfo.FLAG_PRIMARY;
Xiaohui Chen203243a2015-07-16 11:55:47 -07001353 DevicePolicyManager devicePolicyManager = (DevicePolicyManager)
1354 mContext.getSystemService(Context.DEVICE_POLICY_SERVICE);
1355 if (devicePolicyManager == null
1356 || devicePolicyManager.getDeviceOwner() == null) {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001357 flags |= UserInfo.FLAG_ADMIN;
1358 }
1359 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07001360 userId = getNextAvailableIdLocked();
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001361 userInfo = new UserInfo(userId, name, null, flags);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001362 userInfo.serialNumber = mNextSerialNumber++;
Amith Yamasani920ace02012-09-20 22:15:37 -07001363 long now = System.currentTimeMillis();
1364 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001365 userInfo.partial = true;
Amith Yamasani16389312012-10-17 21:20:14 -07001366 Environment.getUserSystemDirectory(userInfo.id).mkdirs();
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001367 mUsers.put(userId, userInfo);
1368 writeUserListLocked();
Jessica Hummelbe81c802014-04-22 15:49:22 +01001369 if (parent != null) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001370 if (isManagedProfile) {
1371 if (parent.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
1372 parent.profileGroupId = parent.id;
1373 scheduleWriteUserLocked(parent);
1374 }
1375 userInfo.profileGroupId = parent.profileGroupId;
1376 } else if (isRestricted) {
1377 if (!parent.canHaveProfile()) {
1378 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
1379 }
1380 if (parent.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) {
1381 parent.restrictedProfileParentId = parent.id;
1382 scheduleWriteUserLocked(parent);
1383 }
1384 userInfo.restrictedProfileParentId = parent.restrictedProfileParentId;
Kenny Guya52dc3e2014-02-11 15:33:14 +00001385 }
Kenny Guya52dc3e2014-02-11 15:33:14 +00001386 }
Jeff Sharkey6dce4962015-07-03 18:08:41 -07001387 final StorageManager storage = mContext.getSystemService(StorageManager.class);
1388 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
1389 final String volumeUuid = vol.getFsUuid();
1390 try {
1391 final File userDir = Environment.getDataUserDirectory(volumeUuid,
1392 userId);
Jeff Sharkey3bb8c852015-07-06 16:44:23 -07001393 prepareUserDirectory(mContext, volumeUuid, userId);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07001394 enforceSerialNumber(userDir, userInfo.serialNumber);
1395 } catch (IOException e) {
1396 Log.wtf(LOG_TAG, "Failed to create user directory on " + volumeUuid, e);
1397 }
1398 }
1399 mPm.createNewUserLILPw(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001400 userInfo.partial = false;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001401 scheduleWriteUserLocked(userInfo);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001402 updateUserIdsLocked();
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001403 Bundle restrictions = new Bundle();
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001404 mUserRestrictions.append(userId, restrictions);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001405 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07001406 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07001407 mPm.newUserCreated(userId);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001408 if (userInfo != null) {
1409 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
1410 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userInfo.id);
1411 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
1412 android.Manifest.permission.MANAGE_USERS);
1413 }
1414 } finally {
1415 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07001416 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001417 return userInfo;
1418 }
1419
Amith Yamasani0b285492011-04-14 17:35:23 -07001420 /**
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07001421 * @hide
1422 */
1423 public UserInfo createRestrictedProfile(String name, int parentUserId) {
1424 checkManageUsersPermission("setupRestrictedProfile");
1425 final UserInfo user = createProfileForUser(name, UserInfo.FLAG_RESTRICTED, parentUserId);
1426 if (user == null) {
1427 return null;
1428 }
1429 setUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, true, user.id);
1430 // Change the setting before applying the DISALLOW_SHARE_LOCATION restriction, otherwise
1431 // the putIntForUser() will fail.
1432 android.provider.Settings.Secure.putIntForUser(mContext.getContentResolver(),
1433 android.provider.Settings.Secure.LOCATION_MODE,
1434 android.provider.Settings.Secure.LOCATION_MODE_OFF, user.id);
1435 setUserRestriction(UserManager.DISALLOW_SHARE_LOCATION, true, user.id);
1436 return user;
1437 }
1438
1439 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07001440 * Find the current guest user. If the Guest user is partial,
1441 * then do not include it in the results as it is about to die.
Adam Lesinskieddeb492014-09-08 17:50:03 -07001442 */
1443 private UserInfo findCurrentGuestUserLocked() {
1444 final int size = mUsers.size();
1445 for (int i = 0; i < size; i++) {
1446 final UserInfo user = mUsers.valueAt(i);
1447 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
1448 return user;
1449 }
1450 }
1451 return null;
1452 }
1453
1454 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07001455 * Mark this guest user for deletion to allow us to create another guest
1456 * and switch to that user before actually removing this guest.
1457 * @param userHandle the userid of the current guest
1458 * @return whether the user could be marked for deletion
1459 */
1460 public boolean markGuestForDeletion(int userHandle) {
1461 checkManageUsersPermission("Only the system can remove users");
1462 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1463 UserManager.DISALLOW_REMOVE_USER, false)) {
1464 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1465 return false;
1466 }
1467
1468 long ident = Binder.clearCallingIdentity();
1469 try {
1470 final UserInfo user;
1471 synchronized (mPackagesLock) {
1472 user = mUsers.get(userHandle);
1473 if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
1474 return false;
1475 }
1476 if (!user.isGuest()) {
1477 return false;
1478 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001479 // We set this to a guest user that is to be removed. This is a temporary state
1480 // where we are allowed to add new Guest users, even if this one is still not
1481 // removed. This user will still show up in getUserInfo() calls.
1482 // If we don't get around to removing this Guest user, it will be purged on next
1483 // startup.
1484 user.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07001485 // Mark it as disabled, so that it isn't returned any more when
1486 // profiles are queried.
1487 user.flags |= UserInfo.FLAG_DISABLED;
Amith Yamasani1df14732014-08-29 21:37:27 -07001488 writeUserLocked(user);
1489 }
1490 } finally {
1491 Binder.restoreCallingIdentity(ident);
1492 }
1493 return true;
1494 }
1495
1496 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07001497 * Removes a user and all data directories created for that user. This method should be called
1498 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001499 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07001500 */
Amith Yamasani258848d2012-08-10 17:06:33 -07001501 public boolean removeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001502 checkManageUsersPermission("Only the system can remove users");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04001503 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1504 UserManager.DISALLOW_REMOVE_USER, false)) {
1505 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1506 return false;
1507 }
1508
Kenny Guyee58b4f2014-05-23 15:19:53 +01001509 long ident = Binder.clearCallingIdentity();
1510 try {
1511 final UserInfo user;
1512 synchronized (mPackagesLock) {
1513 user = mUsers.get(userHandle);
Kenny Guy17c9d692014-06-13 13:51:42 +01001514 if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01001515 return false;
1516 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08001517
1518 // We remember deleted user IDs to prevent them from being
1519 // reused during the current boot; they can still be reused
1520 // after a reboot.
Kenny Guyee58b4f2014-05-23 15:19:53 +01001521 mRemovingUserIds.put(userHandle, true);
Jeff Sharkey6eb09392014-11-14 15:57:59 -08001522
Kenny Guyee58b4f2014-05-23 15:19:53 +01001523 try {
1524 mAppOpsService.removeUser(userHandle);
1525 } catch (RemoteException e) {
1526 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
1527 }
1528 // Set this to a partially created user, so that the user will be purged
1529 // on next startup, in case the runtime stops now before stopping and
1530 // removing the user completely.
1531 user.partial = true;
1532 // Mark it as disabled, so that it isn't returned any more when
1533 // profiles are queried.
1534 user.flags |= UserInfo.FLAG_DISABLED;
1535 writeUserLocked(user);
1536 }
1537
1538 if (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
1539 && user.isManagedProfile()) {
1540 // Send broadcast to notify system that the user removed was a
1541 // managed user.
1542 sendProfileRemovedBroadcast(user.profileGroupId, user.id);
1543 }
1544
1545 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
1546 int res;
1547 try {
1548 res = ActivityManagerNative.getDefault().stopUser(userHandle,
1549 new IStopUserCallback.Stub() {
1550 @Override
1551 public void userStopped(int userId) {
1552 finishRemoveUser(userId);
1553 }
1554 @Override
1555 public void userStopAborted(int userId) {
1556 }
1557 });
1558 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001559 return false;
1560 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01001561 return res == ActivityManager.USER_OP_SUCCESS;
1562 } finally {
1563 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001564 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001565 }
1566
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001567 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07001568 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001569 // Let other services shutdown any activity and clean up their state before completely
1570 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001571 long ident = Binder.clearCallingIdentity();
1572 try {
1573 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
1574 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001575 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
1576 android.Manifest.permission.MANAGE_USERS,
1577
1578 new BroadcastReceiver() {
1579 @Override
1580 public void onReceive(Context context, Intent intent) {
1581 if (DBG) {
1582 Slog.i(LOG_TAG,
1583 "USER_REMOVED broadcast sent, cleaning up user data "
1584 + userHandle);
1585 }
1586 new Thread() {
1587 public void run() {
1588 synchronized (mInstallLock) {
1589 synchronized (mPackagesLock) {
1590 removeUserStateLocked(userHandle);
1591 }
1592 }
1593 }
1594 }.start();
1595 }
1596 },
1597
1598 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001599 } finally {
1600 Binder.restoreCallingIdentity(ident);
1601 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001602 }
1603
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001604 private void removeUserStateLocked(final int userHandle) {
Paul Crowley85e4e812015-05-19 12:42:00 +01001605 mContext.getSystemService(StorageManager.class)
1606 .deleteUserKey(userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001607 // Cleanup package manager settings
Amith Yamasanidda003f2014-08-28 18:06:51 -07001608 mPm.cleanUpUserLILPw(this, userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001609
1610 // Remove this user from the list
1611 mUsers.remove(userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001612 // Remove user file
Amith Yamasanifc95e702013-09-26 13:20:17 -07001613 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001614 userFile.delete();
1615 // Update the user list
1616 writeUserListLocked();
1617 updateUserIdsLocked();
1618 removeDirectoryRecursive(Environment.getUserSystemDirectory(userHandle));
1619 }
1620
Amith Yamasani61f57372012-08-31 12:12:28 -07001621 private void removeDirectoryRecursive(File parent) {
1622 if (parent.isDirectory()) {
1623 String[] files = parent.list();
1624 for (String filename : files) {
1625 File child = new File(parent, filename);
1626 removeDirectoryRecursive(child);
1627 }
1628 }
1629 parent.delete();
1630 }
1631
Kenny Guyf8d3a232014-05-15 16:09:52 +01001632 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01001633 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01001634 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
1635 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01001636 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
1637 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01001638 }
1639
Amith Yamasani2a003292012-08-14 18:25:45 -07001640 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001641 public Bundle getApplicationRestrictions(String packageName) {
1642 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
1643 }
1644
1645 @Override
1646 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001647 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07001648 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Esteban Talavera2a5d6c62015-10-21 10:55:56 +01001649 checkManageUsersPermission("get application restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001650 }
1651 synchronized (mPackagesLock) {
1652 // Read the restrictions from XML
1653 return readApplicationRestrictionsLocked(packageName, userId);
1654 }
1655 }
1656
1657 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001658 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001659 int userId) {
Esteban Talavera2a5d6c62015-10-21 10:55:56 +01001660 checkManageUsersPermission("set application restrictions");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001661 synchronized (mPackagesLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01001662 if (restrictions == null || restrictions.isEmpty()) {
1663 cleanAppRestrictionsForPackage(packageName, userId);
1664 } else {
1665 // Write the restrictions to XML
1666 writeApplicationRestrictionsLocked(packageName, restrictions, userId);
1667 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001668 }
Robin Lee66e5d962014-04-09 16:44:21 +01001669
Kenny Guyd21b2182014-07-17 16:38:55 +01001670 if (isPackageInstalled(packageName, userId)) {
1671 // Notify package of changes via an intent - only sent to explicitly registered receivers.
1672 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
1673 changeIntent.setPackage(packageName);
1674 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
1675 mContext.sendBroadcastAsUser(changeIntent, new UserHandle(userId));
1676 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001677 }
1678
Amith Yamasani655d0e22013-06-12 14:19:10 -07001679 @Override
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001680 public void removeRestrictions() {
Esteban Talavera2a5d6c62015-10-21 10:55:56 +01001681 checkManageUsersPermission("remove restrictions");
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001682 final int userHandle = UserHandle.getCallingUserId();
Amith Yamasani5e486f52013-08-07 11:06:44 -07001683 removeRestrictionsForUser(userHandle, true);
Amith Yamasani350962c2013-08-06 11:18:53 -07001684 }
1685
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001686 private void removeRestrictionsForUser(final int userHandle, boolean unhideApps) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001687 synchronized (mPackagesLock) {
1688 // Remove all user restrictions
1689 setUserRestrictions(new Bundle(), userHandle);
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001690 // Remove any app restrictions
Kenny Guyd21b2182014-07-17 16:38:55 +01001691 cleanAppRestrictions(userHandle);
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001692 }
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001693 if (unhideApps) {
1694 unhideAllInstalledAppsForUser(userHandle);
Amith Yamasani5e486f52013-08-07 11:06:44 -07001695 }
1696 }
1697
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001698 private void unhideAllInstalledAppsForUser(final int userHandle) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001699 mHandler.post(new Runnable() {
1700 @Override
1701 public void run() {
1702 List<ApplicationInfo> apps =
1703 mPm.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES,
1704 userHandle).getList();
1705 final long ident = Binder.clearCallingIdentity();
1706 try {
1707 for (ApplicationInfo appInfo : apps) {
1708 if ((appInfo.flags & ApplicationInfo.FLAG_INSTALLED) != 0
Alex Klyubinb9f8a522015-02-03 11:12:59 -08001709 && (appInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HIDDEN)
1710 != 0) {
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001711 mPm.setApplicationHiddenSettingAsUser(appInfo.packageName, false,
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001712 userHandle);
1713 }
1714 }
1715 } finally {
1716 Binder.restoreCallingIdentity(ident);
1717 }
1718 }
1719 });
1720 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001721 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07001722 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001723 try {
1724 return mContext.getPackageManager().getApplicationInfo(packageName,
1725 PackageManager.GET_UNINSTALLED_PACKAGES).uid;
1726 } catch (NameNotFoundException nnfe) {
1727 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07001728 } finally {
1729 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001730 }
1731 }
1732
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001733 private Bundle readApplicationRestrictionsLocked(String packageName,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001734 int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001735 AtomicFile restrictionsFile =
1736 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
1737 packageToRestrictionsFileName(packageName)));
1738 return readApplicationRestrictionsLocked(restrictionsFile);
1739 }
1740
1741 @VisibleForTesting
1742 static Bundle readApplicationRestrictionsLocked(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001743 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001744 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07001745 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07001746 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07001747 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001748
1749 FileInputStream fis = null;
1750 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001751 fis = restrictionsFile.openRead();
1752 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001753 parser.setInput(fis, StandardCharsets.UTF_8.name());
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001754 XmlUtils.nextElement(parser);
1755 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001756 Slog.e(LOG_TAG, "Unable to read restrictions file "
1757 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001758 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001759 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001760 while (parser.next() != XmlPullParser.END_DOCUMENT) {
1761 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001762 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001763 } catch (IOException|XmlPullParserException e) {
1764 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001765 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001766 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001767 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001768 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001769 }
1770
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001771 private static void readEntry(Bundle restrictions, ArrayList<String> values,
1772 XmlPullParser parser) throws XmlPullParserException, IOException {
1773 int type = parser.getEventType();
1774 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
1775 String key = parser.getAttributeValue(null, ATTR_KEY);
1776 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
1777 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
1778 if (multiple != null) {
1779 values.clear();
1780 int count = Integer.parseInt(multiple);
1781 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1782 if (type == XmlPullParser.START_TAG
1783 && parser.getName().equals(TAG_VALUE)) {
1784 values.add(parser.nextText().trim());
1785 count--;
1786 }
1787 }
1788 String [] valueStrings = new String[values.size()];
1789 values.toArray(valueStrings);
1790 restrictions.putStringArray(key, valueStrings);
1791 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
1792 restrictions.putBundle(key, readBundleEntry(parser, values));
1793 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
1794 final int outerDepth = parser.getDepth();
1795 ArrayList<Bundle> bundleList = new ArrayList<>();
1796 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
1797 Bundle childBundle = readBundleEntry(parser, values);
1798 bundleList.add(childBundle);
1799 }
1800 restrictions.putParcelableArray(key,
1801 bundleList.toArray(new Bundle[bundleList.size()]));
1802 } else {
1803 String value = parser.nextText().trim();
1804 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
1805 restrictions.putBoolean(key, Boolean.parseBoolean(value));
1806 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
1807 restrictions.putInt(key, Integer.parseInt(value));
1808 } else {
1809 restrictions.putString(key, value);
1810 }
1811 }
1812 }
1813 }
1814
1815 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
1816 throws IOException, XmlPullParserException {
1817 Bundle childBundle = new Bundle();
1818 final int outerDepth = parser.getDepth();
1819 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
1820 readEntry(childBundle, values, parser);
1821 }
1822 return childBundle;
1823 }
1824
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001825 private void writeApplicationRestrictionsLocked(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001826 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001827 AtomicFile restrictionsFile = new AtomicFile(
1828 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07001829 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001830 writeApplicationRestrictionsLocked(restrictions, restrictionsFile);
1831 }
1832
1833 @VisibleForTesting
1834 static void writeApplicationRestrictionsLocked(Bundle restrictions,
1835 AtomicFile restrictionsFile) {
1836 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001837 try {
1838 fos = restrictionsFile.startWrite();
1839 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1840
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001841 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001842 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001843 serializer.startDocument(null, true);
1844 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1845
1846 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001847 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001848 serializer.endTag(null, TAG_RESTRICTIONS);
1849
1850 serializer.endDocument();
1851 restrictionsFile.finishWrite(fos);
1852 } catch (Exception e) {
1853 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001854 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
1855 }
1856 }
1857
1858 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
1859 throws IOException {
1860 for (String key : restrictions.keySet()) {
1861 Object value = restrictions.get(key);
1862 serializer.startTag(null, TAG_ENTRY);
1863 serializer.attribute(null, ATTR_KEY, key);
1864
1865 if (value instanceof Boolean) {
1866 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
1867 serializer.text(value.toString());
1868 } else if (value instanceof Integer) {
1869 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
1870 serializer.text(value.toString());
1871 } else if (value == null || value instanceof String) {
1872 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
1873 serializer.text(value != null ? (String) value : "");
1874 } else if (value instanceof Bundle) {
1875 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
1876 writeBundle((Bundle) value, serializer);
1877 } else if (value instanceof Parcelable[]) {
1878 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
1879 Parcelable[] array = (Parcelable[]) value;
1880 for (Parcelable parcelable : array) {
1881 if (!(parcelable instanceof Bundle)) {
1882 throw new IllegalArgumentException("bundle-array can only hold Bundles");
1883 }
1884 serializer.startTag(null, TAG_ENTRY);
1885 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
1886 writeBundle((Bundle) parcelable, serializer);
1887 serializer.endTag(null, TAG_ENTRY);
1888 }
1889 } else {
1890 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
1891 String[] values = (String[]) value;
1892 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
1893 for (String choice : values) {
1894 serializer.startTag(null, TAG_VALUE);
1895 serializer.text(choice != null ? choice : "");
1896 serializer.endTag(null, TAG_VALUE);
1897 }
1898 }
1899 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001900 }
1901 }
1902
1903 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07001904 public int getUserSerialNumber(int userHandle) {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001905 synchronized (mPackagesLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001906 if (!exists(userHandle)) return -1;
Amith Yamasani195263742012-08-21 15:40:12 -07001907 return getUserInfoLocked(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07001908 }
1909 }
1910
1911 @Override
1912 public int getUserHandle(int userSerialNumber) {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001913 synchronized (mPackagesLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001914 for (int userId : mUserIds) {
Kenny Guy945f8832015-02-10 15:17:26 +00001915 UserInfo info = getUserInfoLocked(userId);
1916 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07001917 }
1918 // Not found
1919 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07001920 }
1921 }
1922
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07001923 @Override
1924 public long getUserCreationTime(int userHandle) {
1925 int callingUserId = UserHandle.getCallingUserId();
1926 UserInfo userInfo = null;
1927 synchronized (mPackagesLock) {
1928 if (callingUserId == userHandle) {
1929 userInfo = getUserInfoLocked(userHandle);
1930 } else {
1931 UserInfo parent = getProfileParentLocked(userHandle);
1932 if (parent != null && parent.id == callingUserId) {
1933 userInfo = getUserInfoLocked(userHandle);
1934 }
1935 }
1936 }
1937 if (userInfo == null) {
1938 throw new SecurityException("userHandle can only be the calling user or a managed "
1939 + "profile associated with this user");
1940 }
1941 return userInfo.creationTime;
1942 }
1943
Amith Yamasani0b285492011-04-14 17:35:23 -07001944 /**
1945 * Caches the list of user ids in an array, adjusting the array size when necessary.
1946 */
Amith Yamasani13593602012-03-22 16:16:17 -07001947 private void updateUserIdsLocked() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001948 int num = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -07001949 for (int i = 0; i < mUsers.size(); i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001950 if (!mUsers.valueAt(i).partial) {
1951 num++;
1952 }
1953 }
Amith Yamasani16389312012-10-17 21:20:14 -07001954 final int[] newUsers = new int[num];
1955 int n = 0;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001956 for (int i = 0; i < mUsers.size(); i++) {
1957 if (!mUsers.valueAt(i).partial) {
Amith Yamasani16389312012-10-17 21:20:14 -07001958 newUsers[n++] = mUsers.keyAt(i);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001959 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001960 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001961 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07001962 }
1963
1964 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001965 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasani920ace02012-09-20 22:15:37 -07001966 * @param userId the user that was just foregrounded
1967 */
Amith Yamasani06bf8242015-05-08 16:36:21 -07001968 public void onUserForeground(int userId) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001969 synchronized (mPackagesLock) {
1970 UserInfo user = mUsers.get(userId);
1971 long now = System.currentTimeMillis();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001972 if (user == null || user.partial) {
1973 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
1974 return;
1975 }
1976 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001977 user.lastLoggedInTime = now;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001978 scheduleWriteUserLocked(user);
Amith Yamasani920ace02012-09-20 22:15:37 -07001979 }
1980 }
1981 }
1982
1983 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07001984 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani742a6712011-05-04 14:49:28 -07001985 * TODO: May not be a good idea to recycle ids, in case it results in confusion
1986 * for data and battery stats collection, or unexpected cross-talk.
Amith Yamasani0b285492011-04-14 17:35:23 -07001987 * @return
1988 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001989 private int getNextAvailableIdLocked() {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001990 synchronized (mPackagesLock) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001991 int i = MIN_USER_ID;
Amith Yamasani195263742012-08-21 15:40:12 -07001992 while (i < Integer.MAX_VALUE) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001993 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
Amith Yamasani195263742012-08-21 15:40:12 -07001994 break;
1995 }
1996 i++;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001997 }
Amith Yamasani195263742012-08-21 15:40:12 -07001998 return i;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001999 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002000 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002001
Amith Yamasanifc95e702013-09-26 13:20:17 -07002002 private String packageToRestrictionsFileName(String packageName) {
2003 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
2004 }
2005
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002006 /**
2007 * Create new {@code /data/user/[id]} directory and sets default
2008 * permissions.
2009 */
Jeff Sharkey3bb8c852015-07-06 16:44:23 -07002010 public static void prepareUserDirectory(Context context, String volumeUuid, int userId) {
2011 final StorageManager storage = context.getSystemService(StorageManager.class);
2012 final File userDir = Environment.getDataUserDirectory(volumeUuid, userId);
2013 storage.createNewUserDir(userId, userDir);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002014 }
2015
2016 /**
2017 * Enforce that serial number stored in user directory inode matches the
2018 * given expected value. Gracefully sets the serial number if currently
2019 * undefined.
2020 *
2021 * @throws IOException when problem extracting serial number, or serial
2022 * number is mismatched.
2023 */
2024 public static void enforceSerialNumber(File file, int serialNumber) throws IOException {
2025 final int foundSerial = getSerialNumber(file);
2026 Slog.v(LOG_TAG, "Found " + file + " with serial number " + foundSerial);
2027
2028 if (foundSerial == -1) {
2029 Slog.d(LOG_TAG, "Serial number missing on " + file + "; assuming current is valid");
2030 try {
2031 setSerialNumber(file, serialNumber);
2032 } catch (IOException e) {
2033 Slog.w(LOG_TAG, "Failed to set serial number on " + file, e);
2034 }
2035
2036 } else if (foundSerial != serialNumber) {
2037 throw new IOException("Found serial number " + foundSerial
2038 + " doesn't match expected " + serialNumber);
2039 }
2040 }
2041
2042 /**
2043 * Set serial number stored in user directory inode.
2044 *
2045 * @throws IOException if serial number was already set
2046 */
2047 private static void setSerialNumber(File file, int serialNumber)
2048 throws IOException {
2049 try {
2050 final byte[] buf = Integer.toString(serialNumber).getBytes(StandardCharsets.UTF_8);
2051 Os.setxattr(file.getAbsolutePath(), XATTR_SERIAL, buf, OsConstants.XATTR_CREATE);
2052 } catch (ErrnoException e) {
2053 throw e.rethrowAsIOException();
2054 }
2055 }
2056
2057 /**
2058 * Return serial number stored in user directory inode.
2059 *
2060 * @return parsed serial number, or -1 if not set
2061 */
2062 private static int getSerialNumber(File file) throws IOException {
2063 try {
2064 final byte[] buf = new byte[256];
2065 final int len = Os.getxattr(file.getAbsolutePath(), XATTR_SERIAL, buf);
2066 final String serial = new String(buf, 0, len);
2067 try {
2068 return Integer.parseInt(serial);
2069 } catch (NumberFormatException e) {
2070 throw new IOException("Bad serial number: " + serial);
2071 }
2072 } catch (ErrnoException e) {
2073 if (e.errno == OsConstants.ENODATA) {
2074 return -1;
2075 } else {
2076 throw e.rethrowAsIOException();
2077 }
2078 }
2079 }
2080
Amith Yamasani920ace02012-09-20 22:15:37 -07002081 @Override
2082 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2083 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2084 != PackageManager.PERMISSION_GRANTED) {
2085 pw.println("Permission Denial: can't dump UserManager from from pid="
2086 + Binder.getCallingPid()
2087 + ", uid=" + Binder.getCallingUid()
2088 + " without permission "
2089 + android.Manifest.permission.DUMP);
2090 return;
2091 }
2092
2093 long now = System.currentTimeMillis();
2094 StringBuilder sb = new StringBuilder();
2095 synchronized (mPackagesLock) {
2096 pw.println("Users:");
2097 for (int i = 0; i < mUsers.size(); i++) {
2098 UserInfo user = mUsers.valueAt(i);
2099 if (user == null) continue;
Amith Yamasani634cf312012-10-04 17:34:21 -07002100 pw.print(" "); pw.print(user); pw.print(" serialNo="); pw.print(user.serialNumber);
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002101 if (mRemovingUserIds.get(mUsers.keyAt(i))) pw.print(" <removing> ");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002102 if (user.partial) pw.print(" <partial>");
2103 pw.println();
Amith Yamasani920ace02012-09-20 22:15:37 -07002104 pw.print(" Created: ");
2105 if (user.creationTime == 0) {
2106 pw.println("<unknown>");
2107 } else {
2108 sb.setLength(0);
2109 TimeUtils.formatDuration(now - user.creationTime, sb);
2110 sb.append(" ago");
2111 pw.println(sb);
2112 }
2113 pw.print(" Last logged in: ");
2114 if (user.lastLoggedInTime == 0) {
2115 pw.println("<unknown>");
2116 } else {
2117 sb.setLength(0);
2118 TimeUtils.formatDuration(now - user.lastLoggedInTime, sb);
2119 sb.append(" ago");
2120 pw.println(sb);
2121 }
2122 }
2123 }
2124 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002125
2126 final class MainHandler extends Handler {
2127
2128 @Override
2129 public void handleMessage(Message msg) {
2130 switch (msg.what) {
2131 case WRITE_USER_MSG:
2132 removeMessages(WRITE_USER_MSG, msg.obj);
2133 synchronized (mPackagesLock) {
2134 int userId = ((UserInfo) msg.obj).id;
2135 UserInfo userInfo = mUsers.get(userId);
2136 if (userInfo != null) {
2137 writeUserLocked(userInfo);
2138 }
2139 }
2140 }
2141 }
2142 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07002143
2144 /**
2145 * @param userId
2146 * @return whether the user has been initialized yet
2147 */
2148 boolean isInitialized(int userId) {
2149 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
2150 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002151}