blob: 341410d3522d8c2eb7c6ef0af0b3156446c03328 [file] [log] [blame]
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -070019import android.accounts.Account;
Xiaohui Chen594f2082015-08-18 11:04:20 -070020import android.annotation.NonNull;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070021import android.app.Activity;
Amith Yamasani2a003292012-08-14 18:25:45 -070022import android.app.ActivityManager;
Amith Yamasani515d4062015-09-28 11:30:06 -070023import android.app.ActivityManagerInternal;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070024import android.app.ActivityManagerNative;
25import android.app.IStopUserCallback;
Xiaohui Chen203243a2015-07-16 11:55:47 -070026import android.app.admin.DevicePolicyManager;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070027import android.content.BroadcastReceiver;
Amith Yamasani258848d2012-08-10 17:06:33 -070028import android.content.Context;
29import android.content.Intent;
Amith Yamasani1a7472e2013-07-02 11:17:30 -070030import android.content.pm.ApplicationInfo;
Amith Yamasani0b285492011-04-14 17:35:23 -070031import android.content.pm.PackageManager;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -080032import android.content.pm.PackageManager.NameNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070033import android.content.pm.UserInfo;
Amith Yamasanie928d7d2012-09-17 21:46:51 -070034import android.graphics.Bitmap;
Amith Yamasani258848d2012-08-10 17:06:33 -070035import android.os.Binder;
Amith Yamasanie4cf7342012-12-17 11:12:09 -080036import android.os.Bundle;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070037import android.os.Environment;
38import android.os.FileUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080039import android.os.Handler;
Amith Yamasani258848d2012-08-10 17:06:33 -070040import android.os.IUserManager;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -080041import android.os.Message;
Adrian Roos1bdff912015-02-17 15:51:35 +010042import android.os.ParcelFileDescriptor;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070043import android.os.Parcelable;
Amith Yamasani258848d2012-08-10 17:06:33 -070044import android.os.Process;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070045import android.os.RemoteException;
Jason Monk62062992014-05-06 09:55:28 -040046import android.os.ServiceManager;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070047import android.os.UserHandle;
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070048import android.os.UserManager;
Paul Crowley85e4e812015-05-19 12:42:00 +010049import android.os.storage.StorageManager;
Jeff Sharkey6dce4962015-07-03 18:08:41 -070050import android.os.storage.VolumeInfo;
51import android.system.ErrnoException;
52import android.system.Os;
53import android.system.OsConstants;
Amith Yamasani2a003292012-08-14 18:25:45 -070054import android.util.AtomicFile;
Amith Yamasani655d0e22013-06-12 14:19:10 -070055import android.util.Log;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070056import android.util.Slog;
57import android.util.SparseArray;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080058import android.util.SparseBooleanArray;
Amith Yamasani920ace02012-09-20 22:15:37 -070059import android.util.TimeUtils;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070060import android.util.Xml;
61
Fyodor Kupolov262f9952015-03-23 18:55:11 -070062import com.android.internal.annotations.VisibleForTesting;
Jason Monk62062992014-05-06 09:55:28 -040063import com.android.internal.app.IAppOpsService;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080064import com.android.internal.util.FastXmlSerializer;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070065import com.android.internal.util.XmlUtils;
Amith Yamasani515d4062015-09-28 11:30:06 -070066import com.android.server.LocalServices;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080067
68import org.xmlpull.v1.XmlPullParser;
69import org.xmlpull.v1.XmlPullParserException;
70import org.xmlpull.v1.XmlSerializer;
71
Amith Yamasani4b2e9342011-03-31 12:38:53 -070072import java.io.BufferedOutputStream;
73import java.io.File;
Amith Yamasani920ace02012-09-20 22:15:37 -070074import java.io.FileDescriptor;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070075import java.io.FileInputStream;
Amith Yamasanib8151ec2012-04-18 18:02:48 -070076import java.io.FileNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070077import java.io.FileOutputStream;
78import java.io.IOException;
Amith Yamasani920ace02012-09-20 22:15:37 -070079import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +010080import java.nio.charset.StandardCharsets;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070081import java.util.ArrayList;
82import java.util.List;
83
Fyodor Kupolov262f9952015-03-23 18:55:11 -070084import libcore.io.IoUtils;
85
Amith Yamasani258848d2012-08-10 17:06:33 -070086public class UserManagerService extends IUserManager.Stub {
Amith Yamasanib8151ec2012-04-18 18:02:48 -070087
Amith Yamasani2a003292012-08-14 18:25:45 -070088 private static final String LOG_TAG = "UserManagerService";
Amith Yamasanib8151ec2012-04-18 18:02:48 -070089
Amith Yamasani16389312012-10-17 21:20:14 -070090 private static final boolean DBG = false;
91
Amith Yamasani4b2e9342011-03-31 12:38:53 -070092 private static final String TAG_NAME = "name";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070093 private static final String ATTR_FLAGS = "flags";
Amith Yamasanib8151ec2012-04-18 18:02:48 -070094 private static final String ATTR_ICON_PATH = "icon";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070095 private static final String ATTR_ID = "id";
Amith Yamasani920ace02012-09-20 22:15:37 -070096 private static final String ATTR_CREATION_TIME = "created";
97 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
Amith Yamasani2a003292012-08-14 18:25:45 -070098 private static final String ATTR_SERIAL_NO = "serialNumber";
99 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700100 private static final String ATTR_PARTIAL = "partial";
Adam Lesinskieddeb492014-09-08 17:50:03 -0700101 private static final String ATTR_GUEST_TO_REMOVE = "guestToRemove";
Amith Yamasani6f34b412012-10-22 18:19:27 -0700102 private static final String ATTR_USER_VERSION = "version";
Kenny Guy2a764942014-04-02 13:29:20 +0100103 private static final String ATTR_PROFILE_GROUP_ID = "profileGroupId";
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700104 private static final String ATTR_RESTRICTED_PROFILE_PARENT_ID = "restrictedProfileParentId";
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530105 private static final String TAG_GUEST_RESTRICTIONS = "guestRestrictions";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700106 private static final String TAG_USERS = "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700107 private static final String TAG_USER = "user";
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800108 private static final String TAG_RESTRICTIONS = "restrictions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800109 private static final String TAG_ENTRY = "entry";
110 private static final String TAG_VALUE = "value";
111 private static final String ATTR_KEY = "key";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700112 private static final String ATTR_VALUE_TYPE = "type";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800113 private static final String ATTR_MULTIPLE = "m";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700114
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700115 private static final String ATTR_TYPE_STRING_ARRAY = "sa";
116 private static final String ATTR_TYPE_STRING = "s";
117 private static final String ATTR_TYPE_BOOLEAN = "b";
Amith Yamasani5b5aa402014-06-01 20:10:14 -0700118 private static final String ATTR_TYPE_INTEGER = "i";
Fyodor Kupolov262f9952015-03-23 18:55:11 -0700119 private static final String ATTR_TYPE_BUNDLE = "B";
120 private static final String ATTR_TYPE_BUNDLE_ARRAY = "BA";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700121
Amith Yamasani0b285492011-04-14 17:35:23 -0700122 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700123 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700124 private static final String USER_PHOTO_FILENAME = "photo.png";
Adrian Roos1bdff912015-02-17 15:51:35 +0100125 private static final String USER_PHOTO_FILENAME_TMP = USER_PHOTO_FILENAME + ".tmp";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700126
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800127 private static final String RESTRICTIONS_FILE_PREFIX = "res_";
Amith Yamasanifc95e702013-09-26 13:20:17 -0700128 private static final String XML_SUFFIX = ".xml";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800129
Amith Yamasani634cf312012-10-04 17:34:21 -0700130 private static final int MIN_USER_ID = 10;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700131 // We need to keep process uid within Integer.MAX_VALUE.
132 private static final int MAX_USER_ID = Integer.MAX_VALUE / UserHandle.PER_USER_RANGE;
Amith Yamasani634cf312012-10-04 17:34:21 -0700133
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 Kupolov75d0ea82014-12-15 16:21:07 -0800147 static final int WRITE_USER_MSG = 1;
148 static final int WRITE_USER_DELAY = 2*1000; // 2 seconds
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530149
Jeff Sharkey6dce4962015-07-03 18:08:41 -0700150 private static final String XATTR_SERIAL = "user.serial";
151
Dianne Hackborn4428e172012-08-24 17:43:05 -0700152 private final Context mContext;
153 private final PackageManagerService mPm;
154 private final Object mInstallLock;
155 private final Object mPackagesLock;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700156
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800157 private final Handler mHandler;
158
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700159 private final File mUsersDir;
160 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700161
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800162 private final SparseArray<UserInfo> mUsers = new SparseArray<UserInfo>();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800163 private final SparseArray<Bundle> mUserRestrictions = new SparseArray<Bundle>();
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530164 private final Bundle mGuestRestrictions = new Bundle();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800165
166 /**
167 * Set of user IDs being actively removed. Removed IDs linger in this set
168 * for several seconds to work around a VFS caching issue.
169 */
170 // @GuardedBy("mPackagesLock")
171 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700172
Amith Yamasani0b285492011-04-14 17:35:23 -0700173 private int[] mUserIds;
Amith Yamasani2a003292012-08-14 18:25:45 -0700174 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700175 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700176
Jason Monk62062992014-05-06 09:55:28 -0400177 private IAppOpsService mAppOpsService;
178
Amith Yamasani258848d2012-08-10 17:06:33 -0700179 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700180
Dianne Hackborn4428e172012-08-24 17:43:05 -0700181 public static UserManagerService getInstance() {
182 synchronized (UserManagerService.class) {
183 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700184 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700185 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700186
187 /**
188 * Available for testing purposes.
189 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700190 UserManagerService(File dataDir, File baseUserPath) {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700191 this(null, null, new Object(), new Object(), dataDir, baseUserPath);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700192 }
193
Dianne Hackborn4428e172012-08-24 17:43:05 -0700194 /**
195 * Called by package manager to create the service. This is closely
196 * associated with the package manager, and the given lock is the
197 * package manager's own lock.
198 */
199 UserManagerService(Context context, PackageManagerService pm,
200 Object installLock, Object packagesLock) {
201 this(context, pm, installLock, packagesLock,
202 Environment.getDataDirectory(),
203 new File(Environment.getDataDirectory(), "user"));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700204 }
205
Dianne Hackborn4428e172012-08-24 17:43:05 -0700206 /**
207 * Available for testing purposes.
208 */
209 private UserManagerService(Context context, PackageManagerService pm,
210 Object installLock, Object packagesLock,
211 File dataDir, File baseUserPath) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700212 mContext = context;
213 mPm = pm;
214 mInstallLock = installLock;
215 mPackagesLock = packagesLock;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800216 mHandler = new MainHandler();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700217 synchronized (mInstallLock) {
218 synchronized (mPackagesLock) {
219 mUsersDir = new File(dataDir, USER_INFO_DIR);
220 mUsersDir.mkdirs();
221 // Make zeroth user directory, for services to migrate their files to that location
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700222 File userZeroDir = new File(mUsersDir, String.valueOf(UserHandle.USER_SYSTEM));
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700223 userZeroDir.mkdirs();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700224 FileUtils.setPermissions(mUsersDir.toString(),
225 FileUtils.S_IRWXU|FileUtils.S_IRWXG
226 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
227 -1, -1);
228 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
Amith Yamasanida0b1682014-11-21 12:58:17 -0800229 initDefaultGuestRestrictions();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700230 readUserListLocked();
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700231 sInstance = this;
232 }
233 }
234 }
235
236 void systemReady() {
237 synchronized (mInstallLock) {
238 synchronized (mPackagesLock) {
Amith Yamasani756901d2012-10-12 12:30:07 -0700239 // Prune out any partially created/partially removed users.
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700240 ArrayList<UserInfo> partials = new ArrayList<UserInfo>();
Amith Yamasani515d4062015-09-28 11:30:06 -0700241 final int userSize = mUsers.size();
242 for (int i = 0; i < userSize; i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700243 UserInfo ui = mUsers.valueAt(i);
Adam Lesinskieddeb492014-09-08 17:50:03 -0700244 if ((ui.partial || ui.guestToRemove) && i != 0) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700245 partials.add(ui);
246 }
247 }
Amith Yamasani515d4062015-09-28 11:30:06 -0700248 final int partialsSize = partials.size();
249 for (int i = 0; i < partialsSize; i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700250 UserInfo ui = partials.get(i);
Amith Yamasania7892482015-08-07 11:09:05 -0700251 Slog.w(LOG_TAG, "Removing partially created user " + ui.id
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700252 + " (name=" + ui.name + ")");
253 removeUserStateLocked(ui.id);
254 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700255 }
Dianne Hackborn4428e172012-08-24 17:43:05 -0700256 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700257 onUserForeground(UserHandle.USER_SYSTEM);
Jason Monk62062992014-05-06 09:55:28 -0400258 mAppOpsService = IAppOpsService.Stub.asInterface(
259 ServiceManager.getService(Context.APP_OPS_SERVICE));
260 for (int i = 0; i < mUserIds.length; ++i) {
261 try {
262 mAppOpsService.setUserRestrictions(mUserRestrictions.get(mUserIds[i]), mUserIds[i]);
263 } catch (RemoteException e) {
264 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
265 }
266 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700267 }
268
269 @Override
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700270 public UserInfo getPrimaryUser() {
271 checkManageUsersPermission("query users");
272 synchronized (mPackagesLock) {
Amith Yamasani515d4062015-09-28 11:30:06 -0700273 final int userSize = mUsers.size();
274 for (int i = 0; i < userSize; i++) {
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700275 UserInfo ui = mUsers.valueAt(i);
276 if (ui.isPrimary()) {
277 return ui;
278 }
279 }
280 }
281 return null;
282 }
283
284 @Override
Xiaohui Chen594f2082015-08-18 11:04:20 -0700285 public @NonNull List<UserInfo> getUsers(boolean excludeDying) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700286 checkManageUsersPermission("query users");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700287 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700288 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasani515d4062015-09-28 11:30:06 -0700289 final int userSize = mUsers.size();
290 for (int i = 0; i < userSize; 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 Yamasani515d4062015-09-28 11:30:06 -0700326 final int userSize = mUsers.size();
327 for (int i = 0; i < userSize; i++) {
Amith Yamasanibe465322014-04-24 13:45:17 -0700328 UserInfo profile = mUsers.valueAt(i);
329 if (!isProfileOf(user, profile)) {
330 continue;
331 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100332 if (enabledOnly && !profile.isEnabled()) {
333 continue;
Amith Yamasanibe465322014-04-24 13:45:17 -0700334 }
Amith Yamasani70fcf0c2014-07-11 08:40:19 -0700335 if (mRemovingUserIds.get(profile.id)) {
336 continue;
337 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700338 users.add(profile);
339 }
340 return users;
341 }
342
Jessica Hummelbe81c802014-04-22 15:49:22 +0100343 @Override
Andres Moralesc5548c02015-08-05 10:23:12 -0700344 public int getCredentialOwnerProfile(int userHandle) {
345 checkManageUsersPermission("get the credential owner");
346 if (CONFIG_PROFILES_SHARE_CREDENTIAL) {
347 synchronized (mPackagesLock) {
348 UserInfo profileParent = getProfileParentLocked(userHandle);
349 if (profileParent != null) {
350 return profileParent.id;
351 }
352 }
353 }
354
355 return userHandle;
356 }
357
358 @Override
Jessica Hummelbe81c802014-04-22 15:49:22 +0100359 public UserInfo getProfileParent(int userHandle) {
360 checkManageUsersPermission("get the profile parent");
361 synchronized (mPackagesLock) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700362 return getProfileParentLocked(userHandle);
363 }
364 }
365
366 private UserInfo getProfileParentLocked(int userHandle) {
367 UserInfo profile = getUserInfoLocked(userHandle);
368 if (profile == null) {
369 return null;
370 }
371 int parentUserId = profile.profileGroupId;
372 if (parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
373 return null;
374 } else {
375 return getUserInfoLocked(parentUserId);
Jessica Hummelbe81c802014-04-22 15:49:22 +0100376 }
377 }
378
Kenny Guy2a764942014-04-02 13:29:20 +0100379 private boolean isProfileOf(UserInfo user, UserInfo profile) {
380 return user.id == profile.id ||
381 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
382 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000383 }
384
385 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100386 public void setUserEnabled(int userId) {
387 checkManageUsersPermission("enable user");
388 synchronized (mPackagesLock) {
389 UserInfo info = getUserInfoLocked(userId);
390 if (info != null && !info.isEnabled()) {
391 info.flags ^= UserInfo.FLAG_DISABLED;
392 writeUserLocked(info);
393 }
394 }
395 }
396
397 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700398 public UserInfo getUserInfo(int userId) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700399 checkManageUsersPermission("query user");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700400 synchronized (mPackagesLock) {
Amith Yamasani195263742012-08-21 15:40:12 -0700401 return getUserInfoLocked(userId);
Amith Yamasani13593602012-03-22 16:16:17 -0700402 }
403 }
404
Amith Yamasani71e6c692013-03-24 17:39:28 -0700405 @Override
406 public boolean isRestricted() {
407 synchronized (mPackagesLock) {
408 return getUserInfoLocked(UserHandle.getCallingUserId()).isRestricted();
409 }
410 }
411
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700412 @Override
413 public boolean canHaveRestrictedProfile(int userId) {
414 checkManageUsersPermission("canHaveRestrictedProfile");
415 synchronized (mPackagesLock) {
416 final UserInfo userInfo = getUserInfoLocked(userId);
417 if (userInfo == null || !userInfo.canHaveProfile()) {
418 return false;
419 }
420 if (!userInfo.isAdmin()) {
421 return false;
422 }
423 }
424 DevicePolicyManager dpm = (DevicePolicyManager) mContext.getSystemService(
425 Context.DEVICE_POLICY_SERVICE);
426 // restricted profile can be created if there is no DO set and the admin user has no PO
427 return dpm.getDeviceOwner() == null && dpm.getProfileOwnerAsUser(userId) == null;
428 }
429
Amith Yamasani195263742012-08-21 15:40:12 -0700430 /*
431 * Should be locked on mUsers before calling this.
432 */
433 private UserInfo getUserInfoLocked(int userId) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700434 UserInfo ui = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -0700435 // If it is partial and not in the process of being removed, return as unknown user.
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800436 if (ui != null && ui.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700437 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
438 return null;
439 }
440 return ui;
Amith Yamasani195263742012-08-21 15:40:12 -0700441 }
442
Amith Yamasani236b2b52015-08-18 14:32:14 -0700443 /** Called by PackageManagerService */
Amith Yamasani13593602012-03-22 16:16:17 -0700444 public boolean exists(int userId) {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700445 synchronized (mPackagesLock) {
Amith Yamasani236b2b52015-08-18 14:32:14 -0700446 return mUsers.get(userId) != null;
Amith Yamasani13593602012-03-22 16:16:17 -0700447 }
448 }
449
Amith Yamasani258848d2012-08-10 17:06:33 -0700450 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700451 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700452 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700453 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700454 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700455 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700456 if (info == null || info.partial) {
457 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
458 return;
459 }
Amith Yamasani13593602012-03-22 16:16:17 -0700460 if (name != null && !name.equals(info.name)) {
461 info.name = name;
462 writeUserLocked(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700463 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -0700464 }
465 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700466 if (changed) {
467 sendUserInfoChangedBroadcast(userId);
468 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700469 }
470
Amith Yamasani258848d2012-08-10 17:06:33 -0700471 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700472 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700473 checkManageUsersPermission("update users");
Jason Monk9a944532014-07-08 09:31:21 -0400474 long ident = Binder.clearCallingIdentity();
475 try {
476 synchronized (mPackagesLock) {
477 UserInfo info = mUsers.get(userId);
478 if (info == null || info.partial) {
479 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
480 return;
481 }
482 writeBitmapLocked(info, bitmap);
483 writeUserLocked(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700484 }
Jason Monk9a944532014-07-08 09:31:21 -0400485 sendUserInfoChangedBroadcast(userId);
486 } finally {
487 Binder.restoreCallingIdentity(ident);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700488 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700489 }
490
491 private void sendUserInfoChangedBroadcast(int userId) {
492 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
493 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
494 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -0700495 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700496 }
497
Amith Yamasani258848d2012-08-10 17:06:33 -0700498 @Override
Adrian Roos1bdff912015-02-17 15:51:35 +0100499 public ParcelFileDescriptor getUserIcon(int userId) {
500 String iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700501 synchronized (mPackagesLock) {
502 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700503 if (info == null || info.partial) {
504 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + userId);
505 return null;
506 }
Nicolas Prevot88cc3462014-05-14 14:51:48 +0100507 int callingGroupId = mUsers.get(UserHandle.getCallingUserId()).profileGroupId;
508 if (callingGroupId == UserInfo.NO_PROFILE_GROUP_ID
509 || callingGroupId != info.profileGroupId) {
510 checkManageUsersPermission("get the icon of a user who is not related");
511 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700512 if (info.iconPath == null) {
513 return null;
514 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100515 iconPath = info.iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700516 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100517
518 try {
519 return ParcelFileDescriptor.open(
520 new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
521 } catch (FileNotFoundException e) {
522 Log.e(LOG_TAG, "Couldn't find icon file", e);
523 }
524 return null;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700525 }
526
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700527 public void makeInitialized(int userId) {
528 checkManageUsersPermission("makeInitialized");
529 synchronized (mPackagesLock) {
530 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700531 if (info == null || info.partial) {
532 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
533 }
534 if ((info.flags&UserInfo.FLAG_INITIALIZED) == 0) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700535 info.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800536 scheduleWriteUserLocked(info);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700537 }
538 }
539 }
540
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700541 /**
542 * If default guest restrictions haven't been initialized yet, add the basic
543 * restrictions.
544 */
545 private void initDefaultGuestRestrictions() {
546 if (mGuestRestrictions.isEmpty()) {
547 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
Amith Yamasanida0b1682014-11-21 12:58:17 -0800548 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700549 }
550 }
551
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800552 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530553 public Bundle getDefaultGuestRestrictions() {
554 checkManageUsersPermission("getDefaultGuestRestrictions");
555 synchronized (mPackagesLock) {
556 return new Bundle(mGuestRestrictions);
557 }
558 }
559
560 @Override
561 public void setDefaultGuestRestrictions(Bundle restrictions) {
562 checkManageUsersPermission("setDefaultGuestRestrictions");
563 synchronized (mPackagesLock) {
564 mGuestRestrictions.clear();
565 mGuestRestrictions.putAll(restrictions);
566 writeUserListLocked();
567 }
568 }
569
570 @Override
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700571 public boolean hasUserRestriction(String restrictionKey, int userId) {
572 synchronized (mPackagesLock) {
573 Bundle restrictions = mUserRestrictions.get(userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700574 return restrictions != null && restrictions.getBoolean(restrictionKey);
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700575 }
576 }
577
578 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800579 public Bundle getUserRestrictions(int userId) {
580 // checkManageUsersPermission("getUserRestrictions");
581
582 synchronized (mPackagesLock) {
583 Bundle restrictions = mUserRestrictions.get(userId);
Amith Yamasanibe465322014-04-24 13:45:17 -0700584 return restrictions != null ? new Bundle(restrictions) : new Bundle();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800585 }
586 }
587
588 @Override
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700589 public void setUserRestriction(String key, boolean value, int userId) {
Fyodor Kupolovd4b26042015-07-27 14:30:59 -0700590 checkManageUsersPermission("setUserRestriction");
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700591 synchronized (mPackagesLock) {
Makoto Onukia4f11972015-10-01 13:19:58 -0700592 if (!UserRestrictionsUtils.SYSTEM_CONTROLLED_USER_RESTRICTIONS.contains(key)) {
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700593 Bundle restrictions = getUserRestrictions(userId);
594 restrictions.putBoolean(key, value);
595 setUserRestrictionsInternalLocked(restrictions, userId);
596 }
597 }
598 }
599
600 @Override
601 public void setSystemControlledUserRestriction(String key, boolean value, int userId) {
602 checkSystemOrRoot("setSystemControlledUserRestriction");
603 synchronized (mPackagesLock) {
604 Bundle restrictions = getUserRestrictions(userId);
605 restrictions.putBoolean(key, value);
606 setUserRestrictionsInternalLocked(restrictions, userId);
607 }
608 }
609
610 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800611 public void setUserRestrictions(Bundle restrictions, int userId) {
Amith Yamasanibe465322014-04-24 13:45:17 -0700612 checkManageUsersPermission("setUserRestrictions");
Amith Yamasani0343ec32013-07-22 14:52:06 -0700613 if (restrictions == null) return;
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800614
615 synchronized (mPackagesLock) {
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700616 final Bundle oldUserRestrictions = mUserRestrictions.get(userId);
617 // Restore the original state of system controlled restrictions from oldUserRestrictions
Makoto Onukia4f11972015-10-01 13:19:58 -0700618 for (String key : UserRestrictionsUtils.SYSTEM_CONTROLLED_USER_RESTRICTIONS) {
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700619 restrictions.remove(key);
620 if (oldUserRestrictions.containsKey(key)) {
621 restrictions.putBoolean(key, oldUserRestrictions.getBoolean(key));
622 }
Jason Monk62062992014-05-06 09:55:28 -0400623 }
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700624 setUserRestrictionsInternalLocked(restrictions, userId);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800625 }
626 }
627
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700628 private void setUserRestrictionsInternalLocked(Bundle restrictions, int userId) {
629 final Bundle userRestrictions = mUserRestrictions.get(userId);
630 userRestrictions.clear();
631 userRestrictions.putAll(restrictions);
632 long token = Binder.clearCallingIdentity();
633 try {
634 mAppOpsService.setUserRestrictions(userRestrictions, userId);
635 } catch (RemoteException e) {
636 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
637 } finally {
638 Binder.restoreCallingIdentity(token);
639 }
640 scheduleWriteUserLocked(mUsers.get(userId));
641 }
642
Amith Yamasani258848d2012-08-10 17:06:33 -0700643 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700644 * Check if we've hit the limit of how many users can be created.
645 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700646 private boolean isUserLimitReachedLocked() {
Nicolas Prevot12678a92015-05-13 12:15:03 -0700647 return getAliveUsersExcludingGuestsCountLocked() >= UserManager.getMaxSupportedUsers();
648 }
649
650 @Override
Nicolas Prevotb8186812015-08-06 15:00:03 +0100651 public boolean canAddMoreManagedProfiles(int userId) {
Nicolas Prevot12678a92015-05-13 12:15:03 -0700652 checkManageUsersPermission("check if more managed profiles can be added.");
653 if (ActivityManager.isLowRamDeviceStatic()) {
654 return false;
655 }
Fyodor Kupolovb6157992015-06-05 15:32:28 -0700656 if (!mContext.getPackageManager().hasSystemFeature(
657 PackageManager.FEATURE_MANAGED_USERS)) {
658 return false;
659 }
Nicolas Prevotb8186812015-08-06 15:00:03 +0100660 // Limit number of managed profiles that can be created
661 int managedProfilesCount = getProfiles(userId, true).size() - 1;
662 if (managedProfilesCount >= MAX_MANAGED_PROFILES) {
663 return false;
664 }
Nicolas Prevot12678a92015-05-13 12:15:03 -0700665 synchronized(mPackagesLock) {
Nicolas Prevotb8186812015-08-06 15:00:03 +0100666 UserInfo userInfo = getUserInfoLocked(userId);
667 if (!userInfo.canHaveProfile()) {
Nicolas Prevot12678a92015-05-13 12:15:03 -0700668 return false;
669 }
670 int usersCount = getAliveUsersExcludingGuestsCountLocked();
671 // We allow creating a managed profile in the special case where there is only one user.
672 return usersCount == 1 || usersCount < UserManager.getMaxSupportedUsers();
673 }
674 }
675
676 private int getAliveUsersExcludingGuestsCountLocked() {
Amith Yamasanif584f012014-05-19 17:57:25 -0700677 int aliveUserCount = 0;
678 final int totalUserCount = mUsers.size();
679 // Skip over users being removed
680 for (int i = 0; i < totalUserCount; i++) {
681 UserInfo user = mUsers.valueAt(i);
Amith Yamasani95ab7842014-08-11 17:09:26 -0700682 if (!mRemovingUserIds.get(user.id)
Amith Yamasani1df14732014-08-29 21:37:27 -0700683 && !user.isGuest() && !user.partial) {
Amith Yamasanif584f012014-05-19 17:57:25 -0700684 aliveUserCount++;
685 }
686 }
Nicolas Prevot12678a92015-05-13 12:15:03 -0700687 return aliveUserCount;
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700688 }
689
690 /**
Amith Yamasani195263742012-08-21 15:40:12 -0700691 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -0700692 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -0700693 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -0700694 *
695 * @param message used as message if SecurityException is thrown
696 * @throws SecurityException if the caller is not system or root
697 */
Amith Yamasanibe465322014-04-24 13:45:17 -0700698 private static final void checkManageUsersPermission(String message) {
Amith Yamasani258848d2012-08-10 17:06:33 -0700699 final int uid = Binder.getCallingUid();
Amith Yamasanibe465322014-04-24 13:45:17 -0700700 if (uid != Process.SYSTEM_UID && uid != 0
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400701 && ActivityManager.checkComponentPermission(
702 android.Manifest.permission.MANAGE_USERS,
Amith Yamasanibe465322014-04-24 13:45:17 -0700703 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
704 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
705 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400706 }
707
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700708 private static void checkSystemOrRoot(String message) {
709 final int uid = Binder.getCallingUid();
710 if (uid != Process.SYSTEM_UID && uid != 0) {
711 throw new SecurityException("Only system may call: " + message);
712 }
713 }
714
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700715 private void writeBitmapLocked(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700716 try {
717 File dir = new File(mUsersDir, Integer.toString(info.id));
718 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +0100719 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700720 if (!dir.exists()) {
721 dir.mkdir();
722 FileUtils.setPermissions(
723 dir.getPath(),
724 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
725 -1, -1);
726 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700727 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +0100728 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
729 && tmp.renameTo(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -0700730 info.iconPath = file.getAbsolutePath();
731 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700732 try {
733 os.close();
734 } catch (IOException ioe) {
735 // What the ... !
736 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100737 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700738 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700739 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700740 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700741 }
742
Amith Yamasani0b285492011-04-14 17:35:23 -0700743 /**
744 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
745 * cache it elsewhere.
746 * @return the array of user ids.
747 */
Dianne Hackborn1676c852012-09-10 14:52:30 -0700748 public int[] getUserIds() {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700749 synchronized (mPackagesLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700750 return mUserIds;
751 }
Amith Yamasani0b285492011-04-14 17:35:23 -0700752 }
753
Dianne Hackborn4428e172012-08-24 17:43:05 -0700754 int[] getUserIdsLPr() {
755 return mUserIds;
756 }
757
Amith Yamasani13593602012-03-22 16:16:17 -0700758 private void readUserListLocked() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700759 if (!mUserListFile.exists()) {
Amith Yamasani13593602012-03-22 16:16:17 -0700760 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700761 return;
762 }
763 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700764 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700765 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700766 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700767 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100768 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700769 int type;
770 while ((type = parser.next()) != XmlPullParser.START_TAG
771 && type != XmlPullParser.END_DOCUMENT) {
772 ;
773 }
774
775 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700776 Slog.e(LOG_TAG, "Unable to read user list");
Amith Yamasani13593602012-03-22 16:16:17 -0700777 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700778 return;
779 }
780
Amith Yamasani2a003292012-08-14 18:25:45 -0700781 mNextSerialNumber = -1;
782 if (parser.getName().equals(TAG_USERS)) {
783 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
784 if (lastSerialNumber != null) {
785 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
786 }
Amith Yamasani6f34b412012-10-22 18:19:27 -0700787 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
788 if (versionNumber != null) {
789 mUserVersion = Integer.parseInt(versionNumber);
790 }
Amith Yamasani2a003292012-08-14 18:25:45 -0700791 }
792
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700793 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530794 if (type == XmlPullParser.START_TAG) {
795 final String name = parser.getName();
796 if (name.equals(TAG_USER)) {
797 String id = parser.getAttributeValue(null, ATTR_ID);
798 UserInfo user = readUserLocked(Integer.parseInt(id));
Amith Yamasani6f34b412012-10-22 18:19:27 -0700799
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530800 if (user != null) {
801 mUsers.put(user.id, user);
802 if (mNextSerialNumber < 0 || mNextSerialNumber <= user.id) {
803 mNextSerialNumber = user.id + 1;
804 }
Amith Yamasani2a003292012-08-14 18:25:45 -0700805 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530806 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -0800807 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
808 && type != XmlPullParser.END_TAG) {
809 if (type == XmlPullParser.START_TAG) {
810 if (parser.getName().equals(TAG_RESTRICTIONS)) {
Makoto Onukia4f11972015-10-01 13:19:58 -0700811 UserRestrictionsUtils
812 .readRestrictions(parser, mGuestRestrictions);
Amith Yamasanida0b1682014-11-21 12:58:17 -0800813 }
814 break;
815 }
816 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700817 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700818 }
819 }
Amith Yamasani13593602012-03-22 16:16:17 -0700820 updateUserIdsLocked();
Amith Yamasani350962c2013-08-06 11:18:53 -0700821 upgradeIfNecessaryLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700822 } catch (IOException ioe) {
Amith Yamasani13593602012-03-22 16:16:17 -0700823 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700824 } catch (XmlPullParserException pe) {
Amith Yamasani13593602012-03-22 16:16:17 -0700825 fallbackToSingleUserLocked();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -0800826 } finally {
827 if (fis != null) {
828 try {
829 fis.close();
830 } catch (IOException e) {
831 }
832 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700833 }
834 }
835
Amith Yamasani6f34b412012-10-22 18:19:27 -0700836 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -0800837 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -0700838 */
Amith Yamasani350962c2013-08-06 11:18:53 -0700839 private void upgradeIfNecessaryLocked() {
Amith Yamasani6f34b412012-10-22 18:19:27 -0700840 int userVersion = mUserVersion;
841 if (userVersion < 1) {
842 // Assign a proper name for the owner, if not initialized correctly before
Xiaohui Chen47f07952015-10-02 14:40:27 -0700843 UserInfo user = mUsers.get(UserHandle.USER_SYSTEM);
Amith Yamasani6f34b412012-10-22 18:19:27 -0700844 if ("Primary".equals(user.name)) {
845 user.name = mContext.getResources().getString(com.android.internal.R.string.owner_name);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800846 scheduleWriteUserLocked(user);
Amith Yamasani6f34b412012-10-22 18:19:27 -0700847 }
848 userVersion = 1;
849 }
850
Amith Yamasanibc9625052012-11-15 14:39:18 -0800851 if (userVersion < 2) {
852 // Owner should be marked as initialized
Xiaohui Chen47f07952015-10-02 14:40:27 -0700853 UserInfo user = mUsers.get(UserHandle.USER_SYSTEM);
Amith Yamasanibc9625052012-11-15 14:39:18 -0800854 if ((user.flags & UserInfo.FLAG_INITIALIZED) == 0) {
855 user.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800856 scheduleWriteUserLocked(user);
Amith Yamasanibc9625052012-11-15 14:39:18 -0800857 }
858 userVersion = 2;
859 }
860
Amith Yamasani350962c2013-08-06 11:18:53 -0700861
Amith Yamasani5e486f52013-08-07 11:06:44 -0700862 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -0700863 userVersion = 4;
864 }
865
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700866 if (userVersion < 5) {
867 initDefaultGuestRestrictions();
868 userVersion = 5;
869 }
870
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700871 if (userVersion < 6) {
872 final boolean splitSystemUser = UserManager.isSplitSystemUser();
873 for (int i = 0; i < mUsers.size(); i++) {
874 UserInfo user = mUsers.valueAt(i);
875 // In non-split mode, only user 0 can have restricted profiles
876 if (!splitSystemUser && user.isRestricted()
877 && (user.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID)) {
878 user.restrictedProfileParentId = UserHandle.USER_SYSTEM;
879 scheduleWriteUserLocked(user);
880 }
881 }
882 userVersion = 6;
883 }
884
Amith Yamasani6f34b412012-10-22 18:19:27 -0700885 if (userVersion < USER_VERSION) {
886 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
887 + USER_VERSION);
888 } else {
889 mUserVersion = userVersion;
890 writeUserListLocked();
891 }
892 }
893
Amith Yamasani13593602012-03-22 16:16:17 -0700894 private void fallbackToSingleUserLocked() {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -0700895 int flags = UserInfo.FLAG_INITIALIZED;
896 // In split system user mode, the admin and primary flags are assigned to the first human
897 // user.
898 if (!UserManager.isSplitSystemUser()) {
899 flags |= UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY;
900 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700901 // Create the system user
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700902 UserInfo system = new UserInfo(UserHandle.USER_SYSTEM,
Amith Yamasani6f34b412012-10-22 18:19:27 -0700903 mContext.getResources().getString(com.android.internal.R.string.owner_name), null,
Xiaohui Chenb31e14a2015-07-13 16:04:55 -0700904 flags);
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700905 mUsers.put(system.id, system);
Amith Yamasani634cf312012-10-04 17:34:21 -0700906 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -0400907 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -0800908
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -0500909 Bundle restrictions = new Bundle();
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700910 mUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions);
Amith Yamasani67df64b2012-12-14 12:09:36 -0800911
Amith Yamasani13593602012-03-22 16:16:17 -0700912 updateUserIdsLocked();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700913 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700914
Amith Yamasani13593602012-03-22 16:16:17 -0700915 writeUserListLocked();
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700916 writeUserLocked(system);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700917 }
918
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800919 private void scheduleWriteUserLocked(UserInfo userInfo) {
920 if (!mHandler.hasMessages(WRITE_USER_MSG, userInfo)) {
921 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, userInfo);
922 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
923 }
924 }
925
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700926 /*
927 * Writes the user file in this format:
928 *
929 * <user flags="20039023" id="0">
930 * <name>Primary</name>
931 * </user>
932 */
Amith Yamasani13593602012-03-22 16:16:17 -0700933 private void writeUserLocked(UserInfo userInfo) {
Amith Yamasani742a6712011-05-04 14:49:28 -0700934 FileOutputStream fos = null;
Amith Yamasanifc95e702013-09-26 13:20:17 -0700935 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userInfo.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700936 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700937 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700938 final BufferedOutputStream bos = new BufferedOutputStream(fos);
939
940 // XmlSerializer serializer = XmlUtils.serializerInstance();
941 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100942 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700943 serializer.startDocument(null, true);
944 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
945
946 serializer.startTag(null, TAG_USER);
947 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
Amith Yamasani2a003292012-08-14 18:25:45 -0700948 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700949 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Amith Yamasani920ace02012-09-20 22:15:37 -0700950 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
951 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
952 Long.toString(userInfo.lastLoggedInTime));
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700953 if (userInfo.iconPath != null) {
954 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
955 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700956 if (userInfo.partial) {
957 serializer.attribute(null, ATTR_PARTIAL, "true");
958 }
Adam Lesinskieddeb492014-09-08 17:50:03 -0700959 if (userInfo.guestToRemove) {
960 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
961 }
Kenny Guy2a764942014-04-02 13:29:20 +0100962 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
963 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
964 Integer.toString(userInfo.profileGroupId));
Kenny Guya52dc3e2014-02-11 15:33:14 +0000965 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700966 if (userInfo.restrictedProfileParentId != UserInfo.NO_PROFILE_GROUP_ID) {
967 serializer.attribute(null, ATTR_RESTRICTED_PROFILE_PARENT_ID,
968 Integer.toString(userInfo.restrictedProfileParentId));
969 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700970 serializer.startTag(null, TAG_NAME);
971 serializer.text(userInfo.name);
972 serializer.endTag(null, TAG_NAME);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800973 Bundle restrictions = mUserRestrictions.get(userInfo.id);
974 if (restrictions != null) {
Makoto Onukia4f11972015-10-01 13:19:58 -0700975 UserRestrictionsUtils.writeRestrictions(serializer, restrictions, TAG_RESTRICTIONS);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800976 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700977 serializer.endTag(null, TAG_USER);
978
979 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -0700980 userFile.finishWrite(fos);
981 } catch (Exception ioe) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700982 Slog.e(LOG_TAG, "Error writing user info " + userInfo.id + "\n" + ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -0700983 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700984 }
985 }
986
987 /*
988 * Writes the user list file in this format:
989 *
Amith Yamasani2a003292012-08-14 18:25:45 -0700990 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700991 * <user id="0"></user>
992 * <user id="2"></user>
993 * </users>
994 */
Amith Yamasani13593602012-03-22 16:16:17 -0700995 private void writeUserListLocked() {
Amith Yamasani742a6712011-05-04 14:49:28 -0700996 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700997 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700998 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700999 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001000 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1001
1002 // XmlSerializer serializer = XmlUtils.serializerInstance();
1003 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001004 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001005 serializer.startDocument(null, true);
1006 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1007
1008 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -07001009 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -07001010 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001011
Adam Lesinskieddeb492014-09-08 17:50:03 -07001012 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Makoto Onukia4f11972015-10-01 13:19:58 -07001013 UserRestrictionsUtils
1014 .writeRestrictions(serializer, mGuestRestrictions, TAG_RESTRICTIONS);
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301015 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Amith Yamasani515d4062015-09-28 11:30:06 -07001016 final int userSize = mUsers.size();
1017 for (int i = 0; i < userSize; i++) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001018 UserInfo user = mUsers.valueAt(i);
1019 serializer.startTag(null, TAG_USER);
1020 serializer.attribute(null, ATTR_ID, Integer.toString(user.id));
1021 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001022 }
1023
1024 serializer.endTag(null, TAG_USERS);
1025
1026 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001027 userListFile.finishWrite(fos);
1028 } catch (Exception e) {
1029 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -07001030 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001031 }
1032 }
1033
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001034 private UserInfo readUserLocked(int id) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001035 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -07001036 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001037 String name = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001038 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -07001039 long creationTime = 0L;
1040 long lastLoggedInTime = 0L;
Kenny Guy2a764942014-04-02 13:29:20 +01001041 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001042 int restrictedProfileParentId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001043 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001044 boolean guestToRemove = false;
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001045 Bundle restrictions = new Bundle();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001046
1047 FileInputStream fis = null;
1048 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001049 AtomicFile userFile =
Amith Yamasanifc95e702013-09-26 13:20:17 -07001050 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
Amith Yamasani2a003292012-08-14 18:25:45 -07001051 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001052 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001053 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001054 int type;
1055 while ((type = parser.next()) != XmlPullParser.START_TAG
1056 && type != XmlPullParser.END_DOCUMENT) {
1057 ;
1058 }
1059
1060 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001061 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001062 return null;
1063 }
1064
1065 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001066 int storedId = readIntAttribute(parser, ATTR_ID, -1);
1067 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001068 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001069 return null;
1070 }
Amith Yamasani920ace02012-09-20 22:15:37 -07001071 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
1072 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001073 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -07001074 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
1075 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Kenny Guy2a764942014-04-02 13:29:20 +01001076 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
1077 UserInfo.NO_PROFILE_GROUP_ID);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001078 restrictedProfileParentId = readIntAttribute(parser,
1079 ATTR_RESTRICTED_PROFILE_PARENT_ID, UserInfo.NO_PROFILE_GROUP_ID);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001080 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
1081 if ("true".equals(valueString)) {
1082 partial = true;
1083 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001084 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
1085 if ("true".equals(valueString)) {
1086 guestToRemove = true;
1087 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001088
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001089 int outerDepth = parser.getDepth();
1090 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1091 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1092 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1093 continue;
1094 }
1095 String tag = parser.getName();
1096 if (TAG_NAME.equals(tag)) {
1097 type = parser.next();
1098 if (type == XmlPullParser.TEXT) {
1099 name = parser.getText();
1100 }
1101 } else if (TAG_RESTRICTIONS.equals(tag)) {
Makoto Onukia4f11972015-10-01 13:19:58 -07001102 UserRestrictionsUtils.readRestrictions(parser, restrictions);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001103 }
1104 }
1105 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001106
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001107 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -07001108 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -07001109 userInfo.creationTime = creationTime;
1110 userInfo.lastLoggedInTime = lastLoggedInTime;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001111 userInfo.partial = partial;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001112 userInfo.guestToRemove = guestToRemove;
Kenny Guy2a764942014-04-02 13:29:20 +01001113 userInfo.profileGroupId = profileGroupId;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001114 userInfo.restrictedProfileParentId = restrictedProfileParentId;
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001115 mUserRestrictions.append(id, restrictions);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001116 return userInfo;
1117
1118 } catch (IOException ioe) {
1119 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001120 } finally {
1121 if (fis != null) {
1122 try {
1123 fis.close();
1124 } catch (IOException e) {
1125 }
1126 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001127 }
1128 return null;
1129 }
1130
Amith Yamasani920ace02012-09-20 22:15:37 -07001131 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
1132 String valueString = parser.getAttributeValue(null, attr);
1133 if (valueString == null) return defaultValue;
1134 try {
1135 return Integer.parseInt(valueString);
1136 } catch (NumberFormatException nfe) {
1137 return defaultValue;
1138 }
1139 }
1140
1141 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
1142 String valueString = parser.getAttributeValue(null, attr);
1143 if (valueString == null) return defaultValue;
1144 try {
1145 return Long.parseLong(valueString);
1146 } catch (NumberFormatException nfe) {
1147 return defaultValue;
1148 }
1149 }
1150
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001151 private boolean isPackageInstalled(String pkg, int userId) {
1152 final ApplicationInfo info = mPm.getApplicationInfo(pkg,
1153 PackageManager.GET_UNINSTALLED_PACKAGES,
1154 userId);
1155 if (info == null || (info.flags&ApplicationInfo.FLAG_INSTALLED) == 0) {
1156 return false;
1157 }
1158 return true;
1159 }
1160
Amith Yamasanib82add22013-07-09 11:24:44 -07001161 /**
Kenny Guyd21b2182014-07-17 16:38:55 +01001162 * Removes all the restrictions files (res_<packagename>) for a given user.
Amith Yamasanib82add22013-07-09 11:24:44 -07001163 * Does not do any permissions checking.
1164 */
Kenny Guyd21b2182014-07-17 16:38:55 +01001165 private void cleanAppRestrictions(int userId) {
Amith Yamasanib82add22013-07-09 11:24:44 -07001166 synchronized (mPackagesLock) {
1167 File dir = Environment.getUserSystemDirectory(userId);
1168 String[] files = dir.list();
1169 if (files == null) return;
1170 for (String fileName : files) {
1171 if (fileName.startsWith(RESTRICTIONS_FILE_PREFIX)) {
1172 File resFile = new File(dir, fileName);
1173 if (resFile.exists()) {
Kenny Guyd21b2182014-07-17 16:38:55 +01001174 resFile.delete();
Amith Yamasanib82add22013-07-09 11:24:44 -07001175 }
1176 }
1177 }
1178 }
1179 }
1180
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001181 /**
1182 * Removes the app restrictions file for a specific package and user id, if it exists.
1183 */
1184 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
1185 synchronized (mPackagesLock) {
1186 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07001187 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001188 if (resFile.exists()) {
1189 resFile.delete();
1190 }
1191 }
1192 }
1193
Kenny Guya52dc3e2014-02-11 15:33:14 +00001194 @Override
Kenny Guy2a764942014-04-02 13:29:20 +01001195 public UserInfo createProfileForUser(String name, int flags, int userId) {
Kenny Guya52dc3e2014-02-11 15:33:14 +00001196 checkManageUsersPermission("Only the system can create users");
Kenny Guy2a764942014-04-02 13:29:20 +01001197 return createUserInternal(name, flags, userId);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001198 }
1199
Amith Yamasani258848d2012-08-10 17:06:33 -07001200 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07001201 public UserInfo createUser(String name, int flags) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001202 checkManageUsersPermission("Only the system can create users");
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001203 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001204 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001205
Jessica Hummelbe81c802014-04-22 15:49:22 +01001206 private UserInfo createUserInternal(String name, int flags, int parentId) {
Julia Reynolds75175022014-06-26 16:35:00 -04001207 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1208 UserManager.DISALLOW_ADD_USER, false)) {
1209 Log.w(LOG_TAG, "Cannot add user. DISALLOW_ADD_USER is enabled.");
1210 return null;
1211 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001212 if (ActivityManager.isLowRamDeviceStatic()) {
1213 return null;
1214 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07001215 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001216 final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001217 final boolean isRestricted = (flags & UserInfo.FLAG_RESTRICTED) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001218 final long ident = Binder.clearCallingIdentity();
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001219 UserInfo userInfo = null;
Amith Yamasanibb054c92015-07-09 14:16:27 -07001220 final int userId;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001221 try {
1222 synchronized (mInstallLock) {
1223 synchronized (mPackagesLock) {
Jessica Hummelbe81c802014-04-22 15:49:22 +01001224 UserInfo parent = null;
1225 if (parentId != UserHandle.USER_NULL) {
1226 parent = getUserInfoLocked(parentId);
1227 if (parent == null) return null;
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001228 }
Nicolas Prevotb8186812015-08-06 15:00:03 +01001229 if (isManagedProfile && !canAddMoreManagedProfiles(parentId)) {
1230 Log.e(LOG_TAG, "Cannot add more managed profiles for user " + parentId);
Nicolas Prevot12678a92015-05-13 12:15:03 -07001231 return null;
1232 }
1233 if (!isGuest && !isManagedProfile && isUserLimitReachedLocked()) {
1234 // If we're not adding a guest user or a managed profile and the limit has
1235 // been reached, cannot add a user.
Amith Yamasani95ab7842014-08-11 17:09:26 -07001236 return null;
1237 }
1238 // If we're adding a guest and there already exists one, bail.
Adam Lesinskieddeb492014-09-08 17:50:03 -07001239 if (isGuest && findCurrentGuestUserLocked() != null) {
Amith Yamasani95ab7842014-08-11 17:09:26 -07001240 return null;
1241 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001242 // In legacy mode, restricted profile's parent can only be the owner user
1243 if (isRestricted && !UserManager.isSplitSystemUser()
1244 && (parentId != UserHandle.USER_SYSTEM)) {
1245 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
1246 return null;
1247 }
1248 if (isRestricted && UserManager.isSplitSystemUser()) {
1249 if (parent == null) {
1250 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be "
1251 + "specified");
1252 return null;
1253 }
1254 if (!parent.canHaveProfile()) {
1255 Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be "
1256 + "created for the specified parent user id " + parentId);
1257 return null;
1258 }
1259 }
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001260 // In split system user mode, we assign the first human user the primary flag.
Xiaohui Chen203243a2015-07-16 11:55:47 -07001261 // And if there is no device owner, we also assign the admin flag to primary
1262 // user.
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001263 if (UserManager.isSplitSystemUser()
Xiaohui Chen203243a2015-07-16 11:55:47 -07001264 && !isGuest && !isManagedProfile && getPrimaryUser() == null) {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001265 flags |= UserInfo.FLAG_PRIMARY;
Xiaohui Chen203243a2015-07-16 11:55:47 -07001266 DevicePolicyManager devicePolicyManager = (DevicePolicyManager)
1267 mContext.getSystemService(Context.DEVICE_POLICY_SERVICE);
1268 if (devicePolicyManager == null
1269 || devicePolicyManager.getDeviceOwner() == null) {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001270 flags |= UserInfo.FLAG_ADMIN;
1271 }
1272 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07001273 userId = getNextAvailableIdLocked();
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001274 userInfo = new UserInfo(userId, name, null, flags);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001275 userInfo.serialNumber = mNextSerialNumber++;
Amith Yamasani920ace02012-09-20 22:15:37 -07001276 long now = System.currentTimeMillis();
1277 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001278 userInfo.partial = true;
Amith Yamasani16389312012-10-17 21:20:14 -07001279 Environment.getUserSystemDirectory(userInfo.id).mkdirs();
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001280 mUsers.put(userId, userInfo);
1281 writeUserListLocked();
Jessica Hummelbe81c802014-04-22 15:49:22 +01001282 if (parent != null) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001283 if (isManagedProfile) {
1284 if (parent.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
1285 parent.profileGroupId = parent.id;
1286 scheduleWriteUserLocked(parent);
1287 }
1288 userInfo.profileGroupId = parent.profileGroupId;
1289 } else if (isRestricted) {
1290 if (!parent.canHaveProfile()) {
1291 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
1292 }
1293 if (parent.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) {
1294 parent.restrictedProfileParentId = parent.id;
1295 scheduleWriteUserLocked(parent);
1296 }
1297 userInfo.restrictedProfileParentId = parent.restrictedProfileParentId;
Kenny Guya52dc3e2014-02-11 15:33:14 +00001298 }
Kenny Guya52dc3e2014-02-11 15:33:14 +00001299 }
Jeff Sharkey6dce4962015-07-03 18:08:41 -07001300 final StorageManager storage = mContext.getSystemService(StorageManager.class);
1301 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
1302 final String volumeUuid = vol.getFsUuid();
1303 try {
1304 final File userDir = Environment.getDataUserDirectory(volumeUuid,
1305 userId);
Jeff Sharkey3bb8c852015-07-06 16:44:23 -07001306 prepareUserDirectory(mContext, volumeUuid, userId);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07001307 enforceSerialNumber(userDir, userInfo.serialNumber);
1308 } catch (IOException e) {
1309 Log.wtf(LOG_TAG, "Failed to create user directory on " + volumeUuid, e);
1310 }
1311 }
1312 mPm.createNewUserLILPw(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001313 userInfo.partial = false;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001314 scheduleWriteUserLocked(userInfo);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001315 updateUserIdsLocked();
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001316 Bundle restrictions = new Bundle();
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001317 mUserRestrictions.append(userId, restrictions);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001318 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07001319 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07001320 mPm.newUserCreated(userId);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001321 if (userInfo != null) {
1322 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
1323 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userInfo.id);
1324 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
1325 android.Manifest.permission.MANAGE_USERS);
1326 }
1327 } finally {
1328 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07001329 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001330 return userInfo;
1331 }
1332
Amith Yamasani0b285492011-04-14 17:35:23 -07001333 /**
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07001334 * @hide
1335 */
1336 public UserInfo createRestrictedProfile(String name, int parentUserId) {
1337 checkManageUsersPermission("setupRestrictedProfile");
1338 final UserInfo user = createProfileForUser(name, UserInfo.FLAG_RESTRICTED, parentUserId);
1339 if (user == null) {
1340 return null;
1341 }
1342 setUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, true, user.id);
1343 // Change the setting before applying the DISALLOW_SHARE_LOCATION restriction, otherwise
1344 // the putIntForUser() will fail.
1345 android.provider.Settings.Secure.putIntForUser(mContext.getContentResolver(),
1346 android.provider.Settings.Secure.LOCATION_MODE,
1347 android.provider.Settings.Secure.LOCATION_MODE_OFF, user.id);
1348 setUserRestriction(UserManager.DISALLOW_SHARE_LOCATION, true, user.id);
1349 return user;
1350 }
1351
1352 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07001353 * Find the current guest user. If the Guest user is partial,
1354 * then do not include it in the results as it is about to die.
Adam Lesinskieddeb492014-09-08 17:50:03 -07001355 */
1356 private UserInfo findCurrentGuestUserLocked() {
1357 final int size = mUsers.size();
1358 for (int i = 0; i < size; i++) {
1359 final UserInfo user = mUsers.valueAt(i);
1360 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
1361 return user;
1362 }
1363 }
1364 return null;
1365 }
1366
1367 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07001368 * Mark this guest user for deletion to allow us to create another guest
1369 * and switch to that user before actually removing this guest.
1370 * @param userHandle the userid of the current guest
1371 * @return whether the user could be marked for deletion
1372 */
1373 public boolean markGuestForDeletion(int userHandle) {
1374 checkManageUsersPermission("Only the system can remove users");
1375 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1376 UserManager.DISALLOW_REMOVE_USER, false)) {
1377 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1378 return false;
1379 }
1380
1381 long ident = Binder.clearCallingIdentity();
1382 try {
1383 final UserInfo user;
1384 synchronized (mPackagesLock) {
1385 user = mUsers.get(userHandle);
1386 if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
1387 return false;
1388 }
1389 if (!user.isGuest()) {
1390 return false;
1391 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001392 // We set this to a guest user that is to be removed. This is a temporary state
1393 // where we are allowed to add new Guest users, even if this one is still not
1394 // removed. This user will still show up in getUserInfo() calls.
1395 // If we don't get around to removing this Guest user, it will be purged on next
1396 // startup.
1397 user.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07001398 // Mark it as disabled, so that it isn't returned any more when
1399 // profiles are queried.
1400 user.flags |= UserInfo.FLAG_DISABLED;
Amith Yamasani1df14732014-08-29 21:37:27 -07001401 writeUserLocked(user);
1402 }
1403 } finally {
1404 Binder.restoreCallingIdentity(ident);
1405 }
1406 return true;
1407 }
1408
1409 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07001410 * Removes a user and all data directories created for that user. This method should be called
1411 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001412 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07001413 */
Amith Yamasani258848d2012-08-10 17:06:33 -07001414 public boolean removeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001415 checkManageUsersPermission("Only the system can remove users");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04001416 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1417 UserManager.DISALLOW_REMOVE_USER, false)) {
1418 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1419 return false;
1420 }
1421
Kenny Guyee58b4f2014-05-23 15:19:53 +01001422 long ident = Binder.clearCallingIdentity();
1423 try {
1424 final UserInfo user;
Fyodor Kupolov0df68cd2015-10-01 13:54:22 -07001425 int currentUser = ActivityManager.getCurrentUser();
1426 if (currentUser == userHandle) {
1427 Log.w(LOG_TAG, "Current user cannot be removed");
1428 return false;
1429 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01001430 synchronized (mPackagesLock) {
1431 user = mUsers.get(userHandle);
Kenny Guy17c9d692014-06-13 13:51:42 +01001432 if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01001433 return false;
1434 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08001435
1436 // We remember deleted user IDs to prevent them from being
1437 // reused during the current boot; they can still be reused
1438 // after a reboot.
Kenny Guyee58b4f2014-05-23 15:19:53 +01001439 mRemovingUserIds.put(userHandle, true);
Jeff Sharkey6eb09392014-11-14 15:57:59 -08001440
Kenny Guyee58b4f2014-05-23 15:19:53 +01001441 try {
1442 mAppOpsService.removeUser(userHandle);
1443 } catch (RemoteException e) {
1444 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
1445 }
1446 // Set this to a partially created user, so that the user will be purged
1447 // on next startup, in case the runtime stops now before stopping and
1448 // removing the user completely.
1449 user.partial = true;
1450 // Mark it as disabled, so that it isn't returned any more when
1451 // profiles are queried.
1452 user.flags |= UserInfo.FLAG_DISABLED;
1453 writeUserLocked(user);
1454 }
1455
1456 if (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
1457 && user.isManagedProfile()) {
1458 // Send broadcast to notify system that the user removed was a
1459 // managed user.
1460 sendProfileRemovedBroadcast(user.profileGroupId, user.id);
1461 }
1462
1463 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
1464 int res;
1465 try {
1466 res = ActivityManagerNative.getDefault().stopUser(userHandle,
1467 new IStopUserCallback.Stub() {
1468 @Override
1469 public void userStopped(int userId) {
1470 finishRemoveUser(userId);
1471 }
1472 @Override
1473 public void userStopAborted(int userId) {
1474 }
1475 });
1476 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001477 return false;
1478 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01001479 return res == ActivityManager.USER_OP_SUCCESS;
1480 } finally {
1481 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001482 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001483 }
1484
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001485 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07001486 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001487 // Let other services shutdown any activity and clean up their state before completely
1488 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001489 long ident = Binder.clearCallingIdentity();
1490 try {
1491 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
1492 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001493 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
1494 android.Manifest.permission.MANAGE_USERS,
1495
1496 new BroadcastReceiver() {
1497 @Override
1498 public void onReceive(Context context, Intent intent) {
1499 if (DBG) {
1500 Slog.i(LOG_TAG,
1501 "USER_REMOVED broadcast sent, cleaning up user data "
1502 + userHandle);
1503 }
1504 new Thread() {
1505 public void run() {
Amith Yamasani515d4062015-09-28 11:30:06 -07001506 // Clean up any ActivityManager state
1507 LocalServices.getService(ActivityManagerInternal.class)
1508 .onUserRemoved(userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001509 synchronized (mInstallLock) {
1510 synchronized (mPackagesLock) {
1511 removeUserStateLocked(userHandle);
1512 }
1513 }
1514 }
1515 }.start();
1516 }
1517 },
1518
1519 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001520 } finally {
1521 Binder.restoreCallingIdentity(ident);
1522 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001523 }
1524
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001525 private void removeUserStateLocked(final int userHandle) {
Paul Crowley85e4e812015-05-19 12:42:00 +01001526 mContext.getSystemService(StorageManager.class)
1527 .deleteUserKey(userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001528 // Cleanup package manager settings
Amith Yamasanidda003f2014-08-28 18:06:51 -07001529 mPm.cleanUpUserLILPw(this, userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001530
1531 // Remove this user from the list
1532 mUsers.remove(userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001533 // Remove user file
Amith Yamasanifc95e702013-09-26 13:20:17 -07001534 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001535 userFile.delete();
1536 // Update the user list
1537 writeUserListLocked();
1538 updateUserIdsLocked();
1539 removeDirectoryRecursive(Environment.getUserSystemDirectory(userHandle));
1540 }
1541
Amith Yamasani61f57372012-08-31 12:12:28 -07001542 private void removeDirectoryRecursive(File parent) {
1543 if (parent.isDirectory()) {
1544 String[] files = parent.list();
1545 for (String filename : files) {
1546 File child = new File(parent, filename);
1547 removeDirectoryRecursive(child);
1548 }
1549 }
1550 parent.delete();
1551 }
1552
Kenny Guyf8d3a232014-05-15 16:09:52 +01001553 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01001554 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01001555 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
1556 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01001557 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
1558 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01001559 }
1560
Amith Yamasani2a003292012-08-14 18:25:45 -07001561 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001562 public Bundle getApplicationRestrictions(String packageName) {
1563 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
1564 }
1565
1566 @Override
1567 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001568 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07001569 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001570 checkManageUsersPermission("Only system can get restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001571 }
1572 synchronized (mPackagesLock) {
1573 // Read the restrictions from XML
1574 return readApplicationRestrictionsLocked(packageName, userId);
1575 }
1576 }
1577
1578 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001579 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001580 int userId) {
1581 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07001582 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001583 checkManageUsersPermission("Only system can set restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001584 }
1585 synchronized (mPackagesLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01001586 if (restrictions == null || restrictions.isEmpty()) {
1587 cleanAppRestrictionsForPackage(packageName, userId);
1588 } else {
1589 // Write the restrictions to XML
1590 writeApplicationRestrictionsLocked(packageName, restrictions, userId);
1591 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001592 }
Robin Lee66e5d962014-04-09 16:44:21 +01001593
Kenny Guyd21b2182014-07-17 16:38:55 +01001594 if (isPackageInstalled(packageName, userId)) {
1595 // Notify package of changes via an intent - only sent to explicitly registered receivers.
1596 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
1597 changeIntent.setPackage(packageName);
1598 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
1599 mContext.sendBroadcastAsUser(changeIntent, new UserHandle(userId));
1600 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001601 }
1602
Amith Yamasani655d0e22013-06-12 14:19:10 -07001603 @Override
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001604 public void removeRestrictions() {
Amith Yamasanibe465322014-04-24 13:45:17 -07001605 checkManageUsersPermission("Only system can remove restrictions");
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001606 final int userHandle = UserHandle.getCallingUserId();
Amith Yamasani5e486f52013-08-07 11:06:44 -07001607 removeRestrictionsForUser(userHandle, true);
Amith Yamasani350962c2013-08-06 11:18:53 -07001608 }
1609
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001610 private void removeRestrictionsForUser(final int userHandle, boolean unhideApps) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001611 synchronized (mPackagesLock) {
1612 // Remove all user restrictions
1613 setUserRestrictions(new Bundle(), userHandle);
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001614 // Remove any app restrictions
Kenny Guyd21b2182014-07-17 16:38:55 +01001615 cleanAppRestrictions(userHandle);
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001616 }
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001617 if (unhideApps) {
1618 unhideAllInstalledAppsForUser(userHandle);
Amith Yamasani5e486f52013-08-07 11:06:44 -07001619 }
1620 }
1621
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001622 private void unhideAllInstalledAppsForUser(final int userHandle) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001623 mHandler.post(new Runnable() {
1624 @Override
1625 public void run() {
1626 List<ApplicationInfo> apps =
1627 mPm.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES,
1628 userHandle).getList();
1629 final long ident = Binder.clearCallingIdentity();
1630 try {
1631 for (ApplicationInfo appInfo : apps) {
1632 if ((appInfo.flags & ApplicationInfo.FLAG_INSTALLED) != 0
Alex Klyubinb9f8a522015-02-03 11:12:59 -08001633 && (appInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HIDDEN)
1634 != 0) {
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001635 mPm.setApplicationHiddenSettingAsUser(appInfo.packageName, false,
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001636 userHandle);
1637 }
1638 }
1639 } finally {
1640 Binder.restoreCallingIdentity(ident);
1641 }
1642 }
1643 });
1644 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001645 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07001646 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001647 try {
1648 return mContext.getPackageManager().getApplicationInfo(packageName,
1649 PackageManager.GET_UNINSTALLED_PACKAGES).uid;
1650 } catch (NameNotFoundException nnfe) {
1651 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07001652 } finally {
1653 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001654 }
1655 }
1656
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001657 private Bundle readApplicationRestrictionsLocked(String packageName,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001658 int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001659 AtomicFile restrictionsFile =
1660 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
1661 packageToRestrictionsFileName(packageName)));
1662 return readApplicationRestrictionsLocked(restrictionsFile);
1663 }
1664
1665 @VisibleForTesting
1666 static Bundle readApplicationRestrictionsLocked(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001667 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001668 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07001669 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07001670 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07001671 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001672
1673 FileInputStream fis = null;
1674 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001675 fis = restrictionsFile.openRead();
1676 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001677 parser.setInput(fis, StandardCharsets.UTF_8.name());
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001678 XmlUtils.nextElement(parser);
1679 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001680 Slog.e(LOG_TAG, "Unable to read restrictions file "
1681 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001682 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001683 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001684 while (parser.next() != XmlPullParser.END_DOCUMENT) {
1685 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001686 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001687 } catch (IOException|XmlPullParserException e) {
1688 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001689 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001690 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001691 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001692 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001693 }
1694
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001695 private static void readEntry(Bundle restrictions, ArrayList<String> values,
1696 XmlPullParser parser) throws XmlPullParserException, IOException {
1697 int type = parser.getEventType();
1698 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
1699 String key = parser.getAttributeValue(null, ATTR_KEY);
1700 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
1701 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
1702 if (multiple != null) {
1703 values.clear();
1704 int count = Integer.parseInt(multiple);
1705 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1706 if (type == XmlPullParser.START_TAG
1707 && parser.getName().equals(TAG_VALUE)) {
1708 values.add(parser.nextText().trim());
1709 count--;
1710 }
1711 }
1712 String [] valueStrings = new String[values.size()];
1713 values.toArray(valueStrings);
1714 restrictions.putStringArray(key, valueStrings);
1715 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
1716 restrictions.putBundle(key, readBundleEntry(parser, values));
1717 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
1718 final int outerDepth = parser.getDepth();
1719 ArrayList<Bundle> bundleList = new ArrayList<>();
1720 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
1721 Bundle childBundle = readBundleEntry(parser, values);
1722 bundleList.add(childBundle);
1723 }
1724 restrictions.putParcelableArray(key,
1725 bundleList.toArray(new Bundle[bundleList.size()]));
1726 } else {
1727 String value = parser.nextText().trim();
1728 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
1729 restrictions.putBoolean(key, Boolean.parseBoolean(value));
1730 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
1731 restrictions.putInt(key, Integer.parseInt(value));
1732 } else {
1733 restrictions.putString(key, value);
1734 }
1735 }
1736 }
1737 }
1738
1739 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
1740 throws IOException, XmlPullParserException {
1741 Bundle childBundle = new Bundle();
1742 final int outerDepth = parser.getDepth();
1743 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
1744 readEntry(childBundle, values, parser);
1745 }
1746 return childBundle;
1747 }
1748
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001749 private void writeApplicationRestrictionsLocked(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001750 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001751 AtomicFile restrictionsFile = new AtomicFile(
1752 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07001753 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001754 writeApplicationRestrictionsLocked(restrictions, restrictionsFile);
1755 }
1756
1757 @VisibleForTesting
1758 static void writeApplicationRestrictionsLocked(Bundle restrictions,
1759 AtomicFile restrictionsFile) {
1760 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001761 try {
1762 fos = restrictionsFile.startWrite();
1763 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1764
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001765 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001766 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001767 serializer.startDocument(null, true);
1768 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1769
1770 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001771 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001772 serializer.endTag(null, TAG_RESTRICTIONS);
1773
1774 serializer.endDocument();
1775 restrictionsFile.finishWrite(fos);
1776 } catch (Exception e) {
1777 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001778 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
1779 }
1780 }
1781
1782 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
1783 throws IOException {
1784 for (String key : restrictions.keySet()) {
1785 Object value = restrictions.get(key);
1786 serializer.startTag(null, TAG_ENTRY);
1787 serializer.attribute(null, ATTR_KEY, key);
1788
1789 if (value instanceof Boolean) {
1790 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
1791 serializer.text(value.toString());
1792 } else if (value instanceof Integer) {
1793 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
1794 serializer.text(value.toString());
1795 } else if (value == null || value instanceof String) {
1796 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
1797 serializer.text(value != null ? (String) value : "");
1798 } else if (value instanceof Bundle) {
1799 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
1800 writeBundle((Bundle) value, serializer);
1801 } else if (value instanceof Parcelable[]) {
1802 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
1803 Parcelable[] array = (Parcelable[]) value;
1804 for (Parcelable parcelable : array) {
1805 if (!(parcelable instanceof Bundle)) {
1806 throw new IllegalArgumentException("bundle-array can only hold Bundles");
1807 }
1808 serializer.startTag(null, TAG_ENTRY);
1809 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
1810 writeBundle((Bundle) parcelable, serializer);
1811 serializer.endTag(null, TAG_ENTRY);
1812 }
1813 } else {
1814 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
1815 String[] values = (String[]) value;
1816 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
1817 for (String choice : values) {
1818 serializer.startTag(null, TAG_VALUE);
1819 serializer.text(choice != null ? choice : "");
1820 serializer.endTag(null, TAG_VALUE);
1821 }
1822 }
1823 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001824 }
1825 }
1826
1827 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07001828 public int getUserSerialNumber(int userHandle) {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001829 synchronized (mPackagesLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001830 if (!exists(userHandle)) return -1;
Amith Yamasani195263742012-08-21 15:40:12 -07001831 return getUserInfoLocked(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07001832 }
1833 }
1834
1835 @Override
1836 public int getUserHandle(int userSerialNumber) {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001837 synchronized (mPackagesLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001838 for (int userId : mUserIds) {
Kenny Guy945f8832015-02-10 15:17:26 +00001839 UserInfo info = getUserInfoLocked(userId);
1840 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07001841 }
1842 // Not found
1843 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07001844 }
1845 }
1846
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07001847 @Override
1848 public long getUserCreationTime(int userHandle) {
1849 int callingUserId = UserHandle.getCallingUserId();
1850 UserInfo userInfo = null;
1851 synchronized (mPackagesLock) {
1852 if (callingUserId == userHandle) {
1853 userInfo = getUserInfoLocked(userHandle);
1854 } else {
1855 UserInfo parent = getProfileParentLocked(userHandle);
1856 if (parent != null && parent.id == callingUserId) {
1857 userInfo = getUserInfoLocked(userHandle);
1858 }
1859 }
1860 }
1861 if (userInfo == null) {
1862 throw new SecurityException("userHandle can only be the calling user or a managed "
1863 + "profile associated with this user");
1864 }
1865 return userInfo.creationTime;
1866 }
1867
Amith Yamasani0b285492011-04-14 17:35:23 -07001868 /**
1869 * Caches the list of user ids in an array, adjusting the array size when necessary.
1870 */
Amith Yamasani13593602012-03-22 16:16:17 -07001871 private void updateUserIdsLocked() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001872 int num = 0;
Amith Yamasani515d4062015-09-28 11:30:06 -07001873 final int userSize = mUsers.size();
1874 for (int i = 0; i < userSize; i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001875 if (!mUsers.valueAt(i).partial) {
1876 num++;
1877 }
1878 }
Amith Yamasani16389312012-10-17 21:20:14 -07001879 final int[] newUsers = new int[num];
1880 int n = 0;
Amith Yamasani515d4062015-09-28 11:30:06 -07001881 for (int i = 0; i < userSize; i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001882 if (!mUsers.valueAt(i).partial) {
Amith Yamasani16389312012-10-17 21:20:14 -07001883 newUsers[n++] = mUsers.keyAt(i);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001884 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001885 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001886 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07001887 }
1888
1889 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001890 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasani920ace02012-09-20 22:15:37 -07001891 * @param userId the user that was just foregrounded
1892 */
Amith Yamasani06bf8242015-05-08 16:36:21 -07001893 public void onUserForeground(int userId) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001894 synchronized (mPackagesLock) {
1895 UserInfo user = mUsers.get(userId);
1896 long now = System.currentTimeMillis();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001897 if (user == null || user.partial) {
1898 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
1899 return;
1900 }
1901 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001902 user.lastLoggedInTime = now;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001903 scheduleWriteUserLocked(user);
Amith Yamasani920ace02012-09-20 22:15:37 -07001904 }
1905 }
1906 }
1907
1908 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07001909 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani742a6712011-05-04 14:49:28 -07001910 * TODO: May not be a good idea to recycle ids, in case it results in confusion
1911 * for data and battery stats collection, or unexpected cross-talk.
Amith Yamasani0b285492011-04-14 17:35:23 -07001912 * @return
1913 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001914 private int getNextAvailableIdLocked() {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001915 synchronized (mPackagesLock) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001916 int i = MIN_USER_ID;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07001917 while (i < MAX_USER_ID) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001918 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07001919 return i;
Amith Yamasani195263742012-08-21 15:40:12 -07001920 }
1921 i++;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001922 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001923 }
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07001924 throw new IllegalStateException("No user id available!");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001925 }
Amith Yamasani920ace02012-09-20 22:15:37 -07001926
Amith Yamasanifc95e702013-09-26 13:20:17 -07001927 private String packageToRestrictionsFileName(String packageName) {
1928 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
1929 }
1930
Jeff Sharkey6dce4962015-07-03 18:08:41 -07001931 /**
1932 * Create new {@code /data/user/[id]} directory and sets default
1933 * permissions.
1934 */
Jeff Sharkey3bb8c852015-07-06 16:44:23 -07001935 public static void prepareUserDirectory(Context context, String volumeUuid, int userId) {
1936 final StorageManager storage = context.getSystemService(StorageManager.class);
1937 final File userDir = Environment.getDataUserDirectory(volumeUuid, userId);
1938 storage.createNewUserDir(userId, userDir);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07001939 }
1940
1941 /**
1942 * Enforce that serial number stored in user directory inode matches the
1943 * given expected value. Gracefully sets the serial number if currently
1944 * undefined.
1945 *
1946 * @throws IOException when problem extracting serial number, or serial
1947 * number is mismatched.
1948 */
1949 public static void enforceSerialNumber(File file, int serialNumber) throws IOException {
1950 final int foundSerial = getSerialNumber(file);
1951 Slog.v(LOG_TAG, "Found " + file + " with serial number " + foundSerial);
1952
1953 if (foundSerial == -1) {
1954 Slog.d(LOG_TAG, "Serial number missing on " + file + "; assuming current is valid");
1955 try {
1956 setSerialNumber(file, serialNumber);
1957 } catch (IOException e) {
1958 Slog.w(LOG_TAG, "Failed to set serial number on " + file, e);
1959 }
1960
1961 } else if (foundSerial != serialNumber) {
1962 throw new IOException("Found serial number " + foundSerial
1963 + " doesn't match expected " + serialNumber);
1964 }
1965 }
1966
1967 /**
1968 * Set serial number stored in user directory inode.
1969 *
1970 * @throws IOException if serial number was already set
1971 */
1972 private static void setSerialNumber(File file, int serialNumber)
1973 throws IOException {
1974 try {
1975 final byte[] buf = Integer.toString(serialNumber).getBytes(StandardCharsets.UTF_8);
1976 Os.setxattr(file.getAbsolutePath(), XATTR_SERIAL, buf, OsConstants.XATTR_CREATE);
1977 } catch (ErrnoException e) {
1978 throw e.rethrowAsIOException();
1979 }
1980 }
1981
1982 /**
1983 * Return serial number stored in user directory inode.
1984 *
1985 * @return parsed serial number, or -1 if not set
1986 */
1987 private static int getSerialNumber(File file) throws IOException {
1988 try {
1989 final byte[] buf = new byte[256];
1990 final int len = Os.getxattr(file.getAbsolutePath(), XATTR_SERIAL, buf);
1991 final String serial = new String(buf, 0, len);
1992 try {
1993 return Integer.parseInt(serial);
1994 } catch (NumberFormatException e) {
1995 throw new IOException("Bad serial number: " + serial);
1996 }
1997 } catch (ErrnoException e) {
1998 if (e.errno == OsConstants.ENODATA) {
1999 return -1;
2000 } else {
2001 throw e.rethrowAsIOException();
2002 }
2003 }
2004 }
2005
Amith Yamasani920ace02012-09-20 22:15:37 -07002006 @Override
2007 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2008 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2009 != PackageManager.PERMISSION_GRANTED) {
2010 pw.println("Permission Denial: can't dump UserManager from from pid="
2011 + Binder.getCallingPid()
2012 + ", uid=" + Binder.getCallingUid()
2013 + " without permission "
2014 + android.Manifest.permission.DUMP);
2015 return;
2016 }
2017
2018 long now = System.currentTimeMillis();
2019 StringBuilder sb = new StringBuilder();
2020 synchronized (mPackagesLock) {
2021 pw.println("Users:");
2022 for (int i = 0; i < mUsers.size(); i++) {
2023 UserInfo user = mUsers.valueAt(i);
2024 if (user == null) continue;
Amith Yamasani634cf312012-10-04 17:34:21 -07002025 pw.print(" "); pw.print(user); pw.print(" serialNo="); pw.print(user.serialNumber);
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002026 if (mRemovingUserIds.get(mUsers.keyAt(i))) pw.print(" <removing> ");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002027 if (user.partial) pw.print(" <partial>");
2028 pw.println();
Amith Yamasani920ace02012-09-20 22:15:37 -07002029 pw.print(" Created: ");
2030 if (user.creationTime == 0) {
2031 pw.println("<unknown>");
2032 } else {
2033 sb.setLength(0);
2034 TimeUtils.formatDuration(now - user.creationTime, sb);
2035 sb.append(" ago");
2036 pw.println(sb);
2037 }
2038 pw.print(" Last logged in: ");
2039 if (user.lastLoggedInTime == 0) {
2040 pw.println("<unknown>");
2041 } else {
2042 sb.setLength(0);
2043 TimeUtils.formatDuration(now - user.lastLoggedInTime, sb);
2044 sb.append(" ago");
2045 pw.println(sb);
2046 }
Makoto Onukia4f11972015-10-01 13:19:58 -07002047 pw.println(" Restrictions:");
2048 UserRestrictionsUtils.dumpRestrictions(
2049 pw, " ", mUserRestrictions.get(user.id));
Amith Yamasani920ace02012-09-20 22:15:37 -07002050 }
Makoto Onukia4f11972015-10-01 13:19:58 -07002051 pw.println();
2052 pw.println("Guest restrictions:");
2053 UserRestrictionsUtils.dumpRestrictions(pw, " ", mGuestRestrictions);
Amith Yamasani920ace02012-09-20 22:15:37 -07002054 }
2055 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002056
2057 final class MainHandler extends Handler {
2058
2059 @Override
2060 public void handleMessage(Message msg) {
2061 switch (msg.what) {
2062 case WRITE_USER_MSG:
2063 removeMessages(WRITE_USER_MSG, msg.obj);
2064 synchronized (mPackagesLock) {
2065 int userId = ((UserInfo) msg.obj).id;
2066 UserInfo userInfo = mUsers.get(userId);
2067 if (userInfo != null) {
2068 writeUserLocked(userInfo);
2069 }
2070 }
2071 }
2072 }
2073 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07002074
2075 /**
2076 * @param userId
2077 * @return whether the user has been initialized yet
2078 */
2079 boolean isInitialized(int userId) {
2080 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
2081 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002082}