blob: 80697edd50e5453f14526120d2f766dac4496dac [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
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700359 public boolean isSameProfileGroup(int userId, int otherUserId) {
360 if (userId == otherUserId) return true;
361 checkManageUsersPermission("check if in the same profile group");
362 synchronized (mPackagesLock) {
363 return isSameProfileGroupLocked(userId, otherUserId);
364 }
365 }
366
367 private boolean isSameProfileGroupLocked(int userId, int otherUserId) {
368 UserInfo userInfo = getUserInfoLocked(userId);
369 if (userInfo == null || userInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
370 return false;
371 }
372 UserInfo otherUserInfo = getUserInfoLocked(otherUserId);
373 if (otherUserInfo == null || otherUserInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
374 return false;
375 }
376 return userInfo.profileGroupId == otherUserInfo.profileGroupId;
377 }
378
379 @Override
Jessica Hummelbe81c802014-04-22 15:49:22 +0100380 public UserInfo getProfileParent(int userHandle) {
381 checkManageUsersPermission("get the profile parent");
382 synchronized (mPackagesLock) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700383 return getProfileParentLocked(userHandle);
384 }
385 }
386
387 private UserInfo getProfileParentLocked(int userHandle) {
388 UserInfo profile = getUserInfoLocked(userHandle);
389 if (profile == null) {
390 return null;
391 }
392 int parentUserId = profile.profileGroupId;
393 if (parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
394 return null;
395 } else {
396 return getUserInfoLocked(parentUserId);
Jessica Hummelbe81c802014-04-22 15:49:22 +0100397 }
398 }
399
Kenny Guy2a764942014-04-02 13:29:20 +0100400 private boolean isProfileOf(UserInfo user, UserInfo profile) {
401 return user.id == profile.id ||
402 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
403 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000404 }
405
406 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100407 public void setUserEnabled(int userId) {
408 checkManageUsersPermission("enable user");
409 synchronized (mPackagesLock) {
410 UserInfo info = getUserInfoLocked(userId);
411 if (info != null && !info.isEnabled()) {
412 info.flags ^= UserInfo.FLAG_DISABLED;
413 writeUserLocked(info);
414 }
415 }
416 }
417
418 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700419 public UserInfo getUserInfo(int userId) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700420 checkManageUsersPermission("query user");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700421 synchronized (mPackagesLock) {
Amith Yamasani195263742012-08-21 15:40:12 -0700422 return getUserInfoLocked(userId);
Amith Yamasani13593602012-03-22 16:16:17 -0700423 }
424 }
425
Amith Yamasani71e6c692013-03-24 17:39:28 -0700426 @Override
427 public boolean isRestricted() {
428 synchronized (mPackagesLock) {
429 return getUserInfoLocked(UserHandle.getCallingUserId()).isRestricted();
430 }
431 }
432
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700433 @Override
434 public boolean canHaveRestrictedProfile(int userId) {
435 checkManageUsersPermission("canHaveRestrictedProfile");
436 synchronized (mPackagesLock) {
437 final UserInfo userInfo = getUserInfoLocked(userId);
438 if (userInfo == null || !userInfo.canHaveProfile()) {
439 return false;
440 }
441 if (!userInfo.isAdmin()) {
442 return false;
443 }
444 }
445 DevicePolicyManager dpm = (DevicePolicyManager) mContext.getSystemService(
446 Context.DEVICE_POLICY_SERVICE);
447 // restricted profile can be created if there is no DO set and the admin user has no PO
448 return dpm.getDeviceOwner() == null && dpm.getProfileOwnerAsUser(userId) == null;
449 }
450
Amith Yamasani195263742012-08-21 15:40:12 -0700451 /*
452 * Should be locked on mUsers before calling this.
453 */
454 private UserInfo getUserInfoLocked(int userId) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700455 UserInfo ui = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -0700456 // If it is partial and not in the process of being removed, return as unknown user.
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800457 if (ui != null && ui.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700458 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
459 return null;
460 }
461 return ui;
Amith Yamasani195263742012-08-21 15:40:12 -0700462 }
463
Amith Yamasani236b2b52015-08-18 14:32:14 -0700464 /** Called by PackageManagerService */
Amith Yamasani13593602012-03-22 16:16:17 -0700465 public boolean exists(int userId) {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700466 synchronized (mPackagesLock) {
Amith Yamasani236b2b52015-08-18 14:32:14 -0700467 return mUsers.get(userId) != null;
Amith Yamasani13593602012-03-22 16:16:17 -0700468 }
469 }
470
Amith Yamasani258848d2012-08-10 17:06:33 -0700471 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700472 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700473 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700474 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700475 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700476 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700477 if (info == null || info.partial) {
478 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
479 return;
480 }
Amith Yamasani13593602012-03-22 16:16:17 -0700481 if (name != null && !name.equals(info.name)) {
482 info.name = name;
483 writeUserLocked(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700484 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -0700485 }
486 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700487 if (changed) {
488 sendUserInfoChangedBroadcast(userId);
489 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700490 }
491
Amith Yamasani258848d2012-08-10 17:06:33 -0700492 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700493 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700494 checkManageUsersPermission("update users");
Jason Monk9a944532014-07-08 09:31:21 -0400495 long ident = Binder.clearCallingIdentity();
496 try {
497 synchronized (mPackagesLock) {
498 UserInfo info = mUsers.get(userId);
499 if (info == null || info.partial) {
500 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
501 return;
502 }
503 writeBitmapLocked(info, bitmap);
504 writeUserLocked(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700505 }
Jason Monk9a944532014-07-08 09:31:21 -0400506 sendUserInfoChangedBroadcast(userId);
507 } finally {
508 Binder.restoreCallingIdentity(ident);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700509 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700510 }
511
512 private void sendUserInfoChangedBroadcast(int userId) {
513 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
514 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
515 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -0700516 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700517 }
518
Amith Yamasani258848d2012-08-10 17:06:33 -0700519 @Override
Adrian Roos1bdff912015-02-17 15:51:35 +0100520 public ParcelFileDescriptor getUserIcon(int userId) {
521 String iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700522 synchronized (mPackagesLock) {
523 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700524 if (info == null || info.partial) {
525 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + userId);
526 return null;
527 }
Nicolas Prevot88cc3462014-05-14 14:51:48 +0100528 int callingGroupId = mUsers.get(UserHandle.getCallingUserId()).profileGroupId;
529 if (callingGroupId == UserInfo.NO_PROFILE_GROUP_ID
530 || callingGroupId != info.profileGroupId) {
531 checkManageUsersPermission("get the icon of a user who is not related");
532 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700533 if (info.iconPath == null) {
534 return null;
535 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100536 iconPath = info.iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700537 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100538
539 try {
540 return ParcelFileDescriptor.open(
541 new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
542 } catch (FileNotFoundException e) {
543 Log.e(LOG_TAG, "Couldn't find icon file", e);
544 }
545 return null;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700546 }
547
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700548 public void makeInitialized(int userId) {
549 checkManageUsersPermission("makeInitialized");
550 synchronized (mPackagesLock) {
551 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700552 if (info == null || info.partial) {
553 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
554 }
555 if ((info.flags&UserInfo.FLAG_INITIALIZED) == 0) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700556 info.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800557 scheduleWriteUserLocked(info);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700558 }
559 }
560 }
561
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700562 /**
563 * If default guest restrictions haven't been initialized yet, add the basic
564 * restrictions.
565 */
566 private void initDefaultGuestRestrictions() {
567 if (mGuestRestrictions.isEmpty()) {
568 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
Amith Yamasanida0b1682014-11-21 12:58:17 -0800569 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700570 }
571 }
572
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800573 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530574 public Bundle getDefaultGuestRestrictions() {
575 checkManageUsersPermission("getDefaultGuestRestrictions");
576 synchronized (mPackagesLock) {
577 return new Bundle(mGuestRestrictions);
578 }
579 }
580
581 @Override
582 public void setDefaultGuestRestrictions(Bundle restrictions) {
583 checkManageUsersPermission("setDefaultGuestRestrictions");
584 synchronized (mPackagesLock) {
585 mGuestRestrictions.clear();
586 mGuestRestrictions.putAll(restrictions);
587 writeUserListLocked();
588 }
589 }
590
591 @Override
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700592 public boolean hasUserRestriction(String restrictionKey, int userId) {
593 synchronized (mPackagesLock) {
594 Bundle restrictions = mUserRestrictions.get(userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700595 return restrictions != null && restrictions.getBoolean(restrictionKey);
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700596 }
597 }
598
599 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800600 public Bundle getUserRestrictions(int userId) {
601 // checkManageUsersPermission("getUserRestrictions");
602
603 synchronized (mPackagesLock) {
604 Bundle restrictions = mUserRestrictions.get(userId);
Amith Yamasanibe465322014-04-24 13:45:17 -0700605 return restrictions != null ? new Bundle(restrictions) : new Bundle();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800606 }
607 }
608
609 @Override
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700610 public void setUserRestriction(String key, boolean value, int userId) {
Fyodor Kupolovd4b26042015-07-27 14:30:59 -0700611 checkManageUsersPermission("setUserRestriction");
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700612 synchronized (mPackagesLock) {
Makoto Onukia4f11972015-10-01 13:19:58 -0700613 if (!UserRestrictionsUtils.SYSTEM_CONTROLLED_USER_RESTRICTIONS.contains(key)) {
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700614 Bundle restrictions = getUserRestrictions(userId);
615 restrictions.putBoolean(key, value);
616 setUserRestrictionsInternalLocked(restrictions, userId);
617 }
618 }
619 }
620
621 @Override
622 public void setSystemControlledUserRestriction(String key, boolean value, int userId) {
623 checkSystemOrRoot("setSystemControlledUserRestriction");
624 synchronized (mPackagesLock) {
625 Bundle restrictions = getUserRestrictions(userId);
626 restrictions.putBoolean(key, value);
627 setUserRestrictionsInternalLocked(restrictions, userId);
628 }
629 }
630
631 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800632 public void setUserRestrictions(Bundle restrictions, int userId) {
Amith Yamasanibe465322014-04-24 13:45:17 -0700633 checkManageUsersPermission("setUserRestrictions");
Amith Yamasani0343ec32013-07-22 14:52:06 -0700634 if (restrictions == null) return;
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800635
636 synchronized (mPackagesLock) {
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700637 final Bundle oldUserRestrictions = mUserRestrictions.get(userId);
638 // Restore the original state of system controlled restrictions from oldUserRestrictions
Makoto Onukia4f11972015-10-01 13:19:58 -0700639 for (String key : UserRestrictionsUtils.SYSTEM_CONTROLLED_USER_RESTRICTIONS) {
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700640 restrictions.remove(key);
641 if (oldUserRestrictions.containsKey(key)) {
642 restrictions.putBoolean(key, oldUserRestrictions.getBoolean(key));
643 }
Jason Monk62062992014-05-06 09:55:28 -0400644 }
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700645 setUserRestrictionsInternalLocked(restrictions, userId);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800646 }
647 }
648
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700649 private void setUserRestrictionsInternalLocked(Bundle restrictions, int userId) {
650 final Bundle userRestrictions = mUserRestrictions.get(userId);
651 userRestrictions.clear();
652 userRestrictions.putAll(restrictions);
653 long token = Binder.clearCallingIdentity();
654 try {
655 mAppOpsService.setUserRestrictions(userRestrictions, userId);
656 } catch (RemoteException e) {
657 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
658 } finally {
659 Binder.restoreCallingIdentity(token);
660 }
661 scheduleWriteUserLocked(mUsers.get(userId));
662 }
663
Amith Yamasani258848d2012-08-10 17:06:33 -0700664 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700665 * Check if we've hit the limit of how many users can be created.
666 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700667 private boolean isUserLimitReachedLocked() {
Nicolas Prevot12678a92015-05-13 12:15:03 -0700668 return getAliveUsersExcludingGuestsCountLocked() >= UserManager.getMaxSupportedUsers();
669 }
670
671 @Override
Nicolas Prevotb8186812015-08-06 15:00:03 +0100672 public boolean canAddMoreManagedProfiles(int userId) {
Nicolas Prevot12678a92015-05-13 12:15:03 -0700673 checkManageUsersPermission("check if more managed profiles can be added.");
674 if (ActivityManager.isLowRamDeviceStatic()) {
675 return false;
676 }
Fyodor Kupolovb6157992015-06-05 15:32:28 -0700677 if (!mContext.getPackageManager().hasSystemFeature(
678 PackageManager.FEATURE_MANAGED_USERS)) {
679 return false;
680 }
Nicolas Prevotb8186812015-08-06 15:00:03 +0100681 // Limit number of managed profiles that can be created
682 int managedProfilesCount = getProfiles(userId, true).size() - 1;
683 if (managedProfilesCount >= MAX_MANAGED_PROFILES) {
684 return false;
685 }
Nicolas Prevot12678a92015-05-13 12:15:03 -0700686 synchronized(mPackagesLock) {
Nicolas Prevotb8186812015-08-06 15:00:03 +0100687 UserInfo userInfo = getUserInfoLocked(userId);
688 if (!userInfo.canHaveProfile()) {
Nicolas Prevot12678a92015-05-13 12:15:03 -0700689 return false;
690 }
691 int usersCount = getAliveUsersExcludingGuestsCountLocked();
692 // We allow creating a managed profile in the special case where there is only one user.
693 return usersCount == 1 || usersCount < UserManager.getMaxSupportedUsers();
694 }
695 }
696
697 private int getAliveUsersExcludingGuestsCountLocked() {
Amith Yamasanif584f012014-05-19 17:57:25 -0700698 int aliveUserCount = 0;
699 final int totalUserCount = mUsers.size();
700 // Skip over users being removed
701 for (int i = 0; i < totalUserCount; i++) {
702 UserInfo user = mUsers.valueAt(i);
Amith Yamasani95ab7842014-08-11 17:09:26 -0700703 if (!mRemovingUserIds.get(user.id)
Amith Yamasani1df14732014-08-29 21:37:27 -0700704 && !user.isGuest() && !user.partial) {
Amith Yamasanif584f012014-05-19 17:57:25 -0700705 aliveUserCount++;
706 }
707 }
Nicolas Prevot12678a92015-05-13 12:15:03 -0700708 return aliveUserCount;
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700709 }
710
711 /**
Amith Yamasani195263742012-08-21 15:40:12 -0700712 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -0700713 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -0700714 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -0700715 *
716 * @param message used as message if SecurityException is thrown
717 * @throws SecurityException if the caller is not system or root
718 */
Amith Yamasanibe465322014-04-24 13:45:17 -0700719 private static final void checkManageUsersPermission(String message) {
Amith Yamasani258848d2012-08-10 17:06:33 -0700720 final int uid = Binder.getCallingUid();
Amith Yamasanibe465322014-04-24 13:45:17 -0700721 if (uid != Process.SYSTEM_UID && uid != 0
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400722 && ActivityManager.checkComponentPermission(
723 android.Manifest.permission.MANAGE_USERS,
Amith Yamasanibe465322014-04-24 13:45:17 -0700724 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
725 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
726 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400727 }
728
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700729 private static void checkSystemOrRoot(String message) {
730 final int uid = Binder.getCallingUid();
731 if (uid != Process.SYSTEM_UID && uid != 0) {
732 throw new SecurityException("Only system may call: " + message);
733 }
734 }
735
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700736 private void writeBitmapLocked(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700737 try {
738 File dir = new File(mUsersDir, Integer.toString(info.id));
739 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +0100740 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700741 if (!dir.exists()) {
742 dir.mkdir();
743 FileUtils.setPermissions(
744 dir.getPath(),
745 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
746 -1, -1);
747 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700748 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +0100749 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
750 && tmp.renameTo(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -0700751 info.iconPath = file.getAbsolutePath();
752 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700753 try {
754 os.close();
755 } catch (IOException ioe) {
756 // What the ... !
757 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100758 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700759 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700760 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700761 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700762 }
763
Amith Yamasani0b285492011-04-14 17:35:23 -0700764 /**
765 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
766 * cache it elsewhere.
767 * @return the array of user ids.
768 */
Dianne Hackborn1676c852012-09-10 14:52:30 -0700769 public int[] getUserIds() {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700770 synchronized (mPackagesLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700771 return mUserIds;
772 }
Amith Yamasani0b285492011-04-14 17:35:23 -0700773 }
774
Dianne Hackborn4428e172012-08-24 17:43:05 -0700775 int[] getUserIdsLPr() {
776 return mUserIds;
777 }
778
Amith Yamasani13593602012-03-22 16:16:17 -0700779 private void readUserListLocked() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700780 if (!mUserListFile.exists()) {
Amith Yamasani13593602012-03-22 16:16:17 -0700781 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700782 return;
783 }
784 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700785 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700786 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700787 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700788 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100789 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700790 int type;
791 while ((type = parser.next()) != XmlPullParser.START_TAG
792 && type != XmlPullParser.END_DOCUMENT) {
793 ;
794 }
795
796 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700797 Slog.e(LOG_TAG, "Unable to read user list");
Amith Yamasani13593602012-03-22 16:16:17 -0700798 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700799 return;
800 }
801
Amith Yamasani2a003292012-08-14 18:25:45 -0700802 mNextSerialNumber = -1;
803 if (parser.getName().equals(TAG_USERS)) {
804 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
805 if (lastSerialNumber != null) {
806 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
807 }
Amith Yamasani6f34b412012-10-22 18:19:27 -0700808 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
809 if (versionNumber != null) {
810 mUserVersion = Integer.parseInt(versionNumber);
811 }
Amith Yamasani2a003292012-08-14 18:25:45 -0700812 }
813
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700814 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530815 if (type == XmlPullParser.START_TAG) {
816 final String name = parser.getName();
817 if (name.equals(TAG_USER)) {
818 String id = parser.getAttributeValue(null, ATTR_ID);
819 UserInfo user = readUserLocked(Integer.parseInt(id));
Amith Yamasani6f34b412012-10-22 18:19:27 -0700820
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530821 if (user != null) {
822 mUsers.put(user.id, user);
823 if (mNextSerialNumber < 0 || mNextSerialNumber <= user.id) {
824 mNextSerialNumber = user.id + 1;
825 }
Amith Yamasani2a003292012-08-14 18:25:45 -0700826 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530827 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -0800828 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
829 && type != XmlPullParser.END_TAG) {
830 if (type == XmlPullParser.START_TAG) {
831 if (parser.getName().equals(TAG_RESTRICTIONS)) {
Makoto Onukia4f11972015-10-01 13:19:58 -0700832 UserRestrictionsUtils
833 .readRestrictions(parser, mGuestRestrictions);
Amith Yamasanida0b1682014-11-21 12:58:17 -0800834 }
835 break;
836 }
837 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700838 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700839 }
840 }
Amith Yamasani13593602012-03-22 16:16:17 -0700841 updateUserIdsLocked();
Amith Yamasani350962c2013-08-06 11:18:53 -0700842 upgradeIfNecessaryLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700843 } catch (IOException ioe) {
Amith Yamasani13593602012-03-22 16:16:17 -0700844 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700845 } catch (XmlPullParserException pe) {
Amith Yamasani13593602012-03-22 16:16:17 -0700846 fallbackToSingleUserLocked();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -0800847 } finally {
848 if (fis != null) {
849 try {
850 fis.close();
851 } catch (IOException e) {
852 }
853 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700854 }
855 }
856
Amith Yamasani6f34b412012-10-22 18:19:27 -0700857 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -0800858 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -0700859 */
Amith Yamasani350962c2013-08-06 11:18:53 -0700860 private void upgradeIfNecessaryLocked() {
Amith Yamasani6f34b412012-10-22 18:19:27 -0700861 int userVersion = mUserVersion;
862 if (userVersion < 1) {
863 // Assign a proper name for the owner, if not initialized correctly before
Xiaohui Chen47f07952015-10-02 14:40:27 -0700864 UserInfo user = mUsers.get(UserHandle.USER_SYSTEM);
Amith Yamasani6f34b412012-10-22 18:19:27 -0700865 if ("Primary".equals(user.name)) {
866 user.name = mContext.getResources().getString(com.android.internal.R.string.owner_name);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800867 scheduleWriteUserLocked(user);
Amith Yamasani6f34b412012-10-22 18:19:27 -0700868 }
869 userVersion = 1;
870 }
871
Amith Yamasanibc9625052012-11-15 14:39:18 -0800872 if (userVersion < 2) {
873 // Owner should be marked as initialized
Xiaohui Chen47f07952015-10-02 14:40:27 -0700874 UserInfo user = mUsers.get(UserHandle.USER_SYSTEM);
Amith Yamasanibc9625052012-11-15 14:39:18 -0800875 if ((user.flags & UserInfo.FLAG_INITIALIZED) == 0) {
876 user.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800877 scheduleWriteUserLocked(user);
Amith Yamasanibc9625052012-11-15 14:39:18 -0800878 }
879 userVersion = 2;
880 }
881
Amith Yamasani350962c2013-08-06 11:18:53 -0700882
Amith Yamasani5e486f52013-08-07 11:06:44 -0700883 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -0700884 userVersion = 4;
885 }
886
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700887 if (userVersion < 5) {
888 initDefaultGuestRestrictions();
889 userVersion = 5;
890 }
891
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700892 if (userVersion < 6) {
893 final boolean splitSystemUser = UserManager.isSplitSystemUser();
894 for (int i = 0; i < mUsers.size(); i++) {
895 UserInfo user = mUsers.valueAt(i);
896 // In non-split mode, only user 0 can have restricted profiles
897 if (!splitSystemUser && user.isRestricted()
898 && (user.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID)) {
899 user.restrictedProfileParentId = UserHandle.USER_SYSTEM;
900 scheduleWriteUserLocked(user);
901 }
902 }
903 userVersion = 6;
904 }
905
Amith Yamasani6f34b412012-10-22 18:19:27 -0700906 if (userVersion < USER_VERSION) {
907 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
908 + USER_VERSION);
909 } else {
910 mUserVersion = userVersion;
911 writeUserListLocked();
912 }
913 }
914
Amith Yamasani13593602012-03-22 16:16:17 -0700915 private void fallbackToSingleUserLocked() {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -0700916 int flags = UserInfo.FLAG_INITIALIZED;
917 // In split system user mode, the admin and primary flags are assigned to the first human
918 // user.
919 if (!UserManager.isSplitSystemUser()) {
920 flags |= UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY;
921 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700922 // Create the system user
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700923 UserInfo system = new UserInfo(UserHandle.USER_SYSTEM,
Amith Yamasani6f34b412012-10-22 18:19:27 -0700924 mContext.getResources().getString(com.android.internal.R.string.owner_name), null,
Xiaohui Chenb31e14a2015-07-13 16:04:55 -0700925 flags);
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700926 mUsers.put(system.id, system);
Amith Yamasani634cf312012-10-04 17:34:21 -0700927 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -0400928 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -0800929
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -0500930 Bundle restrictions = new Bundle();
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700931 mUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions);
Amith Yamasani67df64b2012-12-14 12:09:36 -0800932
Amith Yamasani13593602012-03-22 16:16:17 -0700933 updateUserIdsLocked();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700934 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700935
Amith Yamasani13593602012-03-22 16:16:17 -0700936 writeUserListLocked();
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700937 writeUserLocked(system);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700938 }
939
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800940 private void scheduleWriteUserLocked(UserInfo userInfo) {
941 if (!mHandler.hasMessages(WRITE_USER_MSG, userInfo)) {
942 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, userInfo);
943 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
944 }
945 }
946
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700947 /*
948 * Writes the user file in this format:
949 *
950 * <user flags="20039023" id="0">
951 * <name>Primary</name>
952 * </user>
953 */
Amith Yamasani13593602012-03-22 16:16:17 -0700954 private void writeUserLocked(UserInfo userInfo) {
Amith Yamasani742a6712011-05-04 14:49:28 -0700955 FileOutputStream fos = null;
Amith Yamasanifc95e702013-09-26 13:20:17 -0700956 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userInfo.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700957 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700958 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700959 final BufferedOutputStream bos = new BufferedOutputStream(fos);
960
961 // XmlSerializer serializer = XmlUtils.serializerInstance();
962 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100963 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700964 serializer.startDocument(null, true);
965 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
966
967 serializer.startTag(null, TAG_USER);
968 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
Amith Yamasani2a003292012-08-14 18:25:45 -0700969 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700970 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Amith Yamasani920ace02012-09-20 22:15:37 -0700971 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
972 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
973 Long.toString(userInfo.lastLoggedInTime));
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700974 if (userInfo.iconPath != null) {
975 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
976 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700977 if (userInfo.partial) {
978 serializer.attribute(null, ATTR_PARTIAL, "true");
979 }
Adam Lesinskieddeb492014-09-08 17:50:03 -0700980 if (userInfo.guestToRemove) {
981 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
982 }
Kenny Guy2a764942014-04-02 13:29:20 +0100983 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
984 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
985 Integer.toString(userInfo.profileGroupId));
Kenny Guya52dc3e2014-02-11 15:33:14 +0000986 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700987 if (userInfo.restrictedProfileParentId != UserInfo.NO_PROFILE_GROUP_ID) {
988 serializer.attribute(null, ATTR_RESTRICTED_PROFILE_PARENT_ID,
989 Integer.toString(userInfo.restrictedProfileParentId));
990 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700991 serializer.startTag(null, TAG_NAME);
992 serializer.text(userInfo.name);
993 serializer.endTag(null, TAG_NAME);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800994 Bundle restrictions = mUserRestrictions.get(userInfo.id);
995 if (restrictions != null) {
Makoto Onukia4f11972015-10-01 13:19:58 -0700996 UserRestrictionsUtils.writeRestrictions(serializer, restrictions, TAG_RESTRICTIONS);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800997 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700998 serializer.endTag(null, TAG_USER);
999
1000 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001001 userFile.finishWrite(fos);
1002 } catch (Exception ioe) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001003 Slog.e(LOG_TAG, "Error writing user info " + userInfo.id + "\n" + ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -07001004 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001005 }
1006 }
1007
1008 /*
1009 * Writes the user list file in this format:
1010 *
Amith Yamasani2a003292012-08-14 18:25:45 -07001011 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001012 * <user id="0"></user>
1013 * <user id="2"></user>
1014 * </users>
1015 */
Amith Yamasani13593602012-03-22 16:16:17 -07001016 private void writeUserListLocked() {
Amith Yamasani742a6712011-05-04 14:49:28 -07001017 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001018 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001019 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001020 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001021 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1022
1023 // XmlSerializer serializer = XmlUtils.serializerInstance();
1024 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001025 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001026 serializer.startDocument(null, true);
1027 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1028
1029 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -07001030 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -07001031 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001032
Adam Lesinskieddeb492014-09-08 17:50:03 -07001033 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Makoto Onukia4f11972015-10-01 13:19:58 -07001034 UserRestrictionsUtils
1035 .writeRestrictions(serializer, mGuestRestrictions, TAG_RESTRICTIONS);
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301036 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Amith Yamasani515d4062015-09-28 11:30:06 -07001037 final int userSize = mUsers.size();
1038 for (int i = 0; i < userSize; i++) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001039 UserInfo user = mUsers.valueAt(i);
1040 serializer.startTag(null, TAG_USER);
1041 serializer.attribute(null, ATTR_ID, Integer.toString(user.id));
1042 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001043 }
1044
1045 serializer.endTag(null, TAG_USERS);
1046
1047 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001048 userListFile.finishWrite(fos);
1049 } catch (Exception e) {
1050 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -07001051 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001052 }
1053 }
1054
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001055 private UserInfo readUserLocked(int id) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001056 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -07001057 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001058 String name = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001059 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -07001060 long creationTime = 0L;
1061 long lastLoggedInTime = 0L;
Kenny Guy2a764942014-04-02 13:29:20 +01001062 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001063 int restrictedProfileParentId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001064 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001065 boolean guestToRemove = false;
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001066 Bundle restrictions = new Bundle();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001067
1068 FileInputStream fis = null;
1069 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001070 AtomicFile userFile =
Amith Yamasanifc95e702013-09-26 13:20:17 -07001071 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
Amith Yamasani2a003292012-08-14 18:25:45 -07001072 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001073 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001074 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001075 int type;
1076 while ((type = parser.next()) != XmlPullParser.START_TAG
1077 && type != XmlPullParser.END_DOCUMENT) {
1078 ;
1079 }
1080
1081 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001082 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001083 return null;
1084 }
1085
1086 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001087 int storedId = readIntAttribute(parser, ATTR_ID, -1);
1088 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001089 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001090 return null;
1091 }
Amith Yamasani920ace02012-09-20 22:15:37 -07001092 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
1093 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001094 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -07001095 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
1096 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Kenny Guy2a764942014-04-02 13:29:20 +01001097 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
1098 UserInfo.NO_PROFILE_GROUP_ID);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001099 restrictedProfileParentId = readIntAttribute(parser,
1100 ATTR_RESTRICTED_PROFILE_PARENT_ID, UserInfo.NO_PROFILE_GROUP_ID);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001101 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
1102 if ("true".equals(valueString)) {
1103 partial = true;
1104 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001105 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
1106 if ("true".equals(valueString)) {
1107 guestToRemove = true;
1108 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001109
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001110 int outerDepth = parser.getDepth();
1111 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1112 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1113 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1114 continue;
1115 }
1116 String tag = parser.getName();
1117 if (TAG_NAME.equals(tag)) {
1118 type = parser.next();
1119 if (type == XmlPullParser.TEXT) {
1120 name = parser.getText();
1121 }
1122 } else if (TAG_RESTRICTIONS.equals(tag)) {
Makoto Onukia4f11972015-10-01 13:19:58 -07001123 UserRestrictionsUtils.readRestrictions(parser, restrictions);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001124 }
1125 }
1126 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001127
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001128 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -07001129 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -07001130 userInfo.creationTime = creationTime;
1131 userInfo.lastLoggedInTime = lastLoggedInTime;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001132 userInfo.partial = partial;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001133 userInfo.guestToRemove = guestToRemove;
Kenny Guy2a764942014-04-02 13:29:20 +01001134 userInfo.profileGroupId = profileGroupId;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001135 userInfo.restrictedProfileParentId = restrictedProfileParentId;
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001136 mUserRestrictions.append(id, restrictions);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001137 return userInfo;
1138
1139 } catch (IOException ioe) {
1140 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001141 } finally {
1142 if (fis != null) {
1143 try {
1144 fis.close();
1145 } catch (IOException e) {
1146 }
1147 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001148 }
1149 return null;
1150 }
1151
Amith Yamasani920ace02012-09-20 22:15:37 -07001152 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
1153 String valueString = parser.getAttributeValue(null, attr);
1154 if (valueString == null) return defaultValue;
1155 try {
1156 return Integer.parseInt(valueString);
1157 } catch (NumberFormatException nfe) {
1158 return defaultValue;
1159 }
1160 }
1161
1162 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
1163 String valueString = parser.getAttributeValue(null, attr);
1164 if (valueString == null) return defaultValue;
1165 try {
1166 return Long.parseLong(valueString);
1167 } catch (NumberFormatException nfe) {
1168 return defaultValue;
1169 }
1170 }
1171
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001172 private boolean isPackageInstalled(String pkg, int userId) {
1173 final ApplicationInfo info = mPm.getApplicationInfo(pkg,
1174 PackageManager.GET_UNINSTALLED_PACKAGES,
1175 userId);
1176 if (info == null || (info.flags&ApplicationInfo.FLAG_INSTALLED) == 0) {
1177 return false;
1178 }
1179 return true;
1180 }
1181
Amith Yamasanib82add22013-07-09 11:24:44 -07001182 /**
Kenny Guyd21b2182014-07-17 16:38:55 +01001183 * Removes all the restrictions files (res_<packagename>) for a given user.
Amith Yamasanib82add22013-07-09 11:24:44 -07001184 * Does not do any permissions checking.
1185 */
Kenny Guyd21b2182014-07-17 16:38:55 +01001186 private void cleanAppRestrictions(int userId) {
Amith Yamasanib82add22013-07-09 11:24:44 -07001187 synchronized (mPackagesLock) {
1188 File dir = Environment.getUserSystemDirectory(userId);
1189 String[] files = dir.list();
1190 if (files == null) return;
1191 for (String fileName : files) {
1192 if (fileName.startsWith(RESTRICTIONS_FILE_PREFIX)) {
1193 File resFile = new File(dir, fileName);
1194 if (resFile.exists()) {
Kenny Guyd21b2182014-07-17 16:38:55 +01001195 resFile.delete();
Amith Yamasanib82add22013-07-09 11:24:44 -07001196 }
1197 }
1198 }
1199 }
1200 }
1201
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001202 /**
1203 * Removes the app restrictions file for a specific package and user id, if it exists.
1204 */
1205 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
1206 synchronized (mPackagesLock) {
1207 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07001208 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001209 if (resFile.exists()) {
1210 resFile.delete();
1211 }
1212 }
1213 }
1214
Kenny Guya52dc3e2014-02-11 15:33:14 +00001215 @Override
Kenny Guy2a764942014-04-02 13:29:20 +01001216 public UserInfo createProfileForUser(String name, int flags, int userId) {
Kenny Guya52dc3e2014-02-11 15:33:14 +00001217 checkManageUsersPermission("Only the system can create users");
Kenny Guy2a764942014-04-02 13:29:20 +01001218 return createUserInternal(name, flags, userId);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001219 }
1220
Amith Yamasani258848d2012-08-10 17:06:33 -07001221 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07001222 public UserInfo createUser(String name, int flags) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001223 checkManageUsersPermission("Only the system can create users");
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001224 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001225 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001226
Jessica Hummelbe81c802014-04-22 15:49:22 +01001227 private UserInfo createUserInternal(String name, int flags, int parentId) {
Julia Reynolds75175022014-06-26 16:35:00 -04001228 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1229 UserManager.DISALLOW_ADD_USER, false)) {
1230 Log.w(LOG_TAG, "Cannot add user. DISALLOW_ADD_USER is enabled.");
1231 return null;
1232 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001233 if (ActivityManager.isLowRamDeviceStatic()) {
1234 return null;
1235 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07001236 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001237 final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001238 final boolean isRestricted = (flags & UserInfo.FLAG_RESTRICTED) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001239 final long ident = Binder.clearCallingIdentity();
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001240 UserInfo userInfo = null;
Amith Yamasanibb054c92015-07-09 14:16:27 -07001241 final int userId;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001242 try {
1243 synchronized (mInstallLock) {
1244 synchronized (mPackagesLock) {
Jessica Hummelbe81c802014-04-22 15:49:22 +01001245 UserInfo parent = null;
1246 if (parentId != UserHandle.USER_NULL) {
1247 parent = getUserInfoLocked(parentId);
1248 if (parent == null) return null;
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001249 }
Nicolas Prevotb8186812015-08-06 15:00:03 +01001250 if (isManagedProfile && !canAddMoreManagedProfiles(parentId)) {
1251 Log.e(LOG_TAG, "Cannot add more managed profiles for user " + parentId);
Nicolas Prevot12678a92015-05-13 12:15:03 -07001252 return null;
1253 }
1254 if (!isGuest && !isManagedProfile && isUserLimitReachedLocked()) {
1255 // If we're not adding a guest user or a managed profile and the limit has
1256 // been reached, cannot add a user.
Amith Yamasani95ab7842014-08-11 17:09:26 -07001257 return null;
1258 }
1259 // If we're adding a guest and there already exists one, bail.
Adam Lesinskieddeb492014-09-08 17:50:03 -07001260 if (isGuest && findCurrentGuestUserLocked() != null) {
Amith Yamasani95ab7842014-08-11 17:09:26 -07001261 return null;
1262 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001263 // In legacy mode, restricted profile's parent can only be the owner user
1264 if (isRestricted && !UserManager.isSplitSystemUser()
1265 && (parentId != UserHandle.USER_SYSTEM)) {
1266 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
1267 return null;
1268 }
1269 if (isRestricted && UserManager.isSplitSystemUser()) {
1270 if (parent == null) {
1271 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be "
1272 + "specified");
1273 return null;
1274 }
1275 if (!parent.canHaveProfile()) {
1276 Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be "
1277 + "created for the specified parent user id " + parentId);
1278 return null;
1279 }
1280 }
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001281 // In split system user mode, we assign the first human user the primary flag.
Xiaohui Chen203243a2015-07-16 11:55:47 -07001282 // And if there is no device owner, we also assign the admin flag to primary
1283 // user.
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001284 if (UserManager.isSplitSystemUser()
Xiaohui Chen203243a2015-07-16 11:55:47 -07001285 && !isGuest && !isManagedProfile && getPrimaryUser() == null) {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001286 flags |= UserInfo.FLAG_PRIMARY;
Xiaohui Chen203243a2015-07-16 11:55:47 -07001287 DevicePolicyManager devicePolicyManager = (DevicePolicyManager)
1288 mContext.getSystemService(Context.DEVICE_POLICY_SERVICE);
1289 if (devicePolicyManager == null
1290 || devicePolicyManager.getDeviceOwner() == null) {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001291 flags |= UserInfo.FLAG_ADMIN;
1292 }
1293 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07001294 userId = getNextAvailableIdLocked();
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001295 userInfo = new UserInfo(userId, name, null, flags);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001296 userInfo.serialNumber = mNextSerialNumber++;
Amith Yamasani920ace02012-09-20 22:15:37 -07001297 long now = System.currentTimeMillis();
1298 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001299 userInfo.partial = true;
Amith Yamasani16389312012-10-17 21:20:14 -07001300 Environment.getUserSystemDirectory(userInfo.id).mkdirs();
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001301 mUsers.put(userId, userInfo);
1302 writeUserListLocked();
Jessica Hummelbe81c802014-04-22 15:49:22 +01001303 if (parent != null) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001304 if (isManagedProfile) {
1305 if (parent.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
1306 parent.profileGroupId = parent.id;
1307 scheduleWriteUserLocked(parent);
1308 }
1309 userInfo.profileGroupId = parent.profileGroupId;
1310 } else if (isRestricted) {
1311 if (!parent.canHaveProfile()) {
1312 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
1313 }
1314 if (parent.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) {
1315 parent.restrictedProfileParentId = parent.id;
1316 scheduleWriteUserLocked(parent);
1317 }
1318 userInfo.restrictedProfileParentId = parent.restrictedProfileParentId;
Kenny Guya52dc3e2014-02-11 15:33:14 +00001319 }
Kenny Guya52dc3e2014-02-11 15:33:14 +00001320 }
Jeff Sharkey6dce4962015-07-03 18:08:41 -07001321 final StorageManager storage = mContext.getSystemService(StorageManager.class);
1322 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
1323 final String volumeUuid = vol.getFsUuid();
1324 try {
1325 final File userDir = Environment.getDataUserDirectory(volumeUuid,
1326 userId);
Jeff Sharkey3bb8c852015-07-06 16:44:23 -07001327 prepareUserDirectory(mContext, volumeUuid, userId);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07001328 enforceSerialNumber(userDir, userInfo.serialNumber);
1329 } catch (IOException e) {
1330 Log.wtf(LOG_TAG, "Failed to create user directory on " + volumeUuid, e);
1331 }
1332 }
1333 mPm.createNewUserLILPw(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001334 userInfo.partial = false;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001335 scheduleWriteUserLocked(userInfo);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001336 updateUserIdsLocked();
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001337 Bundle restrictions = new Bundle();
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001338 mUserRestrictions.append(userId, restrictions);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001339 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07001340 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07001341 mPm.newUserCreated(userId);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001342 if (userInfo != null) {
1343 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
1344 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userInfo.id);
1345 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
1346 android.Manifest.permission.MANAGE_USERS);
1347 }
1348 } finally {
1349 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07001350 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001351 return userInfo;
1352 }
1353
Amith Yamasani0b285492011-04-14 17:35:23 -07001354 /**
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07001355 * @hide
1356 */
1357 public UserInfo createRestrictedProfile(String name, int parentUserId) {
1358 checkManageUsersPermission("setupRestrictedProfile");
1359 final UserInfo user = createProfileForUser(name, UserInfo.FLAG_RESTRICTED, parentUserId);
1360 if (user == null) {
1361 return null;
1362 }
1363 setUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, true, user.id);
1364 // Change the setting before applying the DISALLOW_SHARE_LOCATION restriction, otherwise
1365 // the putIntForUser() will fail.
1366 android.provider.Settings.Secure.putIntForUser(mContext.getContentResolver(),
1367 android.provider.Settings.Secure.LOCATION_MODE,
1368 android.provider.Settings.Secure.LOCATION_MODE_OFF, user.id);
1369 setUserRestriction(UserManager.DISALLOW_SHARE_LOCATION, true, user.id);
1370 return user;
1371 }
1372
1373 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07001374 * Find the current guest user. If the Guest user is partial,
1375 * then do not include it in the results as it is about to die.
Adam Lesinskieddeb492014-09-08 17:50:03 -07001376 */
1377 private UserInfo findCurrentGuestUserLocked() {
1378 final int size = mUsers.size();
1379 for (int i = 0; i < size; i++) {
1380 final UserInfo user = mUsers.valueAt(i);
1381 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
1382 return user;
1383 }
1384 }
1385 return null;
1386 }
1387
1388 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07001389 * Mark this guest user for deletion to allow us to create another guest
1390 * and switch to that user before actually removing this guest.
1391 * @param userHandle the userid of the current guest
1392 * @return whether the user could be marked for deletion
1393 */
1394 public boolean markGuestForDeletion(int userHandle) {
1395 checkManageUsersPermission("Only the system can remove users");
1396 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1397 UserManager.DISALLOW_REMOVE_USER, false)) {
1398 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1399 return false;
1400 }
1401
1402 long ident = Binder.clearCallingIdentity();
1403 try {
1404 final UserInfo user;
1405 synchronized (mPackagesLock) {
1406 user = mUsers.get(userHandle);
1407 if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
1408 return false;
1409 }
1410 if (!user.isGuest()) {
1411 return false;
1412 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001413 // We set this to a guest user that is to be removed. This is a temporary state
1414 // where we are allowed to add new Guest users, even if this one is still not
1415 // removed. This user will still show up in getUserInfo() calls.
1416 // If we don't get around to removing this Guest user, it will be purged on next
1417 // startup.
1418 user.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07001419 // Mark it as disabled, so that it isn't returned any more when
1420 // profiles are queried.
1421 user.flags |= UserInfo.FLAG_DISABLED;
Amith Yamasani1df14732014-08-29 21:37:27 -07001422 writeUserLocked(user);
1423 }
1424 } finally {
1425 Binder.restoreCallingIdentity(ident);
1426 }
1427 return true;
1428 }
1429
1430 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07001431 * Removes a user and all data directories created for that user. This method should be called
1432 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001433 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07001434 */
Amith Yamasani258848d2012-08-10 17:06:33 -07001435 public boolean removeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001436 checkManageUsersPermission("Only the system can remove users");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04001437 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1438 UserManager.DISALLOW_REMOVE_USER, false)) {
1439 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1440 return false;
1441 }
1442
Kenny Guyee58b4f2014-05-23 15:19:53 +01001443 long ident = Binder.clearCallingIdentity();
1444 try {
1445 final UserInfo user;
Fyodor Kupolov0df68cd2015-10-01 13:54:22 -07001446 int currentUser = ActivityManager.getCurrentUser();
1447 if (currentUser == userHandle) {
1448 Log.w(LOG_TAG, "Current user cannot be removed");
1449 return false;
1450 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01001451 synchronized (mPackagesLock) {
1452 user = mUsers.get(userHandle);
Kenny Guy17c9d692014-06-13 13:51:42 +01001453 if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01001454 return false;
1455 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08001456
1457 // We remember deleted user IDs to prevent them from being
1458 // reused during the current boot; they can still be reused
1459 // after a reboot.
Kenny Guyee58b4f2014-05-23 15:19:53 +01001460 mRemovingUserIds.put(userHandle, true);
Jeff Sharkey6eb09392014-11-14 15:57:59 -08001461
Kenny Guyee58b4f2014-05-23 15:19:53 +01001462 try {
1463 mAppOpsService.removeUser(userHandle);
1464 } catch (RemoteException e) {
1465 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
1466 }
1467 // Set this to a partially created user, so that the user will be purged
1468 // on next startup, in case the runtime stops now before stopping and
1469 // removing the user completely.
1470 user.partial = true;
1471 // Mark it as disabled, so that it isn't returned any more when
1472 // profiles are queried.
1473 user.flags |= UserInfo.FLAG_DISABLED;
1474 writeUserLocked(user);
1475 }
1476
1477 if (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
1478 && user.isManagedProfile()) {
1479 // Send broadcast to notify system that the user removed was a
1480 // managed user.
1481 sendProfileRemovedBroadcast(user.profileGroupId, user.id);
1482 }
1483
1484 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
1485 int res;
1486 try {
1487 res = ActivityManagerNative.getDefault().stopUser(userHandle,
1488 new IStopUserCallback.Stub() {
1489 @Override
1490 public void userStopped(int userId) {
1491 finishRemoveUser(userId);
1492 }
1493 @Override
1494 public void userStopAborted(int userId) {
1495 }
1496 });
1497 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001498 return false;
1499 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01001500 return res == ActivityManager.USER_OP_SUCCESS;
1501 } finally {
1502 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001503 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001504 }
1505
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001506 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07001507 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001508 // Let other services shutdown any activity and clean up their state before completely
1509 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001510 long ident = Binder.clearCallingIdentity();
1511 try {
1512 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
1513 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001514 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
1515 android.Manifest.permission.MANAGE_USERS,
1516
1517 new BroadcastReceiver() {
1518 @Override
1519 public void onReceive(Context context, Intent intent) {
1520 if (DBG) {
1521 Slog.i(LOG_TAG,
1522 "USER_REMOVED broadcast sent, cleaning up user data "
1523 + userHandle);
1524 }
1525 new Thread() {
1526 public void run() {
Amith Yamasani515d4062015-09-28 11:30:06 -07001527 // Clean up any ActivityManager state
1528 LocalServices.getService(ActivityManagerInternal.class)
1529 .onUserRemoved(userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001530 synchronized (mInstallLock) {
1531 synchronized (mPackagesLock) {
1532 removeUserStateLocked(userHandle);
1533 }
1534 }
1535 }
1536 }.start();
1537 }
1538 },
1539
1540 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001541 } finally {
1542 Binder.restoreCallingIdentity(ident);
1543 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001544 }
1545
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001546 private void removeUserStateLocked(final int userHandle) {
Paul Crowley85e4e812015-05-19 12:42:00 +01001547 mContext.getSystemService(StorageManager.class)
1548 .deleteUserKey(userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001549 // Cleanup package manager settings
Amith Yamasanidda003f2014-08-28 18:06:51 -07001550 mPm.cleanUpUserLILPw(this, userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001551
1552 // Remove this user from the list
1553 mUsers.remove(userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001554 // Remove user file
Amith Yamasanifc95e702013-09-26 13:20:17 -07001555 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001556 userFile.delete();
1557 // Update the user list
1558 writeUserListLocked();
1559 updateUserIdsLocked();
1560 removeDirectoryRecursive(Environment.getUserSystemDirectory(userHandle));
1561 }
1562
Amith Yamasani61f57372012-08-31 12:12:28 -07001563 private void removeDirectoryRecursive(File parent) {
1564 if (parent.isDirectory()) {
1565 String[] files = parent.list();
1566 for (String filename : files) {
1567 File child = new File(parent, filename);
1568 removeDirectoryRecursive(child);
1569 }
1570 }
1571 parent.delete();
1572 }
1573
Kenny Guyf8d3a232014-05-15 16:09:52 +01001574 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01001575 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01001576 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
1577 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01001578 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
1579 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01001580 }
1581
Amith Yamasani2a003292012-08-14 18:25:45 -07001582 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001583 public Bundle getApplicationRestrictions(String packageName) {
1584 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
1585 }
1586
1587 @Override
1588 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001589 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07001590 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001591 checkManageUsersPermission("Only system can get restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001592 }
1593 synchronized (mPackagesLock) {
1594 // Read the restrictions from XML
1595 return readApplicationRestrictionsLocked(packageName, userId);
1596 }
1597 }
1598
1599 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001600 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001601 int userId) {
1602 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07001603 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001604 checkManageUsersPermission("Only system can set restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001605 }
1606 synchronized (mPackagesLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01001607 if (restrictions == null || restrictions.isEmpty()) {
1608 cleanAppRestrictionsForPackage(packageName, userId);
1609 } else {
1610 // Write the restrictions to XML
1611 writeApplicationRestrictionsLocked(packageName, restrictions, userId);
1612 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001613 }
Robin Lee66e5d962014-04-09 16:44:21 +01001614
Kenny Guyd21b2182014-07-17 16:38:55 +01001615 if (isPackageInstalled(packageName, userId)) {
1616 // Notify package of changes via an intent - only sent to explicitly registered receivers.
1617 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
1618 changeIntent.setPackage(packageName);
1619 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
1620 mContext.sendBroadcastAsUser(changeIntent, new UserHandle(userId));
1621 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001622 }
1623
Amith Yamasani655d0e22013-06-12 14:19:10 -07001624 @Override
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001625 public void removeRestrictions() {
Amith Yamasanibe465322014-04-24 13:45:17 -07001626 checkManageUsersPermission("Only system can remove restrictions");
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001627 final int userHandle = UserHandle.getCallingUserId();
Amith Yamasani5e486f52013-08-07 11:06:44 -07001628 removeRestrictionsForUser(userHandle, true);
Amith Yamasani350962c2013-08-06 11:18:53 -07001629 }
1630
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001631 private void removeRestrictionsForUser(final int userHandle, boolean unhideApps) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001632 synchronized (mPackagesLock) {
1633 // Remove all user restrictions
1634 setUserRestrictions(new Bundle(), userHandle);
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001635 // Remove any app restrictions
Kenny Guyd21b2182014-07-17 16:38:55 +01001636 cleanAppRestrictions(userHandle);
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001637 }
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001638 if (unhideApps) {
1639 unhideAllInstalledAppsForUser(userHandle);
Amith Yamasani5e486f52013-08-07 11:06:44 -07001640 }
1641 }
1642
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001643 private void unhideAllInstalledAppsForUser(final int userHandle) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001644 mHandler.post(new Runnable() {
1645 @Override
1646 public void run() {
1647 List<ApplicationInfo> apps =
1648 mPm.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES,
1649 userHandle).getList();
1650 final long ident = Binder.clearCallingIdentity();
1651 try {
1652 for (ApplicationInfo appInfo : apps) {
1653 if ((appInfo.flags & ApplicationInfo.FLAG_INSTALLED) != 0
Alex Klyubinb9f8a522015-02-03 11:12:59 -08001654 && (appInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HIDDEN)
1655 != 0) {
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001656 mPm.setApplicationHiddenSettingAsUser(appInfo.packageName, false,
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001657 userHandle);
1658 }
1659 }
1660 } finally {
1661 Binder.restoreCallingIdentity(ident);
1662 }
1663 }
1664 });
1665 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001666 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07001667 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001668 try {
1669 return mContext.getPackageManager().getApplicationInfo(packageName,
1670 PackageManager.GET_UNINSTALLED_PACKAGES).uid;
1671 } catch (NameNotFoundException nnfe) {
1672 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07001673 } finally {
1674 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001675 }
1676 }
1677
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001678 private Bundle readApplicationRestrictionsLocked(String packageName,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001679 int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001680 AtomicFile restrictionsFile =
1681 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
1682 packageToRestrictionsFileName(packageName)));
1683 return readApplicationRestrictionsLocked(restrictionsFile);
1684 }
1685
1686 @VisibleForTesting
1687 static Bundle readApplicationRestrictionsLocked(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001688 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001689 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07001690 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07001691 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07001692 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001693
1694 FileInputStream fis = null;
1695 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001696 fis = restrictionsFile.openRead();
1697 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001698 parser.setInput(fis, StandardCharsets.UTF_8.name());
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001699 XmlUtils.nextElement(parser);
1700 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001701 Slog.e(LOG_TAG, "Unable to read restrictions file "
1702 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001703 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001704 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001705 while (parser.next() != XmlPullParser.END_DOCUMENT) {
1706 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001707 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001708 } catch (IOException|XmlPullParserException e) {
1709 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001710 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001711 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001712 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001713 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001714 }
1715
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001716 private static void readEntry(Bundle restrictions, ArrayList<String> values,
1717 XmlPullParser parser) throws XmlPullParserException, IOException {
1718 int type = parser.getEventType();
1719 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
1720 String key = parser.getAttributeValue(null, ATTR_KEY);
1721 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
1722 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
1723 if (multiple != null) {
1724 values.clear();
1725 int count = Integer.parseInt(multiple);
1726 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1727 if (type == XmlPullParser.START_TAG
1728 && parser.getName().equals(TAG_VALUE)) {
1729 values.add(parser.nextText().trim());
1730 count--;
1731 }
1732 }
1733 String [] valueStrings = new String[values.size()];
1734 values.toArray(valueStrings);
1735 restrictions.putStringArray(key, valueStrings);
1736 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
1737 restrictions.putBundle(key, readBundleEntry(parser, values));
1738 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
1739 final int outerDepth = parser.getDepth();
1740 ArrayList<Bundle> bundleList = new ArrayList<>();
1741 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
1742 Bundle childBundle = readBundleEntry(parser, values);
1743 bundleList.add(childBundle);
1744 }
1745 restrictions.putParcelableArray(key,
1746 bundleList.toArray(new Bundle[bundleList.size()]));
1747 } else {
1748 String value = parser.nextText().trim();
1749 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
1750 restrictions.putBoolean(key, Boolean.parseBoolean(value));
1751 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
1752 restrictions.putInt(key, Integer.parseInt(value));
1753 } else {
1754 restrictions.putString(key, value);
1755 }
1756 }
1757 }
1758 }
1759
1760 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
1761 throws IOException, XmlPullParserException {
1762 Bundle childBundle = new Bundle();
1763 final int outerDepth = parser.getDepth();
1764 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
1765 readEntry(childBundle, values, parser);
1766 }
1767 return childBundle;
1768 }
1769
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001770 private void writeApplicationRestrictionsLocked(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001771 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001772 AtomicFile restrictionsFile = new AtomicFile(
1773 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07001774 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001775 writeApplicationRestrictionsLocked(restrictions, restrictionsFile);
1776 }
1777
1778 @VisibleForTesting
1779 static void writeApplicationRestrictionsLocked(Bundle restrictions,
1780 AtomicFile restrictionsFile) {
1781 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001782 try {
1783 fos = restrictionsFile.startWrite();
1784 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1785
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001786 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001787 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001788 serializer.startDocument(null, true);
1789 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1790
1791 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001792 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001793 serializer.endTag(null, TAG_RESTRICTIONS);
1794
1795 serializer.endDocument();
1796 restrictionsFile.finishWrite(fos);
1797 } catch (Exception e) {
1798 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001799 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
1800 }
1801 }
1802
1803 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
1804 throws IOException {
1805 for (String key : restrictions.keySet()) {
1806 Object value = restrictions.get(key);
1807 serializer.startTag(null, TAG_ENTRY);
1808 serializer.attribute(null, ATTR_KEY, key);
1809
1810 if (value instanceof Boolean) {
1811 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
1812 serializer.text(value.toString());
1813 } else if (value instanceof Integer) {
1814 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
1815 serializer.text(value.toString());
1816 } else if (value == null || value instanceof String) {
1817 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
1818 serializer.text(value != null ? (String) value : "");
1819 } else if (value instanceof Bundle) {
1820 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
1821 writeBundle((Bundle) value, serializer);
1822 } else if (value instanceof Parcelable[]) {
1823 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
1824 Parcelable[] array = (Parcelable[]) value;
1825 for (Parcelable parcelable : array) {
1826 if (!(parcelable instanceof Bundle)) {
1827 throw new IllegalArgumentException("bundle-array can only hold Bundles");
1828 }
1829 serializer.startTag(null, TAG_ENTRY);
1830 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
1831 writeBundle((Bundle) parcelable, serializer);
1832 serializer.endTag(null, TAG_ENTRY);
1833 }
1834 } else {
1835 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
1836 String[] values = (String[]) value;
1837 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
1838 for (String choice : values) {
1839 serializer.startTag(null, TAG_VALUE);
1840 serializer.text(choice != null ? choice : "");
1841 serializer.endTag(null, TAG_VALUE);
1842 }
1843 }
1844 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001845 }
1846 }
1847
1848 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07001849 public int getUserSerialNumber(int userHandle) {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001850 synchronized (mPackagesLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001851 if (!exists(userHandle)) return -1;
Amith Yamasani195263742012-08-21 15:40:12 -07001852 return getUserInfoLocked(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07001853 }
1854 }
1855
1856 @Override
1857 public int getUserHandle(int userSerialNumber) {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001858 synchronized (mPackagesLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001859 for (int userId : mUserIds) {
Kenny Guy945f8832015-02-10 15:17:26 +00001860 UserInfo info = getUserInfoLocked(userId);
1861 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07001862 }
1863 // Not found
1864 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07001865 }
1866 }
1867
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07001868 @Override
1869 public long getUserCreationTime(int userHandle) {
1870 int callingUserId = UserHandle.getCallingUserId();
1871 UserInfo userInfo = null;
1872 synchronized (mPackagesLock) {
1873 if (callingUserId == userHandle) {
1874 userInfo = getUserInfoLocked(userHandle);
1875 } else {
1876 UserInfo parent = getProfileParentLocked(userHandle);
1877 if (parent != null && parent.id == callingUserId) {
1878 userInfo = getUserInfoLocked(userHandle);
1879 }
1880 }
1881 }
1882 if (userInfo == null) {
1883 throw new SecurityException("userHandle can only be the calling user or a managed "
1884 + "profile associated with this user");
1885 }
1886 return userInfo.creationTime;
1887 }
1888
Amith Yamasani0b285492011-04-14 17:35:23 -07001889 /**
1890 * Caches the list of user ids in an array, adjusting the array size when necessary.
1891 */
Amith Yamasani13593602012-03-22 16:16:17 -07001892 private void updateUserIdsLocked() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001893 int num = 0;
Amith Yamasani515d4062015-09-28 11:30:06 -07001894 final int userSize = mUsers.size();
1895 for (int i = 0; i < userSize; i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001896 if (!mUsers.valueAt(i).partial) {
1897 num++;
1898 }
1899 }
Amith Yamasani16389312012-10-17 21:20:14 -07001900 final int[] newUsers = new int[num];
1901 int n = 0;
Amith Yamasani515d4062015-09-28 11:30:06 -07001902 for (int i = 0; i < userSize; i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001903 if (!mUsers.valueAt(i).partial) {
Amith Yamasani16389312012-10-17 21:20:14 -07001904 newUsers[n++] = mUsers.keyAt(i);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001905 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001906 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001907 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07001908 }
1909
1910 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001911 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasani920ace02012-09-20 22:15:37 -07001912 * @param userId the user that was just foregrounded
1913 */
Amith Yamasani06bf8242015-05-08 16:36:21 -07001914 public void onUserForeground(int userId) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001915 synchronized (mPackagesLock) {
1916 UserInfo user = mUsers.get(userId);
1917 long now = System.currentTimeMillis();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001918 if (user == null || user.partial) {
1919 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
1920 return;
1921 }
1922 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001923 user.lastLoggedInTime = now;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001924 scheduleWriteUserLocked(user);
Amith Yamasani920ace02012-09-20 22:15:37 -07001925 }
1926 }
1927 }
1928
1929 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07001930 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani742a6712011-05-04 14:49:28 -07001931 * TODO: May not be a good idea to recycle ids, in case it results in confusion
1932 * for data and battery stats collection, or unexpected cross-talk.
Amith Yamasani0b285492011-04-14 17:35:23 -07001933 * @return
1934 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001935 private int getNextAvailableIdLocked() {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001936 synchronized (mPackagesLock) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001937 int i = MIN_USER_ID;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07001938 while (i < MAX_USER_ID) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001939 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07001940 return i;
Amith Yamasani195263742012-08-21 15:40:12 -07001941 }
1942 i++;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001943 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001944 }
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07001945 throw new IllegalStateException("No user id available!");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001946 }
Amith Yamasani920ace02012-09-20 22:15:37 -07001947
Amith Yamasanifc95e702013-09-26 13:20:17 -07001948 private String packageToRestrictionsFileName(String packageName) {
1949 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
1950 }
1951
Jeff Sharkey6dce4962015-07-03 18:08:41 -07001952 /**
1953 * Create new {@code /data/user/[id]} directory and sets default
1954 * permissions.
1955 */
Jeff Sharkey3bb8c852015-07-06 16:44:23 -07001956 public static void prepareUserDirectory(Context context, String volumeUuid, int userId) {
1957 final StorageManager storage = context.getSystemService(StorageManager.class);
1958 final File userDir = Environment.getDataUserDirectory(volumeUuid, userId);
1959 storage.createNewUserDir(userId, userDir);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07001960 }
1961
1962 /**
1963 * Enforce that serial number stored in user directory inode matches the
1964 * given expected value. Gracefully sets the serial number if currently
1965 * undefined.
1966 *
1967 * @throws IOException when problem extracting serial number, or serial
1968 * number is mismatched.
1969 */
1970 public static void enforceSerialNumber(File file, int serialNumber) throws IOException {
1971 final int foundSerial = getSerialNumber(file);
1972 Slog.v(LOG_TAG, "Found " + file + " with serial number " + foundSerial);
1973
1974 if (foundSerial == -1) {
1975 Slog.d(LOG_TAG, "Serial number missing on " + file + "; assuming current is valid");
1976 try {
1977 setSerialNumber(file, serialNumber);
1978 } catch (IOException e) {
1979 Slog.w(LOG_TAG, "Failed to set serial number on " + file, e);
1980 }
1981
1982 } else if (foundSerial != serialNumber) {
1983 throw new IOException("Found serial number " + foundSerial
1984 + " doesn't match expected " + serialNumber);
1985 }
1986 }
1987
1988 /**
1989 * Set serial number stored in user directory inode.
1990 *
1991 * @throws IOException if serial number was already set
1992 */
1993 private static void setSerialNumber(File file, int serialNumber)
1994 throws IOException {
1995 try {
1996 final byte[] buf = Integer.toString(serialNumber).getBytes(StandardCharsets.UTF_8);
1997 Os.setxattr(file.getAbsolutePath(), XATTR_SERIAL, buf, OsConstants.XATTR_CREATE);
1998 } catch (ErrnoException e) {
1999 throw e.rethrowAsIOException();
2000 }
2001 }
2002
2003 /**
2004 * Return serial number stored in user directory inode.
2005 *
2006 * @return parsed serial number, or -1 if not set
2007 */
2008 private static int getSerialNumber(File file) throws IOException {
2009 try {
2010 final byte[] buf = new byte[256];
2011 final int len = Os.getxattr(file.getAbsolutePath(), XATTR_SERIAL, buf);
2012 final String serial = new String(buf, 0, len);
2013 try {
2014 return Integer.parseInt(serial);
2015 } catch (NumberFormatException e) {
2016 throw new IOException("Bad serial number: " + serial);
2017 }
2018 } catch (ErrnoException e) {
2019 if (e.errno == OsConstants.ENODATA) {
2020 return -1;
2021 } else {
2022 throw e.rethrowAsIOException();
2023 }
2024 }
2025 }
2026
Amith Yamasani920ace02012-09-20 22:15:37 -07002027 @Override
2028 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2029 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2030 != PackageManager.PERMISSION_GRANTED) {
2031 pw.println("Permission Denial: can't dump UserManager from from pid="
2032 + Binder.getCallingPid()
2033 + ", uid=" + Binder.getCallingUid()
2034 + " without permission "
2035 + android.Manifest.permission.DUMP);
2036 return;
2037 }
2038
2039 long now = System.currentTimeMillis();
2040 StringBuilder sb = new StringBuilder();
2041 synchronized (mPackagesLock) {
2042 pw.println("Users:");
2043 for (int i = 0; i < mUsers.size(); i++) {
2044 UserInfo user = mUsers.valueAt(i);
2045 if (user == null) continue;
Amith Yamasani634cf312012-10-04 17:34:21 -07002046 pw.print(" "); pw.print(user); pw.print(" serialNo="); pw.print(user.serialNumber);
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002047 if (mRemovingUserIds.get(mUsers.keyAt(i))) pw.print(" <removing> ");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002048 if (user.partial) pw.print(" <partial>");
2049 pw.println();
Amith Yamasani920ace02012-09-20 22:15:37 -07002050 pw.print(" Created: ");
2051 if (user.creationTime == 0) {
2052 pw.println("<unknown>");
2053 } else {
2054 sb.setLength(0);
2055 TimeUtils.formatDuration(now - user.creationTime, sb);
2056 sb.append(" ago");
2057 pw.println(sb);
2058 }
2059 pw.print(" Last logged in: ");
2060 if (user.lastLoggedInTime == 0) {
2061 pw.println("<unknown>");
2062 } else {
2063 sb.setLength(0);
2064 TimeUtils.formatDuration(now - user.lastLoggedInTime, sb);
2065 sb.append(" ago");
2066 pw.println(sb);
2067 }
Makoto Onukia4f11972015-10-01 13:19:58 -07002068 pw.println(" Restrictions:");
2069 UserRestrictionsUtils.dumpRestrictions(
2070 pw, " ", mUserRestrictions.get(user.id));
Amith Yamasani920ace02012-09-20 22:15:37 -07002071 }
Makoto Onukia4f11972015-10-01 13:19:58 -07002072 pw.println();
2073 pw.println("Guest restrictions:");
2074 UserRestrictionsUtils.dumpRestrictions(pw, " ", mGuestRestrictions);
Amith Yamasani920ace02012-09-20 22:15:37 -07002075 }
2076 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002077
2078 final class MainHandler extends Handler {
2079
2080 @Override
2081 public void handleMessage(Message msg) {
2082 switch (msg.what) {
2083 case WRITE_USER_MSG:
2084 removeMessages(WRITE_USER_MSG, msg.obj);
2085 synchronized (mPackagesLock) {
2086 int userId = ((UserInfo) msg.obj).id;
2087 UserInfo userInfo = mUsers.get(userId);
2088 if (userInfo != null) {
2089 writeUserLocked(userInfo);
2090 }
2091 }
2092 }
2093 }
2094 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07002095
2096 /**
2097 * @param userId
2098 * @return whether the user has been initialized yet
2099 */
2100 boolean isInitialized(int userId) {
2101 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
2102 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002103}