blob: b36a22e4461f2deeb56b1f207f099765efc33d15 [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) {
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800601 synchronized (mPackagesLock) {
602 Bundle restrictions = mUserRestrictions.get(userId);
Amith Yamasanibe465322014-04-24 13:45:17 -0700603 return restrictions != null ? new Bundle(restrictions) : new Bundle();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800604 }
605 }
606
607 @Override
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700608 public void setUserRestriction(String key, boolean value, int userId) {
Fyodor Kupolovd4b26042015-07-27 14:30:59 -0700609 checkManageUsersPermission("setUserRestriction");
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700610 synchronized (mPackagesLock) {
Makoto Onukia4f11972015-10-01 13:19:58 -0700611 if (!UserRestrictionsUtils.SYSTEM_CONTROLLED_USER_RESTRICTIONS.contains(key)) {
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700612 Bundle restrictions = getUserRestrictions(userId);
613 restrictions.putBoolean(key, value);
614 setUserRestrictionsInternalLocked(restrictions, userId);
615 }
616 }
617 }
618
619 @Override
620 public void setSystemControlledUserRestriction(String key, boolean value, int userId) {
621 checkSystemOrRoot("setSystemControlledUserRestriction");
622 synchronized (mPackagesLock) {
623 Bundle restrictions = getUserRestrictions(userId);
624 restrictions.putBoolean(key, value);
625 setUserRestrictionsInternalLocked(restrictions, userId);
626 }
627 }
628
629 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800630 public void setUserRestrictions(Bundle restrictions, int userId) {
Amith Yamasanibe465322014-04-24 13:45:17 -0700631 checkManageUsersPermission("setUserRestrictions");
Amith Yamasani0343ec32013-07-22 14:52:06 -0700632 if (restrictions == null) return;
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800633
634 synchronized (mPackagesLock) {
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700635 final Bundle oldUserRestrictions = mUserRestrictions.get(userId);
636 // Restore the original state of system controlled restrictions from oldUserRestrictions
Makoto Onukia4f11972015-10-01 13:19:58 -0700637 for (String key : UserRestrictionsUtils.SYSTEM_CONTROLLED_USER_RESTRICTIONS) {
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700638 restrictions.remove(key);
639 if (oldUserRestrictions.containsKey(key)) {
640 restrictions.putBoolean(key, oldUserRestrictions.getBoolean(key));
641 }
Jason Monk62062992014-05-06 09:55:28 -0400642 }
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700643 setUserRestrictionsInternalLocked(restrictions, userId);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800644 }
645 }
646
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700647 private void setUserRestrictionsInternalLocked(Bundle restrictions, int userId) {
648 final Bundle userRestrictions = mUserRestrictions.get(userId);
649 userRestrictions.clear();
650 userRestrictions.putAll(restrictions);
651 long token = Binder.clearCallingIdentity();
652 try {
653 mAppOpsService.setUserRestrictions(userRestrictions, userId);
654 } catch (RemoteException e) {
655 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
656 } finally {
657 Binder.restoreCallingIdentity(token);
658 }
659 scheduleWriteUserLocked(mUsers.get(userId));
660 }
661
Amith Yamasani258848d2012-08-10 17:06:33 -0700662 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700663 * Check if we've hit the limit of how many users can be created.
664 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700665 private boolean isUserLimitReachedLocked() {
Nicolas Prevot12678a92015-05-13 12:15:03 -0700666 return getAliveUsersExcludingGuestsCountLocked() >= UserManager.getMaxSupportedUsers();
667 }
668
669 @Override
Nicolas Prevotb8186812015-08-06 15:00:03 +0100670 public boolean canAddMoreManagedProfiles(int userId) {
Nicolas Prevot12678a92015-05-13 12:15:03 -0700671 checkManageUsersPermission("check if more managed profiles can be added.");
672 if (ActivityManager.isLowRamDeviceStatic()) {
673 return false;
674 }
Fyodor Kupolovb6157992015-06-05 15:32:28 -0700675 if (!mContext.getPackageManager().hasSystemFeature(
676 PackageManager.FEATURE_MANAGED_USERS)) {
677 return false;
678 }
Nicolas Prevotb8186812015-08-06 15:00:03 +0100679 // Limit number of managed profiles that can be created
680 int managedProfilesCount = getProfiles(userId, true).size() - 1;
681 if (managedProfilesCount >= MAX_MANAGED_PROFILES) {
682 return false;
683 }
Nicolas Prevot12678a92015-05-13 12:15:03 -0700684 synchronized(mPackagesLock) {
Nicolas Prevotb8186812015-08-06 15:00:03 +0100685 UserInfo userInfo = getUserInfoLocked(userId);
686 if (!userInfo.canHaveProfile()) {
Nicolas Prevot12678a92015-05-13 12:15:03 -0700687 return false;
688 }
689 int usersCount = getAliveUsersExcludingGuestsCountLocked();
690 // We allow creating a managed profile in the special case where there is only one user.
691 return usersCount == 1 || usersCount < UserManager.getMaxSupportedUsers();
692 }
693 }
694
695 private int getAliveUsersExcludingGuestsCountLocked() {
Amith Yamasanif584f012014-05-19 17:57:25 -0700696 int aliveUserCount = 0;
697 final int totalUserCount = mUsers.size();
698 // Skip over users being removed
699 for (int i = 0; i < totalUserCount; i++) {
700 UserInfo user = mUsers.valueAt(i);
Amith Yamasani95ab7842014-08-11 17:09:26 -0700701 if (!mRemovingUserIds.get(user.id)
Amith Yamasani1df14732014-08-29 21:37:27 -0700702 && !user.isGuest() && !user.partial) {
Amith Yamasanif584f012014-05-19 17:57:25 -0700703 aliveUserCount++;
704 }
705 }
Nicolas Prevot12678a92015-05-13 12:15:03 -0700706 return aliveUserCount;
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700707 }
708
709 /**
Amith Yamasani195263742012-08-21 15:40:12 -0700710 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -0700711 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -0700712 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -0700713 *
714 * @param message used as message if SecurityException is thrown
715 * @throws SecurityException if the caller is not system or root
716 */
Amith Yamasanibe465322014-04-24 13:45:17 -0700717 private static final void checkManageUsersPermission(String message) {
Amith Yamasani258848d2012-08-10 17:06:33 -0700718 final int uid = Binder.getCallingUid();
Amith Yamasanibe465322014-04-24 13:45:17 -0700719 if (uid != Process.SYSTEM_UID && uid != 0
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400720 && ActivityManager.checkComponentPermission(
721 android.Manifest.permission.MANAGE_USERS,
Amith Yamasanibe465322014-04-24 13:45:17 -0700722 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
723 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
724 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400725 }
726
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700727 private static void checkSystemOrRoot(String message) {
728 final int uid = Binder.getCallingUid();
729 if (uid != Process.SYSTEM_UID && uid != 0) {
730 throw new SecurityException("Only system may call: " + message);
731 }
732 }
733
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700734 private void writeBitmapLocked(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700735 try {
736 File dir = new File(mUsersDir, Integer.toString(info.id));
737 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +0100738 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700739 if (!dir.exists()) {
740 dir.mkdir();
741 FileUtils.setPermissions(
742 dir.getPath(),
743 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
744 -1, -1);
745 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700746 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +0100747 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
748 && tmp.renameTo(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -0700749 info.iconPath = file.getAbsolutePath();
750 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700751 try {
752 os.close();
753 } catch (IOException ioe) {
754 // What the ... !
755 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100756 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700757 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700758 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700759 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700760 }
761
Amith Yamasani0b285492011-04-14 17:35:23 -0700762 /**
763 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
764 * cache it elsewhere.
765 * @return the array of user ids.
766 */
Dianne Hackborn1676c852012-09-10 14:52:30 -0700767 public int[] getUserIds() {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700768 synchronized (mPackagesLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700769 return mUserIds;
770 }
Amith Yamasani0b285492011-04-14 17:35:23 -0700771 }
772
Dianne Hackborn4428e172012-08-24 17:43:05 -0700773 int[] getUserIdsLPr() {
774 return mUserIds;
775 }
776
Amith Yamasani13593602012-03-22 16:16:17 -0700777 private void readUserListLocked() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700778 if (!mUserListFile.exists()) {
Amith Yamasani13593602012-03-22 16:16:17 -0700779 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700780 return;
781 }
782 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700783 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700784 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700785 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700786 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100787 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700788 int type;
789 while ((type = parser.next()) != XmlPullParser.START_TAG
790 && type != XmlPullParser.END_DOCUMENT) {
791 ;
792 }
793
794 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700795 Slog.e(LOG_TAG, "Unable to read user list");
Amith Yamasani13593602012-03-22 16:16:17 -0700796 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700797 return;
798 }
799
Amith Yamasani2a003292012-08-14 18:25:45 -0700800 mNextSerialNumber = -1;
801 if (parser.getName().equals(TAG_USERS)) {
802 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
803 if (lastSerialNumber != null) {
804 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
805 }
Amith Yamasani6f34b412012-10-22 18:19:27 -0700806 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
807 if (versionNumber != null) {
808 mUserVersion = Integer.parseInt(versionNumber);
809 }
Amith Yamasani2a003292012-08-14 18:25:45 -0700810 }
811
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700812 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530813 if (type == XmlPullParser.START_TAG) {
814 final String name = parser.getName();
815 if (name.equals(TAG_USER)) {
816 String id = parser.getAttributeValue(null, ATTR_ID);
817 UserInfo user = readUserLocked(Integer.parseInt(id));
Amith Yamasani6f34b412012-10-22 18:19:27 -0700818
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530819 if (user != null) {
820 mUsers.put(user.id, user);
821 if (mNextSerialNumber < 0 || mNextSerialNumber <= user.id) {
822 mNextSerialNumber = user.id + 1;
823 }
Amith Yamasani2a003292012-08-14 18:25:45 -0700824 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530825 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -0800826 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
827 && type != XmlPullParser.END_TAG) {
828 if (type == XmlPullParser.START_TAG) {
829 if (parser.getName().equals(TAG_RESTRICTIONS)) {
Makoto Onukia4f11972015-10-01 13:19:58 -0700830 UserRestrictionsUtils
831 .readRestrictions(parser, mGuestRestrictions);
Amith Yamasanida0b1682014-11-21 12:58:17 -0800832 }
833 break;
834 }
835 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700836 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700837 }
838 }
Amith Yamasani13593602012-03-22 16:16:17 -0700839 updateUserIdsLocked();
Amith Yamasani350962c2013-08-06 11:18:53 -0700840 upgradeIfNecessaryLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700841 } catch (IOException ioe) {
Amith Yamasani13593602012-03-22 16:16:17 -0700842 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700843 } catch (XmlPullParserException pe) {
Amith Yamasani13593602012-03-22 16:16:17 -0700844 fallbackToSingleUserLocked();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -0800845 } finally {
846 if (fis != null) {
847 try {
848 fis.close();
849 } catch (IOException e) {
850 }
851 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700852 }
853 }
854
Amith Yamasani6f34b412012-10-22 18:19:27 -0700855 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -0800856 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -0700857 */
Amith Yamasani350962c2013-08-06 11:18:53 -0700858 private void upgradeIfNecessaryLocked() {
Amith Yamasani6f34b412012-10-22 18:19:27 -0700859 int userVersion = mUserVersion;
860 if (userVersion < 1) {
861 // Assign a proper name for the owner, if not initialized correctly before
Xiaohui Chen47f07952015-10-02 14:40:27 -0700862 UserInfo user = mUsers.get(UserHandle.USER_SYSTEM);
Amith Yamasani6f34b412012-10-22 18:19:27 -0700863 if ("Primary".equals(user.name)) {
864 user.name = mContext.getResources().getString(com.android.internal.R.string.owner_name);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800865 scheduleWriteUserLocked(user);
Amith Yamasani6f34b412012-10-22 18:19:27 -0700866 }
867 userVersion = 1;
868 }
869
Amith Yamasanibc9625052012-11-15 14:39:18 -0800870 if (userVersion < 2) {
871 // Owner should be marked as initialized
Xiaohui Chen47f07952015-10-02 14:40:27 -0700872 UserInfo user = mUsers.get(UserHandle.USER_SYSTEM);
Amith Yamasanibc9625052012-11-15 14:39:18 -0800873 if ((user.flags & UserInfo.FLAG_INITIALIZED) == 0) {
874 user.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800875 scheduleWriteUserLocked(user);
Amith Yamasanibc9625052012-11-15 14:39:18 -0800876 }
877 userVersion = 2;
878 }
879
Amith Yamasani350962c2013-08-06 11:18:53 -0700880
Amith Yamasani5e486f52013-08-07 11:06:44 -0700881 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -0700882 userVersion = 4;
883 }
884
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700885 if (userVersion < 5) {
886 initDefaultGuestRestrictions();
887 userVersion = 5;
888 }
889
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700890 if (userVersion < 6) {
891 final boolean splitSystemUser = UserManager.isSplitSystemUser();
892 for (int i = 0; i < mUsers.size(); i++) {
893 UserInfo user = mUsers.valueAt(i);
894 // In non-split mode, only user 0 can have restricted profiles
895 if (!splitSystemUser && user.isRestricted()
896 && (user.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID)) {
897 user.restrictedProfileParentId = UserHandle.USER_SYSTEM;
898 scheduleWriteUserLocked(user);
899 }
900 }
901 userVersion = 6;
902 }
903
Amith Yamasani6f34b412012-10-22 18:19:27 -0700904 if (userVersion < USER_VERSION) {
905 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
906 + USER_VERSION);
907 } else {
908 mUserVersion = userVersion;
909 writeUserListLocked();
910 }
911 }
912
Amith Yamasani13593602012-03-22 16:16:17 -0700913 private void fallbackToSingleUserLocked() {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -0700914 int flags = UserInfo.FLAG_INITIALIZED;
915 // In split system user mode, the admin and primary flags are assigned to the first human
916 // user.
917 if (!UserManager.isSplitSystemUser()) {
918 flags |= UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY;
919 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700920 // Create the system user
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700921 UserInfo system = new UserInfo(UserHandle.USER_SYSTEM,
Amith Yamasani6f34b412012-10-22 18:19:27 -0700922 mContext.getResources().getString(com.android.internal.R.string.owner_name), null,
Xiaohui Chenb31e14a2015-07-13 16:04:55 -0700923 flags);
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700924 mUsers.put(system.id, system);
Amith Yamasani634cf312012-10-04 17:34:21 -0700925 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -0400926 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -0800927
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -0500928 Bundle restrictions = new Bundle();
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700929 mUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions);
Amith Yamasani67df64b2012-12-14 12:09:36 -0800930
Amith Yamasani13593602012-03-22 16:16:17 -0700931 updateUserIdsLocked();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700932 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700933
Amith Yamasani13593602012-03-22 16:16:17 -0700934 writeUserListLocked();
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700935 writeUserLocked(system);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700936 }
937
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800938 private void scheduleWriteUserLocked(UserInfo userInfo) {
939 if (!mHandler.hasMessages(WRITE_USER_MSG, userInfo)) {
940 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, userInfo);
941 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
942 }
943 }
944
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700945 /*
946 * Writes the user file in this format:
947 *
948 * <user flags="20039023" id="0">
949 * <name>Primary</name>
950 * </user>
951 */
Amith Yamasani13593602012-03-22 16:16:17 -0700952 private void writeUserLocked(UserInfo userInfo) {
Amith Yamasani742a6712011-05-04 14:49:28 -0700953 FileOutputStream fos = null;
Amith Yamasanifc95e702013-09-26 13:20:17 -0700954 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userInfo.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700955 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700956 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700957 final BufferedOutputStream bos = new BufferedOutputStream(fos);
958
959 // XmlSerializer serializer = XmlUtils.serializerInstance();
960 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100961 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700962 serializer.startDocument(null, true);
963 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
964
965 serializer.startTag(null, TAG_USER);
966 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
Amith Yamasani2a003292012-08-14 18:25:45 -0700967 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700968 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Amith Yamasani920ace02012-09-20 22:15:37 -0700969 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
970 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
971 Long.toString(userInfo.lastLoggedInTime));
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700972 if (userInfo.iconPath != null) {
973 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
974 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700975 if (userInfo.partial) {
976 serializer.attribute(null, ATTR_PARTIAL, "true");
977 }
Adam Lesinskieddeb492014-09-08 17:50:03 -0700978 if (userInfo.guestToRemove) {
979 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
980 }
Kenny Guy2a764942014-04-02 13:29:20 +0100981 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
982 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
983 Integer.toString(userInfo.profileGroupId));
Kenny Guya52dc3e2014-02-11 15:33:14 +0000984 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700985 if (userInfo.restrictedProfileParentId != UserInfo.NO_PROFILE_GROUP_ID) {
986 serializer.attribute(null, ATTR_RESTRICTED_PROFILE_PARENT_ID,
987 Integer.toString(userInfo.restrictedProfileParentId));
988 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700989 serializer.startTag(null, TAG_NAME);
990 serializer.text(userInfo.name);
991 serializer.endTag(null, TAG_NAME);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800992 Bundle restrictions = mUserRestrictions.get(userInfo.id);
993 if (restrictions != null) {
Makoto Onukia4f11972015-10-01 13:19:58 -0700994 UserRestrictionsUtils.writeRestrictions(serializer, restrictions, TAG_RESTRICTIONS);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800995 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700996 serializer.endTag(null, TAG_USER);
997
998 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -0700999 userFile.finishWrite(fos);
1000 } catch (Exception ioe) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001001 Slog.e(LOG_TAG, "Error writing user info " + userInfo.id + "\n" + ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -07001002 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001003 }
1004 }
1005
1006 /*
1007 * Writes the user list file in this format:
1008 *
Amith Yamasani2a003292012-08-14 18:25:45 -07001009 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001010 * <user id="0"></user>
1011 * <user id="2"></user>
1012 * </users>
1013 */
Amith Yamasani13593602012-03-22 16:16:17 -07001014 private void writeUserListLocked() {
Amith Yamasani742a6712011-05-04 14:49:28 -07001015 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001016 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001017 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001018 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001019 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1020
1021 // XmlSerializer serializer = XmlUtils.serializerInstance();
1022 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001023 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001024 serializer.startDocument(null, true);
1025 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1026
1027 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -07001028 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -07001029 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001030
Adam Lesinskieddeb492014-09-08 17:50:03 -07001031 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Makoto Onukia4f11972015-10-01 13:19:58 -07001032 UserRestrictionsUtils
1033 .writeRestrictions(serializer, mGuestRestrictions, TAG_RESTRICTIONS);
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301034 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Amith Yamasani515d4062015-09-28 11:30:06 -07001035 final int userSize = mUsers.size();
1036 for (int i = 0; i < userSize; i++) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001037 UserInfo user = mUsers.valueAt(i);
1038 serializer.startTag(null, TAG_USER);
1039 serializer.attribute(null, ATTR_ID, Integer.toString(user.id));
1040 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001041 }
1042
1043 serializer.endTag(null, TAG_USERS);
1044
1045 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001046 userListFile.finishWrite(fos);
1047 } catch (Exception e) {
1048 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -07001049 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001050 }
1051 }
1052
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001053 private UserInfo readUserLocked(int id) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001054 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -07001055 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001056 String name = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001057 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -07001058 long creationTime = 0L;
1059 long lastLoggedInTime = 0L;
Kenny Guy2a764942014-04-02 13:29:20 +01001060 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001061 int restrictedProfileParentId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001062 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001063 boolean guestToRemove = false;
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001064 Bundle restrictions = new Bundle();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001065
1066 FileInputStream fis = null;
1067 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001068 AtomicFile userFile =
Amith Yamasanifc95e702013-09-26 13:20:17 -07001069 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
Amith Yamasani2a003292012-08-14 18:25:45 -07001070 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001071 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001072 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001073 int type;
1074 while ((type = parser.next()) != XmlPullParser.START_TAG
1075 && type != XmlPullParser.END_DOCUMENT) {
1076 ;
1077 }
1078
1079 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001080 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001081 return null;
1082 }
1083
1084 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001085 int storedId = readIntAttribute(parser, ATTR_ID, -1);
1086 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001087 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001088 return null;
1089 }
Amith Yamasani920ace02012-09-20 22:15:37 -07001090 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
1091 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001092 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -07001093 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
1094 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Kenny Guy2a764942014-04-02 13:29:20 +01001095 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
1096 UserInfo.NO_PROFILE_GROUP_ID);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001097 restrictedProfileParentId = readIntAttribute(parser,
1098 ATTR_RESTRICTED_PROFILE_PARENT_ID, UserInfo.NO_PROFILE_GROUP_ID);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001099 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
1100 if ("true".equals(valueString)) {
1101 partial = true;
1102 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001103 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
1104 if ("true".equals(valueString)) {
1105 guestToRemove = true;
1106 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001107
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001108 int outerDepth = parser.getDepth();
1109 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1110 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1111 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1112 continue;
1113 }
1114 String tag = parser.getName();
1115 if (TAG_NAME.equals(tag)) {
1116 type = parser.next();
1117 if (type == XmlPullParser.TEXT) {
1118 name = parser.getText();
1119 }
1120 } else if (TAG_RESTRICTIONS.equals(tag)) {
Makoto Onukia4f11972015-10-01 13:19:58 -07001121 UserRestrictionsUtils.readRestrictions(parser, restrictions);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001122 }
1123 }
1124 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001125
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001126 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -07001127 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -07001128 userInfo.creationTime = creationTime;
1129 userInfo.lastLoggedInTime = lastLoggedInTime;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001130 userInfo.partial = partial;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001131 userInfo.guestToRemove = guestToRemove;
Kenny Guy2a764942014-04-02 13:29:20 +01001132 userInfo.profileGroupId = profileGroupId;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001133 userInfo.restrictedProfileParentId = restrictedProfileParentId;
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001134 mUserRestrictions.append(id, restrictions);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001135 return userInfo;
1136
1137 } catch (IOException ioe) {
1138 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001139 } finally {
1140 if (fis != null) {
1141 try {
1142 fis.close();
1143 } catch (IOException e) {
1144 }
1145 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001146 }
1147 return null;
1148 }
1149
Amith Yamasani920ace02012-09-20 22:15:37 -07001150 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
1151 String valueString = parser.getAttributeValue(null, attr);
1152 if (valueString == null) return defaultValue;
1153 try {
1154 return Integer.parseInt(valueString);
1155 } catch (NumberFormatException nfe) {
1156 return defaultValue;
1157 }
1158 }
1159
1160 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
1161 String valueString = parser.getAttributeValue(null, attr);
1162 if (valueString == null) return defaultValue;
1163 try {
1164 return Long.parseLong(valueString);
1165 } catch (NumberFormatException nfe) {
1166 return defaultValue;
1167 }
1168 }
1169
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001170 private boolean isPackageInstalled(String pkg, int userId) {
1171 final ApplicationInfo info = mPm.getApplicationInfo(pkg,
1172 PackageManager.GET_UNINSTALLED_PACKAGES,
1173 userId);
1174 if (info == null || (info.flags&ApplicationInfo.FLAG_INSTALLED) == 0) {
1175 return false;
1176 }
1177 return true;
1178 }
1179
Amith Yamasanib82add22013-07-09 11:24:44 -07001180 /**
Kenny Guyd21b2182014-07-17 16:38:55 +01001181 * Removes all the restrictions files (res_<packagename>) for a given user.
Amith Yamasanib82add22013-07-09 11:24:44 -07001182 * Does not do any permissions checking.
1183 */
Kenny Guyd21b2182014-07-17 16:38:55 +01001184 private void cleanAppRestrictions(int userId) {
Amith Yamasanib82add22013-07-09 11:24:44 -07001185 synchronized (mPackagesLock) {
1186 File dir = Environment.getUserSystemDirectory(userId);
1187 String[] files = dir.list();
1188 if (files == null) return;
1189 for (String fileName : files) {
1190 if (fileName.startsWith(RESTRICTIONS_FILE_PREFIX)) {
1191 File resFile = new File(dir, fileName);
1192 if (resFile.exists()) {
Kenny Guyd21b2182014-07-17 16:38:55 +01001193 resFile.delete();
Amith Yamasanib82add22013-07-09 11:24:44 -07001194 }
1195 }
1196 }
1197 }
1198 }
1199
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001200 /**
1201 * Removes the app restrictions file for a specific package and user id, if it exists.
1202 */
1203 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
1204 synchronized (mPackagesLock) {
1205 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07001206 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001207 if (resFile.exists()) {
1208 resFile.delete();
1209 }
1210 }
1211 }
1212
Kenny Guya52dc3e2014-02-11 15:33:14 +00001213 @Override
Kenny Guy2a764942014-04-02 13:29:20 +01001214 public UserInfo createProfileForUser(String name, int flags, int userId) {
Kenny Guya52dc3e2014-02-11 15:33:14 +00001215 checkManageUsersPermission("Only the system can create users");
Kenny Guy2a764942014-04-02 13:29:20 +01001216 return createUserInternal(name, flags, userId);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001217 }
1218
Amith Yamasani258848d2012-08-10 17:06:33 -07001219 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07001220 public UserInfo createUser(String name, int flags) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001221 checkManageUsersPermission("Only the system can create users");
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001222 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001223 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001224
Jessica Hummelbe81c802014-04-22 15:49:22 +01001225 private UserInfo createUserInternal(String name, int flags, int parentId) {
Julia Reynolds75175022014-06-26 16:35:00 -04001226 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1227 UserManager.DISALLOW_ADD_USER, false)) {
1228 Log.w(LOG_TAG, "Cannot add user. DISALLOW_ADD_USER is enabled.");
1229 return null;
1230 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001231 if (ActivityManager.isLowRamDeviceStatic()) {
1232 return null;
1233 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07001234 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001235 final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001236 final boolean isRestricted = (flags & UserInfo.FLAG_RESTRICTED) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001237 final long ident = Binder.clearCallingIdentity();
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001238 UserInfo userInfo = null;
Amith Yamasanibb054c92015-07-09 14:16:27 -07001239 final int userId;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001240 try {
1241 synchronized (mInstallLock) {
1242 synchronized (mPackagesLock) {
Jessica Hummelbe81c802014-04-22 15:49:22 +01001243 UserInfo parent = null;
1244 if (parentId != UserHandle.USER_NULL) {
1245 parent = getUserInfoLocked(parentId);
1246 if (parent == null) return null;
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001247 }
Nicolas Prevotb8186812015-08-06 15:00:03 +01001248 if (isManagedProfile && !canAddMoreManagedProfiles(parentId)) {
1249 Log.e(LOG_TAG, "Cannot add more managed profiles for user " + parentId);
Nicolas Prevot12678a92015-05-13 12:15:03 -07001250 return null;
1251 }
1252 if (!isGuest && !isManagedProfile && isUserLimitReachedLocked()) {
1253 // If we're not adding a guest user or a managed profile and the limit has
1254 // been reached, cannot add a user.
Amith Yamasani95ab7842014-08-11 17:09:26 -07001255 return null;
1256 }
1257 // If we're adding a guest and there already exists one, bail.
Adam Lesinskieddeb492014-09-08 17:50:03 -07001258 if (isGuest && findCurrentGuestUserLocked() != null) {
Amith Yamasani95ab7842014-08-11 17:09:26 -07001259 return null;
1260 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001261 // In legacy mode, restricted profile's parent can only be the owner user
1262 if (isRestricted && !UserManager.isSplitSystemUser()
1263 && (parentId != UserHandle.USER_SYSTEM)) {
1264 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
1265 return null;
1266 }
1267 if (isRestricted && UserManager.isSplitSystemUser()) {
1268 if (parent == null) {
1269 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be "
1270 + "specified");
1271 return null;
1272 }
1273 if (!parent.canHaveProfile()) {
1274 Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be "
1275 + "created for the specified parent user id " + parentId);
1276 return null;
1277 }
1278 }
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001279 // In split system user mode, we assign the first human user the primary flag.
Xiaohui Chen203243a2015-07-16 11:55:47 -07001280 // And if there is no device owner, we also assign the admin flag to primary
1281 // user.
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001282 if (UserManager.isSplitSystemUser()
Xiaohui Chen203243a2015-07-16 11:55:47 -07001283 && !isGuest && !isManagedProfile && getPrimaryUser() == null) {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001284 flags |= UserInfo.FLAG_PRIMARY;
Xiaohui Chen203243a2015-07-16 11:55:47 -07001285 DevicePolicyManager devicePolicyManager = (DevicePolicyManager)
1286 mContext.getSystemService(Context.DEVICE_POLICY_SERVICE);
1287 if (devicePolicyManager == null
1288 || devicePolicyManager.getDeviceOwner() == null) {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001289 flags |= UserInfo.FLAG_ADMIN;
1290 }
1291 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07001292 userId = getNextAvailableIdLocked();
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001293 userInfo = new UserInfo(userId, name, null, flags);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001294 userInfo.serialNumber = mNextSerialNumber++;
Amith Yamasani920ace02012-09-20 22:15:37 -07001295 long now = System.currentTimeMillis();
1296 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001297 userInfo.partial = true;
Amith Yamasani16389312012-10-17 21:20:14 -07001298 Environment.getUserSystemDirectory(userInfo.id).mkdirs();
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001299 mUsers.put(userId, userInfo);
1300 writeUserListLocked();
Jessica Hummelbe81c802014-04-22 15:49:22 +01001301 if (parent != null) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001302 if (isManagedProfile) {
1303 if (parent.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
1304 parent.profileGroupId = parent.id;
1305 scheduleWriteUserLocked(parent);
1306 }
1307 userInfo.profileGroupId = parent.profileGroupId;
1308 } else if (isRestricted) {
1309 if (!parent.canHaveProfile()) {
1310 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
1311 }
1312 if (parent.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) {
1313 parent.restrictedProfileParentId = parent.id;
1314 scheduleWriteUserLocked(parent);
1315 }
1316 userInfo.restrictedProfileParentId = parent.restrictedProfileParentId;
Kenny Guya52dc3e2014-02-11 15:33:14 +00001317 }
Kenny Guya52dc3e2014-02-11 15:33:14 +00001318 }
Jeff Sharkey6dce4962015-07-03 18:08:41 -07001319 final StorageManager storage = mContext.getSystemService(StorageManager.class);
1320 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
1321 final String volumeUuid = vol.getFsUuid();
1322 try {
1323 final File userDir = Environment.getDataUserDirectory(volumeUuid,
1324 userId);
Jeff Sharkey3bb8c852015-07-06 16:44:23 -07001325 prepareUserDirectory(mContext, volumeUuid, userId);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07001326 enforceSerialNumber(userDir, userInfo.serialNumber);
1327 } catch (IOException e) {
1328 Log.wtf(LOG_TAG, "Failed to create user directory on " + volumeUuid, e);
1329 }
1330 }
1331 mPm.createNewUserLILPw(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001332 userInfo.partial = false;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001333 scheduleWriteUserLocked(userInfo);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001334 updateUserIdsLocked();
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001335 Bundle restrictions = new Bundle();
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001336 mUserRestrictions.append(userId, restrictions);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001337 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07001338 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07001339 mPm.newUserCreated(userId);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001340 if (userInfo != null) {
1341 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
1342 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userInfo.id);
1343 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
1344 android.Manifest.permission.MANAGE_USERS);
1345 }
1346 } finally {
1347 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07001348 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001349 return userInfo;
1350 }
1351
Amith Yamasani0b285492011-04-14 17:35:23 -07001352 /**
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07001353 * @hide
1354 */
1355 public UserInfo createRestrictedProfile(String name, int parentUserId) {
1356 checkManageUsersPermission("setupRestrictedProfile");
1357 final UserInfo user = createProfileForUser(name, UserInfo.FLAG_RESTRICTED, parentUserId);
1358 if (user == null) {
1359 return null;
1360 }
1361 setUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, true, user.id);
1362 // Change the setting before applying the DISALLOW_SHARE_LOCATION restriction, otherwise
1363 // the putIntForUser() will fail.
1364 android.provider.Settings.Secure.putIntForUser(mContext.getContentResolver(),
1365 android.provider.Settings.Secure.LOCATION_MODE,
1366 android.provider.Settings.Secure.LOCATION_MODE_OFF, user.id);
1367 setUserRestriction(UserManager.DISALLOW_SHARE_LOCATION, true, user.id);
1368 return user;
1369 }
1370
1371 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07001372 * Find the current guest user. If the Guest user is partial,
1373 * then do not include it in the results as it is about to die.
Adam Lesinskieddeb492014-09-08 17:50:03 -07001374 */
1375 private UserInfo findCurrentGuestUserLocked() {
1376 final int size = mUsers.size();
1377 for (int i = 0; i < size; i++) {
1378 final UserInfo user = mUsers.valueAt(i);
1379 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
1380 return user;
1381 }
1382 }
1383 return null;
1384 }
1385
1386 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07001387 * Mark this guest user for deletion to allow us to create another guest
1388 * and switch to that user before actually removing this guest.
1389 * @param userHandle the userid of the current guest
1390 * @return whether the user could be marked for deletion
1391 */
1392 public boolean markGuestForDeletion(int userHandle) {
1393 checkManageUsersPermission("Only the system can remove users");
1394 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1395 UserManager.DISALLOW_REMOVE_USER, false)) {
1396 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1397 return false;
1398 }
1399
1400 long ident = Binder.clearCallingIdentity();
1401 try {
1402 final UserInfo user;
1403 synchronized (mPackagesLock) {
1404 user = mUsers.get(userHandle);
1405 if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
1406 return false;
1407 }
1408 if (!user.isGuest()) {
1409 return false;
1410 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001411 // We set this to a guest user that is to be removed. This is a temporary state
1412 // where we are allowed to add new Guest users, even if this one is still not
1413 // removed. This user will still show up in getUserInfo() calls.
1414 // If we don't get around to removing this Guest user, it will be purged on next
1415 // startup.
1416 user.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07001417 // Mark it as disabled, so that it isn't returned any more when
1418 // profiles are queried.
1419 user.flags |= UserInfo.FLAG_DISABLED;
Amith Yamasani1df14732014-08-29 21:37:27 -07001420 writeUserLocked(user);
1421 }
1422 } finally {
1423 Binder.restoreCallingIdentity(ident);
1424 }
1425 return true;
1426 }
1427
1428 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07001429 * Removes a user and all data directories created for that user. This method should be called
1430 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001431 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07001432 */
Amith Yamasani258848d2012-08-10 17:06:33 -07001433 public boolean removeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001434 checkManageUsersPermission("Only the system can remove users");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04001435 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1436 UserManager.DISALLOW_REMOVE_USER, false)) {
1437 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1438 return false;
1439 }
1440
Kenny Guyee58b4f2014-05-23 15:19:53 +01001441 long ident = Binder.clearCallingIdentity();
1442 try {
1443 final UserInfo user;
Fyodor Kupolov0df68cd2015-10-01 13:54:22 -07001444 int currentUser = ActivityManager.getCurrentUser();
1445 if (currentUser == userHandle) {
1446 Log.w(LOG_TAG, "Current user cannot be removed");
1447 return false;
1448 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01001449 synchronized (mPackagesLock) {
1450 user = mUsers.get(userHandle);
Kenny Guy17c9d692014-06-13 13:51:42 +01001451 if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01001452 return false;
1453 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08001454
1455 // We remember deleted user IDs to prevent them from being
1456 // reused during the current boot; they can still be reused
1457 // after a reboot.
Kenny Guyee58b4f2014-05-23 15:19:53 +01001458 mRemovingUserIds.put(userHandle, true);
Jeff Sharkey6eb09392014-11-14 15:57:59 -08001459
Kenny Guyee58b4f2014-05-23 15:19:53 +01001460 try {
1461 mAppOpsService.removeUser(userHandle);
1462 } catch (RemoteException e) {
1463 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
1464 }
1465 // Set this to a partially created user, so that the user will be purged
1466 // on next startup, in case the runtime stops now before stopping and
1467 // removing the user completely.
1468 user.partial = true;
1469 // Mark it as disabled, so that it isn't returned any more when
1470 // profiles are queried.
1471 user.flags |= UserInfo.FLAG_DISABLED;
1472 writeUserLocked(user);
1473 }
1474
1475 if (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
1476 && user.isManagedProfile()) {
1477 // Send broadcast to notify system that the user removed was a
1478 // managed user.
1479 sendProfileRemovedBroadcast(user.profileGroupId, user.id);
1480 }
1481
1482 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
1483 int res;
1484 try {
1485 res = ActivityManagerNative.getDefault().stopUser(userHandle,
1486 new IStopUserCallback.Stub() {
1487 @Override
1488 public void userStopped(int userId) {
1489 finishRemoveUser(userId);
1490 }
1491 @Override
1492 public void userStopAborted(int userId) {
1493 }
1494 });
1495 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001496 return false;
1497 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01001498 return res == ActivityManager.USER_OP_SUCCESS;
1499 } finally {
1500 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001501 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001502 }
1503
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001504 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07001505 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001506 // Let other services shutdown any activity and clean up their state before completely
1507 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001508 long ident = Binder.clearCallingIdentity();
1509 try {
1510 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
1511 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001512 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
1513 android.Manifest.permission.MANAGE_USERS,
1514
1515 new BroadcastReceiver() {
1516 @Override
1517 public void onReceive(Context context, Intent intent) {
1518 if (DBG) {
1519 Slog.i(LOG_TAG,
1520 "USER_REMOVED broadcast sent, cleaning up user data "
1521 + userHandle);
1522 }
1523 new Thread() {
1524 public void run() {
Amith Yamasani515d4062015-09-28 11:30:06 -07001525 // Clean up any ActivityManager state
1526 LocalServices.getService(ActivityManagerInternal.class)
1527 .onUserRemoved(userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001528 synchronized (mInstallLock) {
1529 synchronized (mPackagesLock) {
1530 removeUserStateLocked(userHandle);
1531 }
1532 }
1533 }
1534 }.start();
1535 }
1536 },
1537
1538 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001539 } finally {
1540 Binder.restoreCallingIdentity(ident);
1541 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001542 }
1543
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001544 private void removeUserStateLocked(final int userHandle) {
Paul Crowley85e4e812015-05-19 12:42:00 +01001545 mContext.getSystemService(StorageManager.class)
1546 .deleteUserKey(userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001547 // Cleanup package manager settings
Amith Yamasanidda003f2014-08-28 18:06:51 -07001548 mPm.cleanUpUserLILPw(this, userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001549
1550 // Remove this user from the list
1551 mUsers.remove(userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001552 // Remove user file
Amith Yamasanifc95e702013-09-26 13:20:17 -07001553 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001554 userFile.delete();
1555 // Update the user list
1556 writeUserListLocked();
1557 updateUserIdsLocked();
1558 removeDirectoryRecursive(Environment.getUserSystemDirectory(userHandle));
1559 }
1560
Amith Yamasani61f57372012-08-31 12:12:28 -07001561 private void removeDirectoryRecursive(File parent) {
1562 if (parent.isDirectory()) {
1563 String[] files = parent.list();
1564 for (String filename : files) {
1565 File child = new File(parent, filename);
1566 removeDirectoryRecursive(child);
1567 }
1568 }
1569 parent.delete();
1570 }
1571
Kenny Guyf8d3a232014-05-15 16:09:52 +01001572 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01001573 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01001574 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
1575 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01001576 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
1577 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01001578 }
1579
Amith Yamasani2a003292012-08-14 18:25:45 -07001580 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001581 public Bundle getApplicationRestrictions(String packageName) {
1582 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
1583 }
1584
1585 @Override
1586 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001587 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07001588 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Esteban Talavera2a5d6c62015-10-21 10:55:56 +01001589 checkManageUsersPermission("get application restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001590 }
1591 synchronized (mPackagesLock) {
1592 // Read the restrictions from XML
1593 return readApplicationRestrictionsLocked(packageName, userId);
1594 }
1595 }
1596
1597 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001598 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001599 int userId) {
Esteban Talavera2a5d6c62015-10-21 10:55:56 +01001600 checkManageUsersPermission("set application restrictions");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001601 synchronized (mPackagesLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01001602 if (restrictions == null || restrictions.isEmpty()) {
1603 cleanAppRestrictionsForPackage(packageName, userId);
1604 } else {
1605 // Write the restrictions to XML
1606 writeApplicationRestrictionsLocked(packageName, restrictions, userId);
1607 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001608 }
Robin Lee66e5d962014-04-09 16:44:21 +01001609
Kenny Guyd21b2182014-07-17 16:38:55 +01001610 if (isPackageInstalled(packageName, userId)) {
1611 // Notify package of changes via an intent - only sent to explicitly registered receivers.
1612 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
1613 changeIntent.setPackage(packageName);
1614 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
1615 mContext.sendBroadcastAsUser(changeIntent, new UserHandle(userId));
1616 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001617 }
1618
Amith Yamasani655d0e22013-06-12 14:19:10 -07001619 @Override
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001620 public void removeRestrictions() {
Esteban Talavera2a5d6c62015-10-21 10:55:56 +01001621 checkManageUsersPermission("remove restrictions");
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001622 final int userHandle = UserHandle.getCallingUserId();
Amith Yamasani5e486f52013-08-07 11:06:44 -07001623 removeRestrictionsForUser(userHandle, true);
Amith Yamasani350962c2013-08-06 11:18:53 -07001624 }
1625
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001626 private void removeRestrictionsForUser(final int userHandle, boolean unhideApps) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001627 synchronized (mPackagesLock) {
1628 // Remove all user restrictions
1629 setUserRestrictions(new Bundle(), userHandle);
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001630 // Remove any app restrictions
Kenny Guyd21b2182014-07-17 16:38:55 +01001631 cleanAppRestrictions(userHandle);
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001632 }
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001633 if (unhideApps) {
1634 unhideAllInstalledAppsForUser(userHandle);
Amith Yamasani5e486f52013-08-07 11:06:44 -07001635 }
1636 }
1637
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001638 private void unhideAllInstalledAppsForUser(final int userHandle) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001639 mHandler.post(new Runnable() {
1640 @Override
1641 public void run() {
1642 List<ApplicationInfo> apps =
1643 mPm.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES,
1644 userHandle).getList();
1645 final long ident = Binder.clearCallingIdentity();
1646 try {
1647 for (ApplicationInfo appInfo : apps) {
1648 if ((appInfo.flags & ApplicationInfo.FLAG_INSTALLED) != 0
Alex Klyubinb9f8a522015-02-03 11:12:59 -08001649 && (appInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HIDDEN)
1650 != 0) {
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001651 mPm.setApplicationHiddenSettingAsUser(appInfo.packageName, false,
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001652 userHandle);
1653 }
1654 }
1655 } finally {
1656 Binder.restoreCallingIdentity(ident);
1657 }
1658 }
1659 });
1660 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001661 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07001662 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001663 try {
1664 return mContext.getPackageManager().getApplicationInfo(packageName,
1665 PackageManager.GET_UNINSTALLED_PACKAGES).uid;
1666 } catch (NameNotFoundException nnfe) {
1667 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07001668 } finally {
1669 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001670 }
1671 }
1672
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001673 private Bundle readApplicationRestrictionsLocked(String packageName,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001674 int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001675 AtomicFile restrictionsFile =
1676 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
1677 packageToRestrictionsFileName(packageName)));
1678 return readApplicationRestrictionsLocked(restrictionsFile);
1679 }
1680
1681 @VisibleForTesting
1682 static Bundle readApplicationRestrictionsLocked(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001683 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001684 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07001685 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07001686 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07001687 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001688
1689 FileInputStream fis = null;
1690 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001691 fis = restrictionsFile.openRead();
1692 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001693 parser.setInput(fis, StandardCharsets.UTF_8.name());
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001694 XmlUtils.nextElement(parser);
1695 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001696 Slog.e(LOG_TAG, "Unable to read restrictions file "
1697 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001698 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001699 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001700 while (parser.next() != XmlPullParser.END_DOCUMENT) {
1701 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001702 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001703 } catch (IOException|XmlPullParserException e) {
1704 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001705 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001706 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001707 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001708 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001709 }
1710
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001711 private static void readEntry(Bundle restrictions, ArrayList<String> values,
1712 XmlPullParser parser) throws XmlPullParserException, IOException {
1713 int type = parser.getEventType();
1714 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
1715 String key = parser.getAttributeValue(null, ATTR_KEY);
1716 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
1717 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
1718 if (multiple != null) {
1719 values.clear();
1720 int count = Integer.parseInt(multiple);
1721 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1722 if (type == XmlPullParser.START_TAG
1723 && parser.getName().equals(TAG_VALUE)) {
1724 values.add(parser.nextText().trim());
1725 count--;
1726 }
1727 }
1728 String [] valueStrings = new String[values.size()];
1729 values.toArray(valueStrings);
1730 restrictions.putStringArray(key, valueStrings);
1731 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
1732 restrictions.putBundle(key, readBundleEntry(parser, values));
1733 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
1734 final int outerDepth = parser.getDepth();
1735 ArrayList<Bundle> bundleList = new ArrayList<>();
1736 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
1737 Bundle childBundle = readBundleEntry(parser, values);
1738 bundleList.add(childBundle);
1739 }
1740 restrictions.putParcelableArray(key,
1741 bundleList.toArray(new Bundle[bundleList.size()]));
1742 } else {
1743 String value = parser.nextText().trim();
1744 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
1745 restrictions.putBoolean(key, Boolean.parseBoolean(value));
1746 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
1747 restrictions.putInt(key, Integer.parseInt(value));
1748 } else {
1749 restrictions.putString(key, value);
1750 }
1751 }
1752 }
1753 }
1754
1755 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
1756 throws IOException, XmlPullParserException {
1757 Bundle childBundle = new Bundle();
1758 final int outerDepth = parser.getDepth();
1759 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
1760 readEntry(childBundle, values, parser);
1761 }
1762 return childBundle;
1763 }
1764
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001765 private void writeApplicationRestrictionsLocked(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001766 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001767 AtomicFile restrictionsFile = new AtomicFile(
1768 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07001769 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001770 writeApplicationRestrictionsLocked(restrictions, restrictionsFile);
1771 }
1772
1773 @VisibleForTesting
1774 static void writeApplicationRestrictionsLocked(Bundle restrictions,
1775 AtomicFile restrictionsFile) {
1776 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001777 try {
1778 fos = restrictionsFile.startWrite();
1779 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1780
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001781 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001782 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001783 serializer.startDocument(null, true);
1784 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1785
1786 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001787 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001788 serializer.endTag(null, TAG_RESTRICTIONS);
1789
1790 serializer.endDocument();
1791 restrictionsFile.finishWrite(fos);
1792 } catch (Exception e) {
1793 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001794 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
1795 }
1796 }
1797
1798 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
1799 throws IOException {
1800 for (String key : restrictions.keySet()) {
1801 Object value = restrictions.get(key);
1802 serializer.startTag(null, TAG_ENTRY);
1803 serializer.attribute(null, ATTR_KEY, key);
1804
1805 if (value instanceof Boolean) {
1806 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
1807 serializer.text(value.toString());
1808 } else if (value instanceof Integer) {
1809 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
1810 serializer.text(value.toString());
1811 } else if (value == null || value instanceof String) {
1812 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
1813 serializer.text(value != null ? (String) value : "");
1814 } else if (value instanceof Bundle) {
1815 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
1816 writeBundle((Bundle) value, serializer);
1817 } else if (value instanceof Parcelable[]) {
1818 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
1819 Parcelable[] array = (Parcelable[]) value;
1820 for (Parcelable parcelable : array) {
1821 if (!(parcelable instanceof Bundle)) {
1822 throw new IllegalArgumentException("bundle-array can only hold Bundles");
1823 }
1824 serializer.startTag(null, TAG_ENTRY);
1825 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
1826 writeBundle((Bundle) parcelable, serializer);
1827 serializer.endTag(null, TAG_ENTRY);
1828 }
1829 } else {
1830 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
1831 String[] values = (String[]) value;
1832 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
1833 for (String choice : values) {
1834 serializer.startTag(null, TAG_VALUE);
1835 serializer.text(choice != null ? choice : "");
1836 serializer.endTag(null, TAG_VALUE);
1837 }
1838 }
1839 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001840 }
1841 }
1842
1843 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07001844 public int getUserSerialNumber(int userHandle) {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001845 synchronized (mPackagesLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001846 if (!exists(userHandle)) return -1;
Amith Yamasani195263742012-08-21 15:40:12 -07001847 return getUserInfoLocked(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07001848 }
1849 }
1850
1851 @Override
1852 public int getUserHandle(int userSerialNumber) {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001853 synchronized (mPackagesLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001854 for (int userId : mUserIds) {
Kenny Guy945f8832015-02-10 15:17:26 +00001855 UserInfo info = getUserInfoLocked(userId);
1856 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07001857 }
1858 // Not found
1859 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07001860 }
1861 }
1862
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07001863 @Override
1864 public long getUserCreationTime(int userHandle) {
1865 int callingUserId = UserHandle.getCallingUserId();
1866 UserInfo userInfo = null;
1867 synchronized (mPackagesLock) {
1868 if (callingUserId == userHandle) {
1869 userInfo = getUserInfoLocked(userHandle);
1870 } else {
1871 UserInfo parent = getProfileParentLocked(userHandle);
1872 if (parent != null && parent.id == callingUserId) {
1873 userInfo = getUserInfoLocked(userHandle);
1874 }
1875 }
1876 }
1877 if (userInfo == null) {
1878 throw new SecurityException("userHandle can only be the calling user or a managed "
1879 + "profile associated with this user");
1880 }
1881 return userInfo.creationTime;
1882 }
1883
Amith Yamasani0b285492011-04-14 17:35:23 -07001884 /**
1885 * Caches the list of user ids in an array, adjusting the array size when necessary.
1886 */
Amith Yamasani13593602012-03-22 16:16:17 -07001887 private void updateUserIdsLocked() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001888 int num = 0;
Amith Yamasani515d4062015-09-28 11:30:06 -07001889 final int userSize = mUsers.size();
1890 for (int i = 0; i < userSize; i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001891 if (!mUsers.valueAt(i).partial) {
1892 num++;
1893 }
1894 }
Amith Yamasani16389312012-10-17 21:20:14 -07001895 final int[] newUsers = new int[num];
1896 int n = 0;
Amith Yamasani515d4062015-09-28 11:30:06 -07001897 for (int i = 0; i < userSize; i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001898 if (!mUsers.valueAt(i).partial) {
Amith Yamasani16389312012-10-17 21:20:14 -07001899 newUsers[n++] = mUsers.keyAt(i);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001900 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001901 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001902 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07001903 }
1904
1905 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001906 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasani920ace02012-09-20 22:15:37 -07001907 * @param userId the user that was just foregrounded
1908 */
Amith Yamasani06bf8242015-05-08 16:36:21 -07001909 public void onUserForeground(int userId) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001910 synchronized (mPackagesLock) {
1911 UserInfo user = mUsers.get(userId);
1912 long now = System.currentTimeMillis();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001913 if (user == null || user.partial) {
1914 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
1915 return;
1916 }
1917 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001918 user.lastLoggedInTime = now;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001919 scheduleWriteUserLocked(user);
Amith Yamasani920ace02012-09-20 22:15:37 -07001920 }
1921 }
1922 }
1923
1924 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07001925 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani742a6712011-05-04 14:49:28 -07001926 * TODO: May not be a good idea to recycle ids, in case it results in confusion
1927 * for data and battery stats collection, or unexpected cross-talk.
Amith Yamasani0b285492011-04-14 17:35:23 -07001928 * @return
1929 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001930 private int getNextAvailableIdLocked() {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001931 synchronized (mPackagesLock) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001932 int i = MIN_USER_ID;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07001933 while (i < MAX_USER_ID) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001934 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07001935 return i;
Amith Yamasani195263742012-08-21 15:40:12 -07001936 }
1937 i++;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001938 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001939 }
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07001940 throw new IllegalStateException("No user id available!");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001941 }
Amith Yamasani920ace02012-09-20 22:15:37 -07001942
Amith Yamasanifc95e702013-09-26 13:20:17 -07001943 private String packageToRestrictionsFileName(String packageName) {
1944 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
1945 }
1946
Jeff Sharkey6dce4962015-07-03 18:08:41 -07001947 /**
1948 * Create new {@code /data/user/[id]} directory and sets default
1949 * permissions.
1950 */
Jeff Sharkey3bb8c852015-07-06 16:44:23 -07001951 public static void prepareUserDirectory(Context context, String volumeUuid, int userId) {
1952 final StorageManager storage = context.getSystemService(StorageManager.class);
1953 final File userDir = Environment.getDataUserDirectory(volumeUuid, userId);
1954 storage.createNewUserDir(userId, userDir);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07001955 }
1956
1957 /**
1958 * Enforce that serial number stored in user directory inode matches the
1959 * given expected value. Gracefully sets the serial number if currently
1960 * undefined.
1961 *
1962 * @throws IOException when problem extracting serial number, or serial
1963 * number is mismatched.
1964 */
1965 public static void enforceSerialNumber(File file, int serialNumber) throws IOException {
1966 final int foundSerial = getSerialNumber(file);
1967 Slog.v(LOG_TAG, "Found " + file + " with serial number " + foundSerial);
1968
1969 if (foundSerial == -1) {
1970 Slog.d(LOG_TAG, "Serial number missing on " + file + "; assuming current is valid");
1971 try {
1972 setSerialNumber(file, serialNumber);
1973 } catch (IOException e) {
1974 Slog.w(LOG_TAG, "Failed to set serial number on " + file, e);
1975 }
1976
1977 } else if (foundSerial != serialNumber) {
1978 throw new IOException("Found serial number " + foundSerial
1979 + " doesn't match expected " + serialNumber);
1980 }
1981 }
1982
1983 /**
1984 * Set serial number stored in user directory inode.
1985 *
1986 * @throws IOException if serial number was already set
1987 */
1988 private static void setSerialNumber(File file, int serialNumber)
1989 throws IOException {
1990 try {
1991 final byte[] buf = Integer.toString(serialNumber).getBytes(StandardCharsets.UTF_8);
1992 Os.setxattr(file.getAbsolutePath(), XATTR_SERIAL, buf, OsConstants.XATTR_CREATE);
1993 } catch (ErrnoException e) {
1994 throw e.rethrowAsIOException();
1995 }
1996 }
1997
1998 /**
1999 * Return serial number stored in user directory inode.
2000 *
2001 * @return parsed serial number, or -1 if not set
2002 */
2003 private static int getSerialNumber(File file) throws IOException {
2004 try {
2005 final byte[] buf = new byte[256];
2006 final int len = Os.getxattr(file.getAbsolutePath(), XATTR_SERIAL, buf);
2007 final String serial = new String(buf, 0, len);
2008 try {
2009 return Integer.parseInt(serial);
2010 } catch (NumberFormatException e) {
2011 throw new IOException("Bad serial number: " + serial);
2012 }
2013 } catch (ErrnoException e) {
2014 if (e.errno == OsConstants.ENODATA) {
2015 return -1;
2016 } else {
2017 throw e.rethrowAsIOException();
2018 }
2019 }
2020 }
2021
Amith Yamasani920ace02012-09-20 22:15:37 -07002022 @Override
2023 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2024 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2025 != PackageManager.PERMISSION_GRANTED) {
2026 pw.println("Permission Denial: can't dump UserManager from from pid="
2027 + Binder.getCallingPid()
2028 + ", uid=" + Binder.getCallingUid()
2029 + " without permission "
2030 + android.Manifest.permission.DUMP);
2031 return;
2032 }
2033
2034 long now = System.currentTimeMillis();
2035 StringBuilder sb = new StringBuilder();
2036 synchronized (mPackagesLock) {
2037 pw.println("Users:");
2038 for (int i = 0; i < mUsers.size(); i++) {
2039 UserInfo user = mUsers.valueAt(i);
2040 if (user == null) continue;
Amith Yamasani634cf312012-10-04 17:34:21 -07002041 pw.print(" "); pw.print(user); pw.print(" serialNo="); pw.print(user.serialNumber);
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002042 if (mRemovingUserIds.get(mUsers.keyAt(i))) pw.print(" <removing> ");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002043 if (user.partial) pw.print(" <partial>");
2044 pw.println();
Amith Yamasani920ace02012-09-20 22:15:37 -07002045 pw.print(" Created: ");
2046 if (user.creationTime == 0) {
2047 pw.println("<unknown>");
2048 } else {
2049 sb.setLength(0);
2050 TimeUtils.formatDuration(now - user.creationTime, sb);
2051 sb.append(" ago");
2052 pw.println(sb);
2053 }
2054 pw.print(" Last logged in: ");
2055 if (user.lastLoggedInTime == 0) {
2056 pw.println("<unknown>");
2057 } else {
2058 sb.setLength(0);
2059 TimeUtils.formatDuration(now - user.lastLoggedInTime, sb);
2060 sb.append(" ago");
2061 pw.println(sb);
2062 }
Makoto Onukia4f11972015-10-01 13:19:58 -07002063 pw.println(" Restrictions:");
2064 UserRestrictionsUtils.dumpRestrictions(
2065 pw, " ", mUserRestrictions.get(user.id));
Amith Yamasani920ace02012-09-20 22:15:37 -07002066 }
Makoto Onukia4f11972015-10-01 13:19:58 -07002067 pw.println();
2068 pw.println("Guest restrictions:");
2069 UserRestrictionsUtils.dumpRestrictions(pw, " ", mGuestRestrictions);
Amith Yamasani920ace02012-09-20 22:15:37 -07002070 }
2071 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002072
2073 final class MainHandler extends Handler {
2074
2075 @Override
2076 public void handleMessage(Message msg) {
2077 switch (msg.what) {
2078 case WRITE_USER_MSG:
2079 removeMessages(WRITE_USER_MSG, msg.obj);
2080 synchronized (mPackagesLock) {
2081 int userId = ((UserInfo) msg.obj).id;
2082 UserInfo userInfo = mUsers.get(userId);
2083 if (userInfo != null) {
2084 writeUserLocked(userInfo);
2085 }
2086 }
2087 }
2088 }
2089 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07002090
2091 /**
2092 * @param userId
2093 * @return whether the user has been initialized yet
2094 */
2095 boolean isInitialized(int userId) {
2096 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
2097 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002098}