blob: 9dc8875a725ba80f09ac3f8dc748e441ea297080 [file] [log] [blame]
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -070019import android.accounts.Account;
Xiaohui Chen594f2082015-08-18 11:04:20 -070020import android.annotation.NonNull;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070021import android.app.Activity;
Amith Yamasani2a003292012-08-14 18:25:45 -070022import android.app.ActivityManager;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070023import android.app.ActivityManagerNative;
24import android.app.IStopUserCallback;
Xiaohui Chen203243a2015-07-16 11:55:47 -070025import android.app.admin.DevicePolicyManager;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070026import android.content.BroadcastReceiver;
Amith Yamasani258848d2012-08-10 17:06:33 -070027import android.content.Context;
28import android.content.Intent;
Amith Yamasani1a7472e2013-07-02 11:17:30 -070029import android.content.pm.ApplicationInfo;
Amith Yamasani0b285492011-04-14 17:35:23 -070030import android.content.pm.PackageManager;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -080031import android.content.pm.PackageManager.NameNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070032import android.content.pm.UserInfo;
Amith Yamasanie928d7d2012-09-17 21:46:51 -070033import android.graphics.Bitmap;
Amith Yamasani258848d2012-08-10 17:06:33 -070034import android.os.Binder;
Amith Yamasanie4cf7342012-12-17 11:12:09 -080035import android.os.Bundle;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070036import android.os.Environment;
37import android.os.FileUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080038import android.os.Handler;
Amith Yamasani258848d2012-08-10 17:06:33 -070039import android.os.IUserManager;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -080040import android.os.Message;
Adrian Roos1bdff912015-02-17 15:51:35 +010041import android.os.ParcelFileDescriptor;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070042import android.os.Parcelable;
Amith Yamasani258848d2012-08-10 17:06:33 -070043import android.os.Process;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070044import android.os.RemoteException;
Jason Monk62062992014-05-06 09:55:28 -040045import android.os.ServiceManager;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070046import android.os.UserHandle;
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070047import android.os.UserManager;
Paul Crowley85e4e812015-05-19 12:42:00 +010048import android.os.storage.StorageManager;
Jeff Sharkey6dce4962015-07-03 18:08:41 -070049import android.os.storage.VolumeInfo;
50import android.system.ErrnoException;
51import android.system.Os;
52import android.system.OsConstants;
Amith Yamasani2a003292012-08-14 18:25:45 -070053import android.util.AtomicFile;
Amith Yamasani655d0e22013-06-12 14:19:10 -070054import android.util.Log;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070055import android.util.Slog;
56import android.util.SparseArray;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080057import android.util.SparseBooleanArray;
Amith Yamasani920ace02012-09-20 22:15:37 -070058import android.util.TimeUtils;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070059import android.util.Xml;
60
Fyodor Kupolovb5013302015-04-17 17:59:14 -070061import com.google.android.collect.Sets;
62
Fyodor Kupolov262f9952015-03-23 18:55:11 -070063import com.android.internal.annotations.VisibleForTesting;
Jason Monk62062992014-05-06 09:55:28 -040064import com.android.internal.app.IAppOpsService;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080065import com.android.internal.util.FastXmlSerializer;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070066import com.android.internal.util.XmlUtils;
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -070067import com.android.server.accounts.AccountManagerService;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080068
69import org.xmlpull.v1.XmlPullParser;
70import org.xmlpull.v1.XmlPullParserException;
71import org.xmlpull.v1.XmlSerializer;
72
Amith Yamasani4b2e9342011-03-31 12:38:53 -070073import java.io.BufferedOutputStream;
74import java.io.File;
Amith Yamasani920ace02012-09-20 22:15:37 -070075import java.io.FileDescriptor;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070076import java.io.FileInputStream;
Amith Yamasanib8151ec2012-04-18 18:02:48 -070077import java.io.FileNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070078import java.io.FileOutputStream;
79import java.io.IOException;
Amith Yamasani920ace02012-09-20 22:15:37 -070080import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +010081import java.nio.charset.StandardCharsets;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070082import java.util.ArrayList;
83import java.util.List;
Fyodor Kupolovb5013302015-04-17 17:59:14 -070084import java.util.Set;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070085
Fyodor Kupolov262f9952015-03-23 18:55:11 -070086import libcore.io.IoUtils;
87
Amith Yamasani258848d2012-08-10 17:06:33 -070088public class UserManagerService extends IUserManager.Stub {
Amith Yamasanib8151ec2012-04-18 18:02:48 -070089
Amith Yamasani2a003292012-08-14 18:25:45 -070090 private static final String LOG_TAG = "UserManagerService";
Amith Yamasanib8151ec2012-04-18 18:02:48 -070091
Amith Yamasani16389312012-10-17 21:20:14 -070092 private static final boolean DBG = false;
93
Amith Yamasani4b2e9342011-03-31 12:38:53 -070094 private static final String TAG_NAME = "name";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070095 private static final String ATTR_FLAGS = "flags";
Amith Yamasanib8151ec2012-04-18 18:02:48 -070096 private static final String ATTR_ICON_PATH = "icon";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070097 private static final String ATTR_ID = "id";
Amith Yamasani920ace02012-09-20 22:15:37 -070098 private static final String ATTR_CREATION_TIME = "created";
99 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
Amith Yamasani2a003292012-08-14 18:25:45 -0700100 private static final String ATTR_SERIAL_NO = "serialNumber";
101 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700102 private static final String ATTR_PARTIAL = "partial";
Adam Lesinskieddeb492014-09-08 17:50:03 -0700103 private static final String ATTR_GUEST_TO_REMOVE = "guestToRemove";
Amith Yamasani6f34b412012-10-22 18:19:27 -0700104 private static final String ATTR_USER_VERSION = "version";
Kenny Guy2a764942014-04-02 13:29:20 +0100105 private static final String ATTR_PROFILE_GROUP_ID = "profileGroupId";
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700106 private static final String ATTR_RESTRICTED_PROFILE_PARENT_ID = "restrictedProfileParentId";
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530107 private static final String TAG_GUEST_RESTRICTIONS = "guestRestrictions";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700108 private static final String TAG_USERS = "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700109 private static final String TAG_USER = "user";
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800110 private static final String TAG_RESTRICTIONS = "restrictions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800111 private static final String TAG_ENTRY = "entry";
112 private static final String TAG_VALUE = "value";
113 private static final String ATTR_KEY = "key";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700114 private static final String ATTR_VALUE_TYPE = "type";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800115 private static final String ATTR_MULTIPLE = "m";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700116
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700117 private static final String ATTR_TYPE_STRING_ARRAY = "sa";
118 private static final String ATTR_TYPE_STRING = "s";
119 private static final String ATTR_TYPE_BOOLEAN = "b";
Amith Yamasani5b5aa402014-06-01 20:10:14 -0700120 private static final String ATTR_TYPE_INTEGER = "i";
Fyodor Kupolov262f9952015-03-23 18:55:11 -0700121 private static final String ATTR_TYPE_BUNDLE = "B";
122 private static final String ATTR_TYPE_BUNDLE_ARRAY = "BA";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700123
Amith Yamasani0b285492011-04-14 17:35:23 -0700124 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700125 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700126 private static final String USER_PHOTO_FILENAME = "photo.png";
Adrian Roos1bdff912015-02-17 15:51:35 +0100127 private static final String USER_PHOTO_FILENAME_TMP = USER_PHOTO_FILENAME + ".tmp";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700128
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800129 private static final String RESTRICTIONS_FILE_PREFIX = "res_";
Amith Yamasanifc95e702013-09-26 13:20:17 -0700130 private static final String XML_SUFFIX = ".xml";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800131
Amith Yamasani634cf312012-10-04 17:34:21 -0700132 private static final int MIN_USER_ID = 10;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700133 // We need to keep process uid within Integer.MAX_VALUE.
134 private static final int MAX_USER_ID = Integer.MAX_VALUE / UserHandle.PER_USER_RANGE;
Amith Yamasani634cf312012-10-04 17:34:21 -0700135
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700136 private static final int USER_VERSION = 6;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700137
Amith Yamasani920ace02012-09-20 22:15:37 -0700138 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
139
Nicolas Prevotb8186812015-08-06 15:00:03 +0100140 // Maximum number of managed profiles permitted per user is 1. This cannot be increased
Amith Yamasani95ab7842014-08-11 17:09:26 -0700141 // without first making sure that the rest of the framework is prepared for it.
142 private static final int MAX_MANAGED_PROFILES = 1;
143
Andres Moralesc5548c02015-08-05 10:23:12 -0700144 /**
145 * Flag indicating whether device credentials are shared among same-user profiles.
146 */
147 private static final boolean CONFIG_PROFILES_SHARE_CREDENTIAL = true;
148
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700149 // Set of user restrictions, which can only be enforced by the system
150 private static final Set<String> SYSTEM_CONTROLLED_RESTRICTIONS = Sets.newArraySet(
151 UserManager.DISALLOW_RECORD_AUDIO);
152
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800153 static final int WRITE_USER_MSG = 1;
154 static final int WRITE_USER_DELAY = 2*1000; // 2 seconds
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530155
Jeff Sharkey6dce4962015-07-03 18:08:41 -0700156 private static final String XATTR_SERIAL = "user.serial";
157
Dianne Hackborn4428e172012-08-24 17:43:05 -0700158 private final Context mContext;
159 private final PackageManagerService mPm;
160 private final Object mInstallLock;
161 private final Object mPackagesLock;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700162
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800163 private final Handler mHandler;
164
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700165 private final File mUsersDir;
166 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700167
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800168 private final SparseArray<UserInfo> mUsers = new SparseArray<UserInfo>();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800169 private final SparseArray<Bundle> mUserRestrictions = new SparseArray<Bundle>();
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530170 private final Bundle mGuestRestrictions = new Bundle();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800171
172 /**
173 * Set of user IDs being actively removed. Removed IDs linger in this set
174 * for several seconds to work around a VFS caching issue.
175 */
176 // @GuardedBy("mPackagesLock")
177 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700178
Amith Yamasani0b285492011-04-14 17:35:23 -0700179 private int[] mUserIds;
Amith Yamasani2a003292012-08-14 18:25:45 -0700180 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700181 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700182
Jason Monk62062992014-05-06 09:55:28 -0400183 private IAppOpsService mAppOpsService;
184
Amith Yamasani258848d2012-08-10 17:06:33 -0700185 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700186
Dianne Hackborn4428e172012-08-24 17:43:05 -0700187 public static UserManagerService getInstance() {
188 synchronized (UserManagerService.class) {
189 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700190 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700191 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700192
193 /**
194 * Available for testing purposes.
195 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700196 UserManagerService(File dataDir, File baseUserPath) {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700197 this(null, null, new Object(), new Object(), dataDir, baseUserPath);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700198 }
199
Dianne Hackborn4428e172012-08-24 17:43:05 -0700200 /**
201 * Called by package manager to create the service. This is closely
202 * associated with the package manager, and the given lock is the
203 * package manager's own lock.
204 */
205 UserManagerService(Context context, PackageManagerService pm,
206 Object installLock, Object packagesLock) {
207 this(context, pm, installLock, packagesLock,
208 Environment.getDataDirectory(),
209 new File(Environment.getDataDirectory(), "user"));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700210 }
211
Dianne Hackborn4428e172012-08-24 17:43:05 -0700212 /**
213 * Available for testing purposes.
214 */
215 private UserManagerService(Context context, PackageManagerService pm,
216 Object installLock, Object packagesLock,
217 File dataDir, File baseUserPath) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700218 mContext = context;
219 mPm = pm;
220 mInstallLock = installLock;
221 mPackagesLock = packagesLock;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800222 mHandler = new MainHandler();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700223 synchronized (mInstallLock) {
224 synchronized (mPackagesLock) {
225 mUsersDir = new File(dataDir, USER_INFO_DIR);
226 mUsersDir.mkdirs();
227 // Make zeroth user directory, for services to migrate their files to that location
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700228 File userZeroDir = new File(mUsersDir, String.valueOf(UserHandle.USER_SYSTEM));
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700229 userZeroDir.mkdirs();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700230 FileUtils.setPermissions(mUsersDir.toString(),
231 FileUtils.S_IRWXU|FileUtils.S_IRWXG
232 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
233 -1, -1);
234 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
Amith Yamasanida0b1682014-11-21 12:58:17 -0800235 initDefaultGuestRestrictions();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700236 readUserListLocked();
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700237 sInstance = this;
238 }
239 }
240 }
241
242 void systemReady() {
243 synchronized (mInstallLock) {
244 synchronized (mPackagesLock) {
Amith Yamasani756901d2012-10-12 12:30:07 -0700245 // Prune out any partially created/partially removed users.
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700246 ArrayList<UserInfo> partials = new ArrayList<UserInfo>();
247 for (int i = 0; i < mUsers.size(); i++) {
248 UserInfo ui = mUsers.valueAt(i);
Adam Lesinskieddeb492014-09-08 17:50:03 -0700249 if ((ui.partial || ui.guestToRemove) && i != 0) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700250 partials.add(ui);
251 }
252 }
253 for (int i = 0; i < partials.size(); i++) {
254 UserInfo ui = partials.get(i);
Amith Yamasania7892482015-08-07 11:09:05 -0700255 Slog.w(LOG_TAG, "Removing partially created user " + ui.id
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700256 + " (name=" + ui.name + ")");
257 removeUserStateLocked(ui.id);
258 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700259 }
Dianne Hackborn4428e172012-08-24 17:43:05 -0700260 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700261 onUserForeground(UserHandle.USER_SYSTEM);
Jason Monk62062992014-05-06 09:55:28 -0400262 mAppOpsService = IAppOpsService.Stub.asInterface(
263 ServiceManager.getService(Context.APP_OPS_SERVICE));
264 for (int i = 0; i < mUserIds.length; ++i) {
265 try {
266 mAppOpsService.setUserRestrictions(mUserRestrictions.get(mUserIds[i]), mUserIds[i]);
267 } catch (RemoteException e) {
268 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
269 }
270 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700271 }
272
273 @Override
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700274 public UserInfo getPrimaryUser() {
275 checkManageUsersPermission("query users");
276 synchronized (mPackagesLock) {
277 for (int i = 0; i < mUsers.size(); i++) {
278 UserInfo ui = mUsers.valueAt(i);
279 if (ui.isPrimary()) {
280 return ui;
281 }
282 }
283 }
284 return null;
285 }
286
287 @Override
Xiaohui Chen594f2082015-08-18 11:04:20 -0700288 public @NonNull List<UserInfo> getUsers(boolean excludeDying) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700289 checkManageUsersPermission("query users");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700290 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700291 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
292 for (int i = 0; i < mUsers.size(); i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700293 UserInfo ui = mUsers.valueAt(i);
294 if (ui.partial) {
295 continue;
296 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800297 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700298 users.add(ui);
Amith Yamasani920ace02012-09-20 22:15:37 -0700299 }
Amith Yamasani13593602012-03-22 16:16:17 -0700300 }
301 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700302 }
Amith Yamasani13593602012-03-22 16:16:17 -0700303 }
304
Amith Yamasani258848d2012-08-10 17:06:33 -0700305 @Override
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100306 public List<UserInfo> getProfiles(int userId, boolean enabledOnly) {
Amith Yamasani4f582632014-02-19 14:31:52 -0800307 if (userId != UserHandle.getCallingUserId()) {
308 checkManageUsersPermission("getting profiles related to user " + userId);
309 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700310 final long ident = Binder.clearCallingIdentity();
311 try {
312 synchronized (mPackagesLock) {
313 return getProfilesLocked(userId, enabledOnly);
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100314 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700315 } finally {
316 Binder.restoreCallingIdentity(ident);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000317 }
318 }
319
Amith Yamasanibe465322014-04-24 13:45:17 -0700320 /** Assume permissions already checked and caller's identity cleared */
321 private List<UserInfo> getProfilesLocked(int userId, boolean enabledOnly) {
Amith Yamasanibe465322014-04-24 13:45:17 -0700322 UserInfo user = getUserInfoLocked(userId);
323 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasanidda003f2014-08-28 18:06:51 -0700324 if (user == null) {
325 // Probably a dying user
326 return users;
327 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700328 for (int i = 0; i < mUsers.size(); i++) {
329 UserInfo profile = mUsers.valueAt(i);
330 if (!isProfileOf(user, profile)) {
331 continue;
332 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100333 if (enabledOnly && !profile.isEnabled()) {
334 continue;
Amith Yamasanibe465322014-04-24 13:45:17 -0700335 }
Amith Yamasani70fcf0c2014-07-11 08:40:19 -0700336 if (mRemovingUserIds.get(profile.id)) {
337 continue;
338 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700339 users.add(profile);
340 }
341 return users;
342 }
343
Jessica Hummelbe81c802014-04-22 15:49:22 +0100344 @Override
Andres Moralesc5548c02015-08-05 10:23:12 -0700345 public int getCredentialOwnerProfile(int userHandle) {
346 checkManageUsersPermission("get the credential owner");
347 if (CONFIG_PROFILES_SHARE_CREDENTIAL) {
348 synchronized (mPackagesLock) {
349 UserInfo profileParent = getProfileParentLocked(userHandle);
350 if (profileParent != null) {
351 return profileParent.id;
352 }
353 }
354 }
355
356 return userHandle;
357 }
358
359 @Override
Jessica Hummelbe81c802014-04-22 15:49:22 +0100360 public UserInfo getProfileParent(int userHandle) {
361 checkManageUsersPermission("get the profile parent");
362 synchronized (mPackagesLock) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700363 return getProfileParentLocked(userHandle);
364 }
365 }
366
367 private UserInfo getProfileParentLocked(int userHandle) {
368 UserInfo profile = getUserInfoLocked(userHandle);
369 if (profile == null) {
370 return null;
371 }
372 int parentUserId = profile.profileGroupId;
373 if (parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
374 return null;
375 } else {
376 return getUserInfoLocked(parentUserId);
Jessica Hummelbe81c802014-04-22 15:49:22 +0100377 }
378 }
379
Kenny Guy2a764942014-04-02 13:29:20 +0100380 private boolean isProfileOf(UserInfo user, UserInfo profile) {
381 return user.id == profile.id ||
382 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
383 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000384 }
385
386 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100387 public void setUserEnabled(int userId) {
388 checkManageUsersPermission("enable user");
389 synchronized (mPackagesLock) {
390 UserInfo info = getUserInfoLocked(userId);
391 if (info != null && !info.isEnabled()) {
392 info.flags ^= UserInfo.FLAG_DISABLED;
393 writeUserLocked(info);
394 }
395 }
396 }
397
398 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700399 public UserInfo getUserInfo(int userId) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700400 checkManageUsersPermission("query user");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700401 synchronized (mPackagesLock) {
Amith Yamasani195263742012-08-21 15:40:12 -0700402 return getUserInfoLocked(userId);
Amith Yamasani13593602012-03-22 16:16:17 -0700403 }
404 }
405
Amith Yamasani71e6c692013-03-24 17:39:28 -0700406 @Override
407 public boolean isRestricted() {
408 synchronized (mPackagesLock) {
409 return getUserInfoLocked(UserHandle.getCallingUserId()).isRestricted();
410 }
411 }
412
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700413 @Override
414 public boolean canHaveRestrictedProfile(int userId) {
415 checkManageUsersPermission("canHaveRestrictedProfile");
416 synchronized (mPackagesLock) {
417 final UserInfo userInfo = getUserInfoLocked(userId);
418 if (userInfo == null || !userInfo.canHaveProfile()) {
419 return false;
420 }
421 if (!userInfo.isAdmin()) {
422 return false;
423 }
424 }
425 DevicePolicyManager dpm = (DevicePolicyManager) mContext.getSystemService(
426 Context.DEVICE_POLICY_SERVICE);
427 // restricted profile can be created if there is no DO set and the admin user has no PO
428 return dpm.getDeviceOwner() == null && dpm.getProfileOwnerAsUser(userId) == null;
429 }
430
Amith Yamasani195263742012-08-21 15:40:12 -0700431 /*
432 * Should be locked on mUsers before calling this.
433 */
434 private UserInfo getUserInfoLocked(int userId) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700435 UserInfo ui = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -0700436 // If it is partial and not in the process of being removed, return as unknown user.
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800437 if (ui != null && ui.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700438 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
439 return null;
440 }
441 return ui;
Amith Yamasani195263742012-08-21 15:40:12 -0700442 }
443
Amith Yamasani236b2b52015-08-18 14:32:14 -0700444 /** Called by PackageManagerService */
Amith Yamasani13593602012-03-22 16:16:17 -0700445 public boolean exists(int userId) {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700446 synchronized (mPackagesLock) {
Amith Yamasani236b2b52015-08-18 14:32:14 -0700447 return mUsers.get(userId) != null;
Amith Yamasani13593602012-03-22 16:16:17 -0700448 }
449 }
450
Amith Yamasani258848d2012-08-10 17:06:33 -0700451 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700452 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700453 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700454 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700455 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700456 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700457 if (info == null || info.partial) {
458 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
459 return;
460 }
Amith Yamasani13593602012-03-22 16:16:17 -0700461 if (name != null && !name.equals(info.name)) {
462 info.name = name;
463 writeUserLocked(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700464 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -0700465 }
466 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700467 if (changed) {
468 sendUserInfoChangedBroadcast(userId);
469 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700470 }
471
Amith Yamasani258848d2012-08-10 17:06:33 -0700472 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700473 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700474 checkManageUsersPermission("update users");
Jason Monk9a944532014-07-08 09:31:21 -0400475 long ident = Binder.clearCallingIdentity();
476 try {
477 synchronized (mPackagesLock) {
478 UserInfo info = mUsers.get(userId);
479 if (info == null || info.partial) {
480 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
481 return;
482 }
483 writeBitmapLocked(info, bitmap);
484 writeUserLocked(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700485 }
Jason Monk9a944532014-07-08 09:31:21 -0400486 sendUserInfoChangedBroadcast(userId);
487 } finally {
488 Binder.restoreCallingIdentity(ident);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700489 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700490 }
491
492 private void sendUserInfoChangedBroadcast(int userId) {
493 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
494 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
495 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -0700496 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700497 }
498
Amith Yamasani258848d2012-08-10 17:06:33 -0700499 @Override
Adrian Roos1bdff912015-02-17 15:51:35 +0100500 public ParcelFileDescriptor getUserIcon(int userId) {
501 String iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700502 synchronized (mPackagesLock) {
503 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700504 if (info == null || info.partial) {
505 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + userId);
506 return null;
507 }
Nicolas Prevot88cc3462014-05-14 14:51:48 +0100508 int callingGroupId = mUsers.get(UserHandle.getCallingUserId()).profileGroupId;
509 if (callingGroupId == UserInfo.NO_PROFILE_GROUP_ID
510 || callingGroupId != info.profileGroupId) {
511 checkManageUsersPermission("get the icon of a user who is not related");
512 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700513 if (info.iconPath == null) {
514 return null;
515 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100516 iconPath = info.iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700517 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100518
519 try {
520 return ParcelFileDescriptor.open(
521 new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
522 } catch (FileNotFoundException e) {
523 Log.e(LOG_TAG, "Couldn't find icon file", e);
524 }
525 return null;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700526 }
527
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700528 public void makeInitialized(int userId) {
529 checkManageUsersPermission("makeInitialized");
530 synchronized (mPackagesLock) {
531 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700532 if (info == null || info.partial) {
533 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
534 }
535 if ((info.flags&UserInfo.FLAG_INITIALIZED) == 0) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700536 info.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800537 scheduleWriteUserLocked(info);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700538 }
539 }
540 }
541
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700542 /**
543 * If default guest restrictions haven't been initialized yet, add the basic
544 * restrictions.
545 */
546 private void initDefaultGuestRestrictions() {
547 if (mGuestRestrictions.isEmpty()) {
548 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
Amith Yamasanida0b1682014-11-21 12:58:17 -0800549 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700550 }
551 }
552
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800553 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530554 public Bundle getDefaultGuestRestrictions() {
555 checkManageUsersPermission("getDefaultGuestRestrictions");
556 synchronized (mPackagesLock) {
557 return new Bundle(mGuestRestrictions);
558 }
559 }
560
561 @Override
562 public void setDefaultGuestRestrictions(Bundle restrictions) {
563 checkManageUsersPermission("setDefaultGuestRestrictions");
564 synchronized (mPackagesLock) {
565 mGuestRestrictions.clear();
566 mGuestRestrictions.putAll(restrictions);
567 writeUserListLocked();
568 }
569 }
570
571 @Override
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700572 public boolean hasUserRestriction(String restrictionKey, int userId) {
573 synchronized (mPackagesLock) {
574 Bundle restrictions = mUserRestrictions.get(userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700575 return restrictions != null && restrictions.getBoolean(restrictionKey);
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700576 }
577 }
578
579 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800580 public Bundle getUserRestrictions(int userId) {
581 // checkManageUsersPermission("getUserRestrictions");
582
583 synchronized (mPackagesLock) {
584 Bundle restrictions = mUserRestrictions.get(userId);
Amith Yamasanibe465322014-04-24 13:45:17 -0700585 return restrictions != null ? new Bundle(restrictions) : new Bundle();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800586 }
587 }
588
589 @Override
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700590 public void setUserRestriction(String key, boolean value, int userId) {
Fyodor Kupolovd4b26042015-07-27 14:30:59 -0700591 checkManageUsersPermission("setUserRestriction");
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700592 synchronized (mPackagesLock) {
593 if (!SYSTEM_CONTROLLED_RESTRICTIONS.contains(key)) {
594 Bundle restrictions = getUserRestrictions(userId);
595 restrictions.putBoolean(key, value);
596 setUserRestrictionsInternalLocked(restrictions, userId);
597 }
598 }
599 }
600
601 @Override
602 public void setSystemControlledUserRestriction(String key, boolean value, int userId) {
603 checkSystemOrRoot("setSystemControlledUserRestriction");
604 synchronized (mPackagesLock) {
605 Bundle restrictions = getUserRestrictions(userId);
606 restrictions.putBoolean(key, value);
607 setUserRestrictionsInternalLocked(restrictions, userId);
608 }
609 }
610
611 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800612 public void setUserRestrictions(Bundle restrictions, int userId) {
Amith Yamasanibe465322014-04-24 13:45:17 -0700613 checkManageUsersPermission("setUserRestrictions");
Amith Yamasani0343ec32013-07-22 14:52:06 -0700614 if (restrictions == null) return;
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800615
616 synchronized (mPackagesLock) {
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700617 final Bundle oldUserRestrictions = mUserRestrictions.get(userId);
618 // Restore the original state of system controlled restrictions from oldUserRestrictions
619 for (String key : SYSTEM_CONTROLLED_RESTRICTIONS) {
620 restrictions.remove(key);
621 if (oldUserRestrictions.containsKey(key)) {
622 restrictions.putBoolean(key, oldUserRestrictions.getBoolean(key));
623 }
Jason Monk62062992014-05-06 09:55:28 -0400624 }
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700625 setUserRestrictionsInternalLocked(restrictions, userId);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800626 }
627 }
628
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700629 private void setUserRestrictionsInternalLocked(Bundle restrictions, int userId) {
630 final Bundle userRestrictions = mUserRestrictions.get(userId);
631 userRestrictions.clear();
632 userRestrictions.putAll(restrictions);
633 long token = Binder.clearCallingIdentity();
634 try {
635 mAppOpsService.setUserRestrictions(userRestrictions, userId);
636 } catch (RemoteException e) {
637 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
638 } finally {
639 Binder.restoreCallingIdentity(token);
640 }
641 scheduleWriteUserLocked(mUsers.get(userId));
642 }
643
Amith Yamasani258848d2012-08-10 17:06:33 -0700644 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700645 * Check if we've hit the limit of how many users can be created.
646 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700647 private boolean isUserLimitReachedLocked() {
Nicolas Prevot12678a92015-05-13 12:15:03 -0700648 return getAliveUsersExcludingGuestsCountLocked() >= UserManager.getMaxSupportedUsers();
649 }
650
651 @Override
Nicolas Prevotb8186812015-08-06 15:00:03 +0100652 public boolean canAddMoreManagedProfiles(int userId) {
Nicolas Prevot12678a92015-05-13 12:15:03 -0700653 checkManageUsersPermission("check if more managed profiles can be added.");
654 if (ActivityManager.isLowRamDeviceStatic()) {
655 return false;
656 }
Fyodor Kupolovb6157992015-06-05 15:32:28 -0700657 if (!mContext.getPackageManager().hasSystemFeature(
658 PackageManager.FEATURE_MANAGED_USERS)) {
659 return false;
660 }
Nicolas Prevotb8186812015-08-06 15:00:03 +0100661 // Limit number of managed profiles that can be created
662 int managedProfilesCount = getProfiles(userId, true).size() - 1;
663 if (managedProfilesCount >= MAX_MANAGED_PROFILES) {
664 return false;
665 }
Nicolas Prevot12678a92015-05-13 12:15:03 -0700666 synchronized(mPackagesLock) {
Nicolas Prevotb8186812015-08-06 15:00:03 +0100667 UserInfo userInfo = getUserInfoLocked(userId);
668 if (!userInfo.canHaveProfile()) {
Nicolas Prevot12678a92015-05-13 12:15:03 -0700669 return false;
670 }
671 int usersCount = getAliveUsersExcludingGuestsCountLocked();
672 // We allow creating a managed profile in the special case where there is only one user.
673 return usersCount == 1 || usersCount < UserManager.getMaxSupportedUsers();
674 }
675 }
676
677 private int getAliveUsersExcludingGuestsCountLocked() {
Amith Yamasanif584f012014-05-19 17:57:25 -0700678 int aliveUserCount = 0;
679 final int totalUserCount = mUsers.size();
680 // Skip over users being removed
681 for (int i = 0; i < totalUserCount; i++) {
682 UserInfo user = mUsers.valueAt(i);
Amith Yamasani95ab7842014-08-11 17:09:26 -0700683 if (!mRemovingUserIds.get(user.id)
Amith Yamasani1df14732014-08-29 21:37:27 -0700684 && !user.isGuest() && !user.partial) {
Amith Yamasanif584f012014-05-19 17:57:25 -0700685 aliveUserCount++;
686 }
687 }
Nicolas Prevot12678a92015-05-13 12:15:03 -0700688 return aliveUserCount;
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700689 }
690
691 /**
Amith Yamasani195263742012-08-21 15:40:12 -0700692 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -0700693 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -0700694 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -0700695 *
696 * @param message used as message if SecurityException is thrown
697 * @throws SecurityException if the caller is not system or root
698 */
Amith Yamasanibe465322014-04-24 13:45:17 -0700699 private static final void checkManageUsersPermission(String message) {
Amith Yamasani258848d2012-08-10 17:06:33 -0700700 final int uid = Binder.getCallingUid();
Amith Yamasanibe465322014-04-24 13:45:17 -0700701 if (uid != Process.SYSTEM_UID && uid != 0
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400702 && ActivityManager.checkComponentPermission(
703 android.Manifest.permission.MANAGE_USERS,
Amith Yamasanibe465322014-04-24 13:45:17 -0700704 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
705 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
706 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400707 }
708
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700709 private static void checkSystemOrRoot(String message) {
710 final int uid = Binder.getCallingUid();
711 if (uid != Process.SYSTEM_UID && uid != 0) {
712 throw new SecurityException("Only system may call: " + message);
713 }
714 }
715
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700716 private void writeBitmapLocked(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700717 try {
718 File dir = new File(mUsersDir, Integer.toString(info.id));
719 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +0100720 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700721 if (!dir.exists()) {
722 dir.mkdir();
723 FileUtils.setPermissions(
724 dir.getPath(),
725 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
726 -1, -1);
727 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700728 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +0100729 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
730 && tmp.renameTo(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -0700731 info.iconPath = file.getAbsolutePath();
732 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700733 try {
734 os.close();
735 } catch (IOException ioe) {
736 // What the ... !
737 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100738 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700739 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700740 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700741 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700742 }
743
Amith Yamasani0b285492011-04-14 17:35:23 -0700744 /**
745 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
746 * cache it elsewhere.
747 * @return the array of user ids.
748 */
Dianne Hackborn1676c852012-09-10 14:52:30 -0700749 public int[] getUserIds() {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700750 synchronized (mPackagesLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700751 return mUserIds;
752 }
Amith Yamasani0b285492011-04-14 17:35:23 -0700753 }
754
Dianne Hackborn4428e172012-08-24 17:43:05 -0700755 int[] getUserIdsLPr() {
756 return mUserIds;
757 }
758
Amith Yamasani13593602012-03-22 16:16:17 -0700759 private void readUserListLocked() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700760 if (!mUserListFile.exists()) {
Amith Yamasani13593602012-03-22 16:16:17 -0700761 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700762 return;
763 }
764 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700765 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700766 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700767 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700768 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100769 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700770 int type;
771 while ((type = parser.next()) != XmlPullParser.START_TAG
772 && type != XmlPullParser.END_DOCUMENT) {
773 ;
774 }
775
776 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700777 Slog.e(LOG_TAG, "Unable to read user list");
Amith Yamasani13593602012-03-22 16:16:17 -0700778 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700779 return;
780 }
781
Amith Yamasani2a003292012-08-14 18:25:45 -0700782 mNextSerialNumber = -1;
783 if (parser.getName().equals(TAG_USERS)) {
784 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
785 if (lastSerialNumber != null) {
786 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
787 }
Amith Yamasani6f34b412012-10-22 18:19:27 -0700788 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
789 if (versionNumber != null) {
790 mUserVersion = Integer.parseInt(versionNumber);
791 }
Amith Yamasani2a003292012-08-14 18:25:45 -0700792 }
793
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700794 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530795 if (type == XmlPullParser.START_TAG) {
796 final String name = parser.getName();
797 if (name.equals(TAG_USER)) {
798 String id = parser.getAttributeValue(null, ATTR_ID);
799 UserInfo user = readUserLocked(Integer.parseInt(id));
Amith Yamasani6f34b412012-10-22 18:19:27 -0700800
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530801 if (user != null) {
802 mUsers.put(user.id, user);
803 if (mNextSerialNumber < 0 || mNextSerialNumber <= user.id) {
804 mNextSerialNumber = user.id + 1;
805 }
Amith Yamasani2a003292012-08-14 18:25:45 -0700806 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530807 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -0800808 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
809 && type != XmlPullParser.END_TAG) {
810 if (type == XmlPullParser.START_TAG) {
811 if (parser.getName().equals(TAG_RESTRICTIONS)) {
812 readRestrictionsLocked(parser, mGuestRestrictions);
813 }
814 break;
815 }
816 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700817 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700818 }
819 }
Amith Yamasani13593602012-03-22 16:16:17 -0700820 updateUserIdsLocked();
Amith Yamasani350962c2013-08-06 11:18:53 -0700821 upgradeIfNecessaryLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700822 } catch (IOException ioe) {
Amith Yamasani13593602012-03-22 16:16:17 -0700823 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700824 } catch (XmlPullParserException pe) {
Amith Yamasani13593602012-03-22 16:16:17 -0700825 fallbackToSingleUserLocked();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -0800826 } finally {
827 if (fis != null) {
828 try {
829 fis.close();
830 } catch (IOException e) {
831 }
832 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700833 }
834 }
835
Amith Yamasani6f34b412012-10-22 18:19:27 -0700836 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -0800837 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -0700838 */
Amith Yamasani350962c2013-08-06 11:18:53 -0700839 private void upgradeIfNecessaryLocked() {
Amith Yamasani6f34b412012-10-22 18:19:27 -0700840 int userVersion = mUserVersion;
841 if (userVersion < 1) {
842 // Assign a proper name for the owner, if not initialized correctly before
843 UserInfo user = mUsers.get(UserHandle.USER_OWNER);
844 if ("Primary".equals(user.name)) {
845 user.name = mContext.getResources().getString(com.android.internal.R.string.owner_name);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800846 scheduleWriteUserLocked(user);
Amith Yamasani6f34b412012-10-22 18:19:27 -0700847 }
848 userVersion = 1;
849 }
850
Amith Yamasanibc9625052012-11-15 14:39:18 -0800851 if (userVersion < 2) {
852 // Owner should be marked as initialized
853 UserInfo user = mUsers.get(UserHandle.USER_OWNER);
854 if ((user.flags & UserInfo.FLAG_INITIALIZED) == 0) {
855 user.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800856 scheduleWriteUserLocked(user);
Amith Yamasanibc9625052012-11-15 14:39:18 -0800857 }
858 userVersion = 2;
859 }
860
Amith Yamasani350962c2013-08-06 11:18:53 -0700861
Amith Yamasani5e486f52013-08-07 11:06:44 -0700862 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -0700863 userVersion = 4;
864 }
865
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700866 if (userVersion < 5) {
867 initDefaultGuestRestrictions();
868 userVersion = 5;
869 }
870
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700871 if (userVersion < 6) {
872 final boolean splitSystemUser = UserManager.isSplitSystemUser();
873 for (int i = 0; i < mUsers.size(); i++) {
874 UserInfo user = mUsers.valueAt(i);
875 // In non-split mode, only user 0 can have restricted profiles
876 if (!splitSystemUser && user.isRestricted()
877 && (user.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID)) {
878 user.restrictedProfileParentId = UserHandle.USER_SYSTEM;
879 scheduleWriteUserLocked(user);
880 }
881 }
882 userVersion = 6;
883 }
884
Amith Yamasani6f34b412012-10-22 18:19:27 -0700885 if (userVersion < USER_VERSION) {
886 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
887 + USER_VERSION);
888 } else {
889 mUserVersion = userVersion;
890 writeUserListLocked();
891 }
892 }
893
Amith Yamasani13593602012-03-22 16:16:17 -0700894 private void fallbackToSingleUserLocked() {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -0700895 int flags = UserInfo.FLAG_INITIALIZED;
896 // In split system user mode, the admin and primary flags are assigned to the first human
897 // user.
898 if (!UserManager.isSplitSystemUser()) {
899 flags |= UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY;
900 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700901 // Create the system user
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700902 UserInfo system = new UserInfo(UserHandle.USER_SYSTEM,
Amith Yamasani6f34b412012-10-22 18:19:27 -0700903 mContext.getResources().getString(com.android.internal.R.string.owner_name), null,
Xiaohui Chenb31e14a2015-07-13 16:04:55 -0700904 flags);
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700905 mUsers.put(system.id, system);
Amith Yamasani634cf312012-10-04 17:34:21 -0700906 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -0400907 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -0800908
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -0500909 Bundle restrictions = new Bundle();
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700910 mUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions);
Amith Yamasani67df64b2012-12-14 12:09:36 -0800911
Amith Yamasani13593602012-03-22 16:16:17 -0700912 updateUserIdsLocked();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700913 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700914
Amith Yamasani13593602012-03-22 16:16:17 -0700915 writeUserListLocked();
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700916 writeUserLocked(system);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700917 }
918
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800919 private void scheduleWriteUserLocked(UserInfo userInfo) {
920 if (!mHandler.hasMessages(WRITE_USER_MSG, userInfo)) {
921 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, userInfo);
922 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
923 }
924 }
925
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700926 /*
927 * Writes the user file in this format:
928 *
929 * <user flags="20039023" id="0">
930 * <name>Primary</name>
931 * </user>
932 */
Amith Yamasani13593602012-03-22 16:16:17 -0700933 private void writeUserLocked(UserInfo userInfo) {
Amith Yamasani742a6712011-05-04 14:49:28 -0700934 FileOutputStream fos = null;
Amith Yamasanifc95e702013-09-26 13:20:17 -0700935 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userInfo.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700936 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700937 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700938 final BufferedOutputStream bos = new BufferedOutputStream(fos);
939
940 // XmlSerializer serializer = XmlUtils.serializerInstance();
941 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100942 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700943 serializer.startDocument(null, true);
944 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
945
946 serializer.startTag(null, TAG_USER);
947 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
Amith Yamasani2a003292012-08-14 18:25:45 -0700948 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700949 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Amith Yamasani920ace02012-09-20 22:15:37 -0700950 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
951 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
952 Long.toString(userInfo.lastLoggedInTime));
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700953 if (userInfo.iconPath != null) {
954 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
955 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700956 if (userInfo.partial) {
957 serializer.attribute(null, ATTR_PARTIAL, "true");
958 }
Adam Lesinskieddeb492014-09-08 17:50:03 -0700959 if (userInfo.guestToRemove) {
960 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
961 }
Kenny Guy2a764942014-04-02 13:29:20 +0100962 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
963 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
964 Integer.toString(userInfo.profileGroupId));
Kenny Guya52dc3e2014-02-11 15:33:14 +0000965 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700966 if (userInfo.restrictedProfileParentId != UserInfo.NO_PROFILE_GROUP_ID) {
967 serializer.attribute(null, ATTR_RESTRICTED_PROFILE_PARENT_ID,
968 Integer.toString(userInfo.restrictedProfileParentId));
969 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700970 serializer.startTag(null, TAG_NAME);
971 serializer.text(userInfo.name);
972 serializer.endTag(null, TAG_NAME);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800973 Bundle restrictions = mUserRestrictions.get(userInfo.id);
974 if (restrictions != null) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530975 writeRestrictionsLocked(serializer, restrictions);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800976 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700977 serializer.endTag(null, TAG_USER);
978
979 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -0700980 userFile.finishWrite(fos);
981 } catch (Exception ioe) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700982 Slog.e(LOG_TAG, "Error writing user info " + userInfo.id + "\n" + ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -0700983 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700984 }
985 }
986
987 /*
988 * Writes the user list file in this format:
989 *
Amith Yamasani2a003292012-08-14 18:25:45 -0700990 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700991 * <user id="0"></user>
992 * <user id="2"></user>
993 * </users>
994 */
Amith Yamasani13593602012-03-22 16:16:17 -0700995 private void writeUserListLocked() {
Amith Yamasani742a6712011-05-04 14:49:28 -0700996 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700997 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700998 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700999 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001000 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1001
1002 // XmlSerializer serializer = XmlUtils.serializerInstance();
1003 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001004 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001005 serializer.startDocument(null, true);
1006 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1007
1008 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -07001009 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -07001010 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001011
Adam Lesinskieddeb492014-09-08 17:50:03 -07001012 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301013 writeRestrictionsLocked(serializer, mGuestRestrictions);
1014 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001015 for (int i = 0; i < mUsers.size(); i++) {
1016 UserInfo user = mUsers.valueAt(i);
1017 serializer.startTag(null, TAG_USER);
1018 serializer.attribute(null, ATTR_ID, Integer.toString(user.id));
1019 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001020 }
1021
1022 serializer.endTag(null, TAG_USERS);
1023
1024 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001025 userListFile.finishWrite(fos);
1026 } catch (Exception e) {
1027 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -07001028 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001029 }
1030 }
1031
Andres Moralesc5548c02015-08-05 10:23:12 -07001032 private void writeRestrictionsLocked(XmlSerializer serializer, Bundle restrictions)
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301033 throws IOException {
1034 serializer.startTag(null, TAG_RESTRICTIONS);
1035 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_WIFI);
1036 writeBoolean(serializer, restrictions, UserManager.DISALLOW_MODIFY_ACCOUNTS);
1037 writeBoolean(serializer, restrictions, UserManager.DISALLOW_INSTALL_APPS);
1038 writeBoolean(serializer, restrictions, UserManager.DISALLOW_UNINSTALL_APPS);
1039 writeBoolean(serializer, restrictions, UserManager.DISALLOW_SHARE_LOCATION);
1040 writeBoolean(serializer, restrictions,
1041 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
1042 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_BLUETOOTH);
1043 writeBoolean(serializer, restrictions, UserManager.DISALLOW_USB_FILE_TRANSFER);
1044 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_CREDENTIALS);
1045 writeBoolean(serializer, restrictions, UserManager.DISALLOW_REMOVE_USER);
1046 writeBoolean(serializer, restrictions, UserManager.DISALLOW_DEBUGGING_FEATURES);
1047 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_VPN);
1048 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_TETHERING);
Stuart Scott94b038b2015-04-20 14:07:45 -07001049 writeBoolean(serializer, restrictions, UserManager.DISALLOW_NETWORK_RESET);
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301050 writeBoolean(serializer, restrictions, UserManager.DISALLOW_FACTORY_RESET);
1051 writeBoolean(serializer, restrictions, UserManager.DISALLOW_ADD_USER);
1052 writeBoolean(serializer, restrictions, UserManager.ENSURE_VERIFY_APPS);
1053 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_CELL_BROADCASTS);
1054 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS);
1055 writeBoolean(serializer, restrictions, UserManager.DISALLOW_APPS_CONTROL);
1056 writeBoolean(serializer, restrictions, UserManager.DISALLOW_MOUNT_PHYSICAL_MEDIA);
1057 writeBoolean(serializer, restrictions, UserManager.DISALLOW_UNMUTE_MICROPHONE);
1058 writeBoolean(serializer, restrictions, UserManager.DISALLOW_ADJUST_VOLUME);
Amith Yamasani390989d2014-07-17 10:52:03 -07001059 writeBoolean(serializer, restrictions, UserManager.DISALLOW_OUTGOING_CALLS);
1060 writeBoolean(serializer, restrictions, UserManager.DISALLOW_SMS);
Jeff Sharkey2cc03e52015-03-20 11:24:04 -07001061 writeBoolean(serializer, restrictions, UserManager.DISALLOW_FUN);
Jason Monk1c7c3192014-06-26 12:52:18 -04001062 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CREATE_WINDOWS);
Amith Yamasani26af8292014-09-09 09:57:27 -07001063 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CROSS_PROFILE_COPY_PASTE);
1064 writeBoolean(serializer, restrictions, UserManager.DISALLOW_OUTGOING_BEAM);
Benjamin Franzf3ece362015-02-11 10:51:10 +00001065 writeBoolean(serializer, restrictions, UserManager.DISALLOW_WALLPAPER);
Benjamin Franzbff46ba2015-03-05 18:33:51 +00001066 writeBoolean(serializer, restrictions, UserManager.DISALLOW_SAFE_BOOT);
Nicolas Prevotf0029c12015-06-25 14:25:41 -07001067 writeBoolean(serializer, restrictions, UserManager.ALLOW_PARENT_PROFILE_APP_LINKING);
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301068 serializer.endTag(null, TAG_RESTRICTIONS);
1069 }
1070
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001071 private UserInfo readUserLocked(int id) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001072 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -07001073 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001074 String name = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001075 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -07001076 long creationTime = 0L;
1077 long lastLoggedInTime = 0L;
Kenny Guy2a764942014-04-02 13:29:20 +01001078 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001079 int restrictedProfileParentId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001080 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001081 boolean guestToRemove = false;
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001082 Bundle restrictions = new Bundle();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001083
1084 FileInputStream fis = null;
1085 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001086 AtomicFile userFile =
Amith Yamasanifc95e702013-09-26 13:20:17 -07001087 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
Amith Yamasani2a003292012-08-14 18:25:45 -07001088 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001089 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001090 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001091 int type;
1092 while ((type = parser.next()) != XmlPullParser.START_TAG
1093 && type != XmlPullParser.END_DOCUMENT) {
1094 ;
1095 }
1096
1097 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001098 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001099 return null;
1100 }
1101
1102 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001103 int storedId = readIntAttribute(parser, ATTR_ID, -1);
1104 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001105 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001106 return null;
1107 }
Amith Yamasani920ace02012-09-20 22:15:37 -07001108 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
1109 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001110 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -07001111 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
1112 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Kenny Guy2a764942014-04-02 13:29:20 +01001113 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
1114 UserInfo.NO_PROFILE_GROUP_ID);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001115 restrictedProfileParentId = readIntAttribute(parser,
1116 ATTR_RESTRICTED_PROFILE_PARENT_ID, UserInfo.NO_PROFILE_GROUP_ID);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001117 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
1118 if ("true".equals(valueString)) {
1119 partial = true;
1120 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001121 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
1122 if ("true".equals(valueString)) {
1123 guestToRemove = true;
1124 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001125
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001126 int outerDepth = parser.getDepth();
1127 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1128 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1129 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1130 continue;
1131 }
1132 String tag = parser.getName();
1133 if (TAG_NAME.equals(tag)) {
1134 type = parser.next();
1135 if (type == XmlPullParser.TEXT) {
1136 name = parser.getText();
1137 }
1138 } else if (TAG_RESTRICTIONS.equals(tag)) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301139 readRestrictionsLocked(parser, restrictions);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001140 }
1141 }
1142 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001143
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001144 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -07001145 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -07001146 userInfo.creationTime = creationTime;
1147 userInfo.lastLoggedInTime = lastLoggedInTime;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001148 userInfo.partial = partial;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001149 userInfo.guestToRemove = guestToRemove;
Kenny Guy2a764942014-04-02 13:29:20 +01001150 userInfo.profileGroupId = profileGroupId;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001151 userInfo.restrictedProfileParentId = restrictedProfileParentId;
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001152 mUserRestrictions.append(id, restrictions);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001153 return userInfo;
1154
1155 } catch (IOException ioe) {
1156 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001157 } finally {
1158 if (fis != null) {
1159 try {
1160 fis.close();
1161 } catch (IOException e) {
1162 }
1163 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001164 }
1165 return null;
1166 }
1167
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301168 private void readRestrictionsLocked(XmlPullParser parser, Bundle restrictions)
1169 throws IOException {
1170 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_WIFI);
1171 readBoolean(parser, restrictions, UserManager.DISALLOW_MODIFY_ACCOUNTS);
1172 readBoolean(parser, restrictions, UserManager.DISALLOW_INSTALL_APPS);
1173 readBoolean(parser, restrictions, UserManager.DISALLOW_UNINSTALL_APPS);
1174 readBoolean(parser, restrictions, UserManager.DISALLOW_SHARE_LOCATION);
1175 readBoolean(parser, restrictions,
1176 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
1177 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_BLUETOOTH);
1178 readBoolean(parser, restrictions, UserManager.DISALLOW_USB_FILE_TRANSFER);
1179 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_CREDENTIALS);
1180 readBoolean(parser, restrictions, UserManager.DISALLOW_REMOVE_USER);
1181 readBoolean(parser, restrictions, UserManager.DISALLOW_DEBUGGING_FEATURES);
1182 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_VPN);
1183 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_TETHERING);
Stuart Scott94b038b2015-04-20 14:07:45 -07001184 readBoolean(parser, restrictions, UserManager.DISALLOW_NETWORK_RESET);
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301185 readBoolean(parser, restrictions, UserManager.DISALLOW_FACTORY_RESET);
1186 readBoolean(parser, restrictions, UserManager.DISALLOW_ADD_USER);
1187 readBoolean(parser, restrictions, UserManager.ENSURE_VERIFY_APPS);
1188 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_CELL_BROADCASTS);
1189 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS);
1190 readBoolean(parser, restrictions, UserManager.DISALLOW_APPS_CONTROL);
1191 readBoolean(parser, restrictions,
1192 UserManager.DISALLOW_MOUNT_PHYSICAL_MEDIA);
1193 readBoolean(parser, restrictions, UserManager.DISALLOW_UNMUTE_MICROPHONE);
1194 readBoolean(parser, restrictions, UserManager.DISALLOW_ADJUST_VOLUME);
Amith Yamasani390989d2014-07-17 10:52:03 -07001195 readBoolean(parser, restrictions, UserManager.DISALLOW_OUTGOING_CALLS);
1196 readBoolean(parser, restrictions, UserManager.DISALLOW_SMS);
Jeff Sharkey2cc03e52015-03-20 11:24:04 -07001197 readBoolean(parser, restrictions, UserManager.DISALLOW_FUN);
Jason Monk1c7c3192014-06-26 12:52:18 -04001198 readBoolean(parser, restrictions, UserManager.DISALLOW_CREATE_WINDOWS);
Amith Yamasani26af8292014-09-09 09:57:27 -07001199 readBoolean(parser, restrictions, UserManager.DISALLOW_CROSS_PROFILE_COPY_PASTE);
1200 readBoolean(parser, restrictions, UserManager.DISALLOW_OUTGOING_BEAM);
Benjamin Franzf3ece362015-02-11 10:51:10 +00001201 readBoolean(parser, restrictions, UserManager.DISALLOW_WALLPAPER);
Benjamin Franzbff46ba2015-03-05 18:33:51 +00001202 readBoolean(parser, restrictions, UserManager.DISALLOW_SAFE_BOOT);
Nicolas Prevotf0029c12015-06-25 14:25:41 -07001203 readBoolean(parser, restrictions, UserManager.ALLOW_PARENT_PROFILE_APP_LINKING);
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301204 }
1205
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001206 private void readBoolean(XmlPullParser parser, Bundle restrictions,
1207 String restrictionKey) {
1208 String value = parser.getAttributeValue(null, restrictionKey);
Amith Yamasani71e6c692013-03-24 17:39:28 -07001209 if (value != null) {
1210 restrictions.putBoolean(restrictionKey, Boolean.parseBoolean(value));
1211 }
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001212 }
1213
1214 private void writeBoolean(XmlSerializer xml, Bundle restrictions, String restrictionKey)
1215 throws IOException {
1216 if (restrictions.containsKey(restrictionKey)) {
1217 xml.attribute(null, restrictionKey,
1218 Boolean.toString(restrictions.getBoolean(restrictionKey)));
1219 }
1220 }
1221
Amith Yamasani920ace02012-09-20 22:15:37 -07001222 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
1223 String valueString = parser.getAttributeValue(null, attr);
1224 if (valueString == null) return defaultValue;
1225 try {
1226 return Integer.parseInt(valueString);
1227 } catch (NumberFormatException nfe) {
1228 return defaultValue;
1229 }
1230 }
1231
1232 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
1233 String valueString = parser.getAttributeValue(null, attr);
1234 if (valueString == null) return defaultValue;
1235 try {
1236 return Long.parseLong(valueString);
1237 } catch (NumberFormatException nfe) {
1238 return defaultValue;
1239 }
1240 }
1241
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001242 private boolean isPackageInstalled(String pkg, int userId) {
1243 final ApplicationInfo info = mPm.getApplicationInfo(pkg,
1244 PackageManager.GET_UNINSTALLED_PACKAGES,
1245 userId);
1246 if (info == null || (info.flags&ApplicationInfo.FLAG_INSTALLED) == 0) {
1247 return false;
1248 }
1249 return true;
1250 }
1251
Amith Yamasanib82add22013-07-09 11:24:44 -07001252 /**
Kenny Guyd21b2182014-07-17 16:38:55 +01001253 * Removes all the restrictions files (res_<packagename>) for a given user.
Amith Yamasanib82add22013-07-09 11:24:44 -07001254 * Does not do any permissions checking.
1255 */
Kenny Guyd21b2182014-07-17 16:38:55 +01001256 private void cleanAppRestrictions(int userId) {
Amith Yamasanib82add22013-07-09 11:24:44 -07001257 synchronized (mPackagesLock) {
1258 File dir = Environment.getUserSystemDirectory(userId);
1259 String[] files = dir.list();
1260 if (files == null) return;
1261 for (String fileName : files) {
1262 if (fileName.startsWith(RESTRICTIONS_FILE_PREFIX)) {
1263 File resFile = new File(dir, fileName);
1264 if (resFile.exists()) {
Kenny Guyd21b2182014-07-17 16:38:55 +01001265 resFile.delete();
Amith Yamasanib82add22013-07-09 11:24:44 -07001266 }
1267 }
1268 }
1269 }
1270 }
1271
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001272 /**
1273 * Removes the app restrictions file for a specific package and user id, if it exists.
1274 */
1275 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
1276 synchronized (mPackagesLock) {
1277 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07001278 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001279 if (resFile.exists()) {
1280 resFile.delete();
1281 }
1282 }
1283 }
1284
Kenny Guya52dc3e2014-02-11 15:33:14 +00001285 @Override
Kenny Guy2a764942014-04-02 13:29:20 +01001286 public UserInfo createProfileForUser(String name, int flags, int userId) {
Kenny Guya52dc3e2014-02-11 15:33:14 +00001287 checkManageUsersPermission("Only the system can create users");
Kenny Guy2a764942014-04-02 13:29:20 +01001288 return createUserInternal(name, flags, userId);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001289 }
1290
Amith Yamasani258848d2012-08-10 17:06:33 -07001291 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07001292 public UserInfo createUser(String name, int flags) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001293 checkManageUsersPermission("Only the system can create users");
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001294 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001295 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001296
Jessica Hummelbe81c802014-04-22 15:49:22 +01001297 private UserInfo createUserInternal(String name, int flags, int parentId) {
Julia Reynolds75175022014-06-26 16:35:00 -04001298 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1299 UserManager.DISALLOW_ADD_USER, false)) {
1300 Log.w(LOG_TAG, "Cannot add user. DISALLOW_ADD_USER is enabled.");
1301 return null;
1302 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001303 if (ActivityManager.isLowRamDeviceStatic()) {
1304 return null;
1305 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07001306 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001307 final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001308 final boolean isRestricted = (flags & UserInfo.FLAG_RESTRICTED) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001309 final long ident = Binder.clearCallingIdentity();
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001310 UserInfo userInfo = null;
Amith Yamasanibb054c92015-07-09 14:16:27 -07001311 final int userId;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001312 try {
1313 synchronized (mInstallLock) {
1314 synchronized (mPackagesLock) {
Jessica Hummelbe81c802014-04-22 15:49:22 +01001315 UserInfo parent = null;
1316 if (parentId != UserHandle.USER_NULL) {
1317 parent = getUserInfoLocked(parentId);
1318 if (parent == null) return null;
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001319 }
Nicolas Prevotb8186812015-08-06 15:00:03 +01001320 if (isManagedProfile && !canAddMoreManagedProfiles(parentId)) {
1321 Log.e(LOG_TAG, "Cannot add more managed profiles for user " + parentId);
Nicolas Prevot12678a92015-05-13 12:15:03 -07001322 return null;
1323 }
1324 if (!isGuest && !isManagedProfile && isUserLimitReachedLocked()) {
1325 // If we're not adding a guest user or a managed profile and the limit has
1326 // been reached, cannot add a user.
Amith Yamasani95ab7842014-08-11 17:09:26 -07001327 return null;
1328 }
1329 // If we're adding a guest and there already exists one, bail.
Adam Lesinskieddeb492014-09-08 17:50:03 -07001330 if (isGuest && findCurrentGuestUserLocked() != null) {
Amith Yamasani95ab7842014-08-11 17:09:26 -07001331 return null;
1332 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001333 // In legacy mode, restricted profile's parent can only be the owner user
1334 if (isRestricted && !UserManager.isSplitSystemUser()
1335 && (parentId != UserHandle.USER_SYSTEM)) {
1336 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
1337 return null;
1338 }
1339 if (isRestricted && UserManager.isSplitSystemUser()) {
1340 if (parent == null) {
1341 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be "
1342 + "specified");
1343 return null;
1344 }
1345 if (!parent.canHaveProfile()) {
1346 Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be "
1347 + "created for the specified parent user id " + parentId);
1348 return null;
1349 }
1350 }
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001351 // In split system user mode, we assign the first human user the primary flag.
Xiaohui Chen203243a2015-07-16 11:55:47 -07001352 // And if there is no device owner, we also assign the admin flag to primary
1353 // user.
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001354 if (UserManager.isSplitSystemUser()
Xiaohui Chen203243a2015-07-16 11:55:47 -07001355 && !isGuest && !isManagedProfile && getPrimaryUser() == null) {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001356 flags |= UserInfo.FLAG_PRIMARY;
Xiaohui Chen203243a2015-07-16 11:55:47 -07001357 DevicePolicyManager devicePolicyManager = (DevicePolicyManager)
1358 mContext.getSystemService(Context.DEVICE_POLICY_SERVICE);
1359 if (devicePolicyManager == null
1360 || devicePolicyManager.getDeviceOwner() == null) {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001361 flags |= UserInfo.FLAG_ADMIN;
1362 }
1363 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07001364 userId = getNextAvailableIdLocked();
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001365 userInfo = new UserInfo(userId, name, null, flags);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001366 userInfo.serialNumber = mNextSerialNumber++;
Amith Yamasani920ace02012-09-20 22:15:37 -07001367 long now = System.currentTimeMillis();
1368 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001369 userInfo.partial = true;
Amith Yamasani16389312012-10-17 21:20:14 -07001370 Environment.getUserSystemDirectory(userInfo.id).mkdirs();
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001371 mUsers.put(userId, userInfo);
1372 writeUserListLocked();
Jessica Hummelbe81c802014-04-22 15:49:22 +01001373 if (parent != null) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001374 if (isManagedProfile) {
1375 if (parent.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
1376 parent.profileGroupId = parent.id;
1377 scheduleWriteUserLocked(parent);
1378 }
1379 userInfo.profileGroupId = parent.profileGroupId;
1380 } else if (isRestricted) {
1381 if (!parent.canHaveProfile()) {
1382 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
1383 }
1384 if (parent.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) {
1385 parent.restrictedProfileParentId = parent.id;
1386 scheduleWriteUserLocked(parent);
1387 }
1388 userInfo.restrictedProfileParentId = parent.restrictedProfileParentId;
Kenny Guya52dc3e2014-02-11 15:33:14 +00001389 }
Kenny Guya52dc3e2014-02-11 15:33:14 +00001390 }
Jeff Sharkey6dce4962015-07-03 18:08:41 -07001391 final StorageManager storage = mContext.getSystemService(StorageManager.class);
1392 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
1393 final String volumeUuid = vol.getFsUuid();
1394 try {
1395 final File userDir = Environment.getDataUserDirectory(volumeUuid,
1396 userId);
Jeff Sharkey3bb8c852015-07-06 16:44:23 -07001397 prepareUserDirectory(mContext, volumeUuid, userId);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07001398 enforceSerialNumber(userDir, userInfo.serialNumber);
1399 } catch (IOException e) {
1400 Log.wtf(LOG_TAG, "Failed to create user directory on " + volumeUuid, e);
1401 }
1402 }
1403 mPm.createNewUserLILPw(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001404 userInfo.partial = false;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001405 scheduleWriteUserLocked(userInfo);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001406 updateUserIdsLocked();
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001407 Bundle restrictions = new Bundle();
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001408 mUserRestrictions.append(userId, restrictions);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001409 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07001410 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07001411 mPm.newUserCreated(userId);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001412 if (userInfo != null) {
1413 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
1414 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userInfo.id);
1415 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
1416 android.Manifest.permission.MANAGE_USERS);
1417 }
1418 } finally {
1419 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07001420 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001421 return userInfo;
1422 }
1423
Amith Yamasani0b285492011-04-14 17:35:23 -07001424 /**
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07001425 * @hide
1426 */
1427 public UserInfo createRestrictedProfile(String name, int parentUserId) {
1428 checkManageUsersPermission("setupRestrictedProfile");
1429 final UserInfo user = createProfileForUser(name, UserInfo.FLAG_RESTRICTED, parentUserId);
1430 if (user == null) {
1431 return null;
1432 }
1433 setUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, true, user.id);
1434 // Change the setting before applying the DISALLOW_SHARE_LOCATION restriction, otherwise
1435 // the putIntForUser() will fail.
1436 android.provider.Settings.Secure.putIntForUser(mContext.getContentResolver(),
1437 android.provider.Settings.Secure.LOCATION_MODE,
1438 android.provider.Settings.Secure.LOCATION_MODE_OFF, user.id);
1439 setUserRestriction(UserManager.DISALLOW_SHARE_LOCATION, true, user.id);
1440 return user;
1441 }
1442
1443 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07001444 * Find the current guest user. If the Guest user is partial,
1445 * then do not include it in the results as it is about to die.
Adam Lesinskieddeb492014-09-08 17:50:03 -07001446 */
1447 private UserInfo findCurrentGuestUserLocked() {
1448 final int size = mUsers.size();
1449 for (int i = 0; i < size; i++) {
1450 final UserInfo user = mUsers.valueAt(i);
1451 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
1452 return user;
1453 }
1454 }
1455 return null;
1456 }
1457
1458 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07001459 * Mark this guest user for deletion to allow us to create another guest
1460 * and switch to that user before actually removing this guest.
1461 * @param userHandle the userid of the current guest
1462 * @return whether the user could be marked for deletion
1463 */
1464 public boolean markGuestForDeletion(int userHandle) {
1465 checkManageUsersPermission("Only the system can remove users");
1466 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1467 UserManager.DISALLOW_REMOVE_USER, false)) {
1468 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1469 return false;
1470 }
1471
1472 long ident = Binder.clearCallingIdentity();
1473 try {
1474 final UserInfo user;
1475 synchronized (mPackagesLock) {
1476 user = mUsers.get(userHandle);
1477 if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
1478 return false;
1479 }
1480 if (!user.isGuest()) {
1481 return false;
1482 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001483 // We set this to a guest user that is to be removed. This is a temporary state
1484 // where we are allowed to add new Guest users, even if this one is still not
1485 // removed. This user will still show up in getUserInfo() calls.
1486 // If we don't get around to removing this Guest user, it will be purged on next
1487 // startup.
1488 user.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07001489 // Mark it as disabled, so that it isn't returned any more when
1490 // profiles are queried.
1491 user.flags |= UserInfo.FLAG_DISABLED;
Amith Yamasani1df14732014-08-29 21:37:27 -07001492 writeUserLocked(user);
1493 }
1494 } finally {
1495 Binder.restoreCallingIdentity(ident);
1496 }
1497 return true;
1498 }
1499
1500 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07001501 * Removes a user and all data directories created for that user. This method should be called
1502 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001503 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07001504 */
Amith Yamasani258848d2012-08-10 17:06:33 -07001505 public boolean removeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001506 checkManageUsersPermission("Only the system can remove users");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04001507 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1508 UserManager.DISALLOW_REMOVE_USER, false)) {
1509 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1510 return false;
1511 }
1512
Kenny Guyee58b4f2014-05-23 15:19:53 +01001513 long ident = Binder.clearCallingIdentity();
1514 try {
1515 final UserInfo user;
1516 synchronized (mPackagesLock) {
1517 user = mUsers.get(userHandle);
Kenny Guy17c9d692014-06-13 13:51:42 +01001518 if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01001519 return false;
1520 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08001521
1522 // We remember deleted user IDs to prevent them from being
1523 // reused during the current boot; they can still be reused
1524 // after a reboot.
Kenny Guyee58b4f2014-05-23 15:19:53 +01001525 mRemovingUserIds.put(userHandle, true);
Jeff Sharkey6eb09392014-11-14 15:57:59 -08001526
Kenny Guyee58b4f2014-05-23 15:19:53 +01001527 try {
1528 mAppOpsService.removeUser(userHandle);
1529 } catch (RemoteException e) {
1530 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
1531 }
1532 // Set this to a partially created user, so that the user will be purged
1533 // on next startup, in case the runtime stops now before stopping and
1534 // removing the user completely.
1535 user.partial = true;
1536 // Mark it as disabled, so that it isn't returned any more when
1537 // profiles are queried.
1538 user.flags |= UserInfo.FLAG_DISABLED;
1539 writeUserLocked(user);
1540 }
1541
1542 if (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
1543 && user.isManagedProfile()) {
1544 // Send broadcast to notify system that the user removed was a
1545 // managed user.
1546 sendProfileRemovedBroadcast(user.profileGroupId, user.id);
1547 }
1548
1549 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
1550 int res;
1551 try {
1552 res = ActivityManagerNative.getDefault().stopUser(userHandle,
1553 new IStopUserCallback.Stub() {
1554 @Override
1555 public void userStopped(int userId) {
1556 finishRemoveUser(userId);
1557 }
1558 @Override
1559 public void userStopAborted(int userId) {
1560 }
1561 });
1562 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001563 return false;
1564 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01001565 return res == ActivityManager.USER_OP_SUCCESS;
1566 } finally {
1567 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001568 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001569 }
1570
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001571 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07001572 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001573 // Let other services shutdown any activity and clean up their state before completely
1574 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001575 long ident = Binder.clearCallingIdentity();
1576 try {
1577 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
1578 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001579 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
1580 android.Manifest.permission.MANAGE_USERS,
1581
1582 new BroadcastReceiver() {
1583 @Override
1584 public void onReceive(Context context, Intent intent) {
1585 if (DBG) {
1586 Slog.i(LOG_TAG,
1587 "USER_REMOVED broadcast sent, cleaning up user data "
1588 + userHandle);
1589 }
1590 new Thread() {
1591 public void run() {
1592 synchronized (mInstallLock) {
1593 synchronized (mPackagesLock) {
1594 removeUserStateLocked(userHandle);
1595 }
1596 }
1597 }
1598 }.start();
1599 }
1600 },
1601
1602 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001603 } finally {
1604 Binder.restoreCallingIdentity(ident);
1605 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001606 }
1607
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001608 private void removeUserStateLocked(final int userHandle) {
Paul Crowley85e4e812015-05-19 12:42:00 +01001609 mContext.getSystemService(StorageManager.class)
1610 .deleteUserKey(userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001611 // Cleanup package manager settings
Amith Yamasanidda003f2014-08-28 18:06:51 -07001612 mPm.cleanUpUserLILPw(this, userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001613
1614 // Remove this user from the list
1615 mUsers.remove(userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001616 // Remove user file
Amith Yamasanifc95e702013-09-26 13:20:17 -07001617 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001618 userFile.delete();
1619 // Update the user list
1620 writeUserListLocked();
1621 updateUserIdsLocked();
1622 removeDirectoryRecursive(Environment.getUserSystemDirectory(userHandle));
1623 }
1624
Amith Yamasani61f57372012-08-31 12:12:28 -07001625 private void removeDirectoryRecursive(File parent) {
1626 if (parent.isDirectory()) {
1627 String[] files = parent.list();
1628 for (String filename : files) {
1629 File child = new File(parent, filename);
1630 removeDirectoryRecursive(child);
1631 }
1632 }
1633 parent.delete();
1634 }
1635
Kenny Guyf8d3a232014-05-15 16:09:52 +01001636 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01001637 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01001638 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
1639 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01001640 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
1641 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01001642 }
1643
Amith Yamasani2a003292012-08-14 18:25:45 -07001644 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001645 public Bundle getApplicationRestrictions(String packageName) {
1646 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
1647 }
1648
1649 @Override
1650 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001651 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07001652 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001653 checkManageUsersPermission("Only system can get restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001654 }
1655 synchronized (mPackagesLock) {
1656 // Read the restrictions from XML
1657 return readApplicationRestrictionsLocked(packageName, userId);
1658 }
1659 }
1660
1661 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001662 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001663 int userId) {
1664 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07001665 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001666 checkManageUsersPermission("Only system can set restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001667 }
1668 synchronized (mPackagesLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01001669 if (restrictions == null || restrictions.isEmpty()) {
1670 cleanAppRestrictionsForPackage(packageName, userId);
1671 } else {
1672 // Write the restrictions to XML
1673 writeApplicationRestrictionsLocked(packageName, restrictions, userId);
1674 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001675 }
Robin Lee66e5d962014-04-09 16:44:21 +01001676
Kenny Guyd21b2182014-07-17 16:38:55 +01001677 if (isPackageInstalled(packageName, userId)) {
1678 // Notify package of changes via an intent - only sent to explicitly registered receivers.
1679 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
1680 changeIntent.setPackage(packageName);
1681 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
1682 mContext.sendBroadcastAsUser(changeIntent, new UserHandle(userId));
1683 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001684 }
1685
Amith Yamasani655d0e22013-06-12 14:19:10 -07001686 @Override
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001687 public void removeRestrictions() {
Amith Yamasanibe465322014-04-24 13:45:17 -07001688 checkManageUsersPermission("Only system can remove restrictions");
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001689 final int userHandle = UserHandle.getCallingUserId();
Amith Yamasani5e486f52013-08-07 11:06:44 -07001690 removeRestrictionsForUser(userHandle, true);
Amith Yamasani350962c2013-08-06 11:18:53 -07001691 }
1692
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001693 private void removeRestrictionsForUser(final int userHandle, boolean unhideApps) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001694 synchronized (mPackagesLock) {
1695 // Remove all user restrictions
1696 setUserRestrictions(new Bundle(), userHandle);
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001697 // Remove any app restrictions
Kenny Guyd21b2182014-07-17 16:38:55 +01001698 cleanAppRestrictions(userHandle);
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001699 }
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001700 if (unhideApps) {
1701 unhideAllInstalledAppsForUser(userHandle);
Amith Yamasani5e486f52013-08-07 11:06:44 -07001702 }
1703 }
1704
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001705 private void unhideAllInstalledAppsForUser(final int userHandle) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001706 mHandler.post(new Runnable() {
1707 @Override
1708 public void run() {
1709 List<ApplicationInfo> apps =
1710 mPm.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES,
1711 userHandle).getList();
1712 final long ident = Binder.clearCallingIdentity();
1713 try {
1714 for (ApplicationInfo appInfo : apps) {
1715 if ((appInfo.flags & ApplicationInfo.FLAG_INSTALLED) != 0
Alex Klyubinb9f8a522015-02-03 11:12:59 -08001716 && (appInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HIDDEN)
1717 != 0) {
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001718 mPm.setApplicationHiddenSettingAsUser(appInfo.packageName, false,
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001719 userHandle);
1720 }
1721 }
1722 } finally {
1723 Binder.restoreCallingIdentity(ident);
1724 }
1725 }
1726 });
1727 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001728 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07001729 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001730 try {
1731 return mContext.getPackageManager().getApplicationInfo(packageName,
1732 PackageManager.GET_UNINSTALLED_PACKAGES).uid;
1733 } catch (NameNotFoundException nnfe) {
1734 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07001735 } finally {
1736 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001737 }
1738 }
1739
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001740 private Bundle readApplicationRestrictionsLocked(String packageName,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001741 int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001742 AtomicFile restrictionsFile =
1743 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
1744 packageToRestrictionsFileName(packageName)));
1745 return readApplicationRestrictionsLocked(restrictionsFile);
1746 }
1747
1748 @VisibleForTesting
1749 static Bundle readApplicationRestrictionsLocked(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001750 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001751 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07001752 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07001753 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07001754 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001755
1756 FileInputStream fis = null;
1757 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001758 fis = restrictionsFile.openRead();
1759 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001760 parser.setInput(fis, StandardCharsets.UTF_8.name());
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001761 XmlUtils.nextElement(parser);
1762 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001763 Slog.e(LOG_TAG, "Unable to read restrictions file "
1764 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001765 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001766 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001767 while (parser.next() != XmlPullParser.END_DOCUMENT) {
1768 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001769 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001770 } catch (IOException|XmlPullParserException e) {
1771 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001772 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001773 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001774 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001775 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001776 }
1777
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001778 private static void readEntry(Bundle restrictions, ArrayList<String> values,
1779 XmlPullParser parser) throws XmlPullParserException, IOException {
1780 int type = parser.getEventType();
1781 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
1782 String key = parser.getAttributeValue(null, ATTR_KEY);
1783 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
1784 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
1785 if (multiple != null) {
1786 values.clear();
1787 int count = Integer.parseInt(multiple);
1788 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1789 if (type == XmlPullParser.START_TAG
1790 && parser.getName().equals(TAG_VALUE)) {
1791 values.add(parser.nextText().trim());
1792 count--;
1793 }
1794 }
1795 String [] valueStrings = new String[values.size()];
1796 values.toArray(valueStrings);
1797 restrictions.putStringArray(key, valueStrings);
1798 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
1799 restrictions.putBundle(key, readBundleEntry(parser, values));
1800 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
1801 final int outerDepth = parser.getDepth();
1802 ArrayList<Bundle> bundleList = new ArrayList<>();
1803 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
1804 Bundle childBundle = readBundleEntry(parser, values);
1805 bundleList.add(childBundle);
1806 }
1807 restrictions.putParcelableArray(key,
1808 bundleList.toArray(new Bundle[bundleList.size()]));
1809 } else {
1810 String value = parser.nextText().trim();
1811 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
1812 restrictions.putBoolean(key, Boolean.parseBoolean(value));
1813 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
1814 restrictions.putInt(key, Integer.parseInt(value));
1815 } else {
1816 restrictions.putString(key, value);
1817 }
1818 }
1819 }
1820 }
1821
1822 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
1823 throws IOException, XmlPullParserException {
1824 Bundle childBundle = new Bundle();
1825 final int outerDepth = parser.getDepth();
1826 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
1827 readEntry(childBundle, values, parser);
1828 }
1829 return childBundle;
1830 }
1831
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001832 private void writeApplicationRestrictionsLocked(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001833 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001834 AtomicFile restrictionsFile = new AtomicFile(
1835 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07001836 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001837 writeApplicationRestrictionsLocked(restrictions, restrictionsFile);
1838 }
1839
1840 @VisibleForTesting
1841 static void writeApplicationRestrictionsLocked(Bundle restrictions,
1842 AtomicFile restrictionsFile) {
1843 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001844 try {
1845 fos = restrictionsFile.startWrite();
1846 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1847
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001848 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001849 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001850 serializer.startDocument(null, true);
1851 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1852
1853 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001854 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001855 serializer.endTag(null, TAG_RESTRICTIONS);
1856
1857 serializer.endDocument();
1858 restrictionsFile.finishWrite(fos);
1859 } catch (Exception e) {
1860 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001861 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
1862 }
1863 }
1864
1865 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
1866 throws IOException {
1867 for (String key : restrictions.keySet()) {
1868 Object value = restrictions.get(key);
1869 serializer.startTag(null, TAG_ENTRY);
1870 serializer.attribute(null, ATTR_KEY, key);
1871
1872 if (value instanceof Boolean) {
1873 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
1874 serializer.text(value.toString());
1875 } else if (value instanceof Integer) {
1876 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
1877 serializer.text(value.toString());
1878 } else if (value == null || value instanceof String) {
1879 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
1880 serializer.text(value != null ? (String) value : "");
1881 } else if (value instanceof Bundle) {
1882 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
1883 writeBundle((Bundle) value, serializer);
1884 } else if (value instanceof Parcelable[]) {
1885 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
1886 Parcelable[] array = (Parcelable[]) value;
1887 for (Parcelable parcelable : array) {
1888 if (!(parcelable instanceof Bundle)) {
1889 throw new IllegalArgumentException("bundle-array can only hold Bundles");
1890 }
1891 serializer.startTag(null, TAG_ENTRY);
1892 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
1893 writeBundle((Bundle) parcelable, serializer);
1894 serializer.endTag(null, TAG_ENTRY);
1895 }
1896 } else {
1897 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
1898 String[] values = (String[]) value;
1899 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
1900 for (String choice : values) {
1901 serializer.startTag(null, TAG_VALUE);
1902 serializer.text(choice != null ? choice : "");
1903 serializer.endTag(null, TAG_VALUE);
1904 }
1905 }
1906 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001907 }
1908 }
1909
1910 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07001911 public int getUserSerialNumber(int userHandle) {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001912 synchronized (mPackagesLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001913 if (!exists(userHandle)) return -1;
Amith Yamasani195263742012-08-21 15:40:12 -07001914 return getUserInfoLocked(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07001915 }
1916 }
1917
1918 @Override
1919 public int getUserHandle(int userSerialNumber) {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001920 synchronized (mPackagesLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001921 for (int userId : mUserIds) {
Kenny Guy945f8832015-02-10 15:17:26 +00001922 UserInfo info = getUserInfoLocked(userId);
1923 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07001924 }
1925 // Not found
1926 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07001927 }
1928 }
1929
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07001930 @Override
1931 public long getUserCreationTime(int userHandle) {
1932 int callingUserId = UserHandle.getCallingUserId();
1933 UserInfo userInfo = null;
1934 synchronized (mPackagesLock) {
1935 if (callingUserId == userHandle) {
1936 userInfo = getUserInfoLocked(userHandle);
1937 } else {
1938 UserInfo parent = getProfileParentLocked(userHandle);
1939 if (parent != null && parent.id == callingUserId) {
1940 userInfo = getUserInfoLocked(userHandle);
1941 }
1942 }
1943 }
1944 if (userInfo == null) {
1945 throw new SecurityException("userHandle can only be the calling user or a managed "
1946 + "profile associated with this user");
1947 }
1948 return userInfo.creationTime;
1949 }
1950
Amith Yamasani0b285492011-04-14 17:35:23 -07001951 /**
1952 * Caches the list of user ids in an array, adjusting the array size when necessary.
1953 */
Amith Yamasani13593602012-03-22 16:16:17 -07001954 private void updateUserIdsLocked() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001955 int num = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -07001956 for (int i = 0; i < mUsers.size(); i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001957 if (!mUsers.valueAt(i).partial) {
1958 num++;
1959 }
1960 }
Amith Yamasani16389312012-10-17 21:20:14 -07001961 final int[] newUsers = new int[num];
1962 int n = 0;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001963 for (int i = 0; i < mUsers.size(); i++) {
1964 if (!mUsers.valueAt(i).partial) {
Amith Yamasani16389312012-10-17 21:20:14 -07001965 newUsers[n++] = mUsers.keyAt(i);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001966 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001967 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001968 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07001969 }
1970
1971 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001972 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasani920ace02012-09-20 22:15:37 -07001973 * @param userId the user that was just foregrounded
1974 */
Amith Yamasani06bf8242015-05-08 16:36:21 -07001975 public void onUserForeground(int userId) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001976 synchronized (mPackagesLock) {
1977 UserInfo user = mUsers.get(userId);
1978 long now = System.currentTimeMillis();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001979 if (user == null || user.partial) {
1980 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
1981 return;
1982 }
1983 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001984 user.lastLoggedInTime = now;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001985 scheduleWriteUserLocked(user);
Amith Yamasani920ace02012-09-20 22:15:37 -07001986 }
1987 }
1988 }
1989
1990 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07001991 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani742a6712011-05-04 14:49:28 -07001992 * TODO: May not be a good idea to recycle ids, in case it results in confusion
1993 * for data and battery stats collection, or unexpected cross-talk.
Amith Yamasani0b285492011-04-14 17:35:23 -07001994 * @return
1995 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001996 private int getNextAvailableIdLocked() {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001997 synchronized (mPackagesLock) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001998 int i = MIN_USER_ID;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07001999 while (i < MAX_USER_ID) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002000 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002001 return i;
Amith Yamasani195263742012-08-21 15:40:12 -07002002 }
2003 i++;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002004 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002005 }
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002006 throw new IllegalStateException("No user id available!");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002007 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002008
Amith Yamasanifc95e702013-09-26 13:20:17 -07002009 private String packageToRestrictionsFileName(String packageName) {
2010 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
2011 }
2012
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002013 /**
2014 * Create new {@code /data/user/[id]} directory and sets default
2015 * permissions.
2016 */
Jeff Sharkey3bb8c852015-07-06 16:44:23 -07002017 public static void prepareUserDirectory(Context context, String volumeUuid, int userId) {
2018 final StorageManager storage = context.getSystemService(StorageManager.class);
2019 final File userDir = Environment.getDataUserDirectory(volumeUuid, userId);
2020 storage.createNewUserDir(userId, userDir);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002021 }
2022
2023 /**
2024 * Enforce that serial number stored in user directory inode matches the
2025 * given expected value. Gracefully sets the serial number if currently
2026 * undefined.
2027 *
2028 * @throws IOException when problem extracting serial number, or serial
2029 * number is mismatched.
2030 */
2031 public static void enforceSerialNumber(File file, int serialNumber) throws IOException {
2032 final int foundSerial = getSerialNumber(file);
2033 Slog.v(LOG_TAG, "Found " + file + " with serial number " + foundSerial);
2034
2035 if (foundSerial == -1) {
2036 Slog.d(LOG_TAG, "Serial number missing on " + file + "; assuming current is valid");
2037 try {
2038 setSerialNumber(file, serialNumber);
2039 } catch (IOException e) {
2040 Slog.w(LOG_TAG, "Failed to set serial number on " + file, e);
2041 }
2042
2043 } else if (foundSerial != serialNumber) {
2044 throw new IOException("Found serial number " + foundSerial
2045 + " doesn't match expected " + serialNumber);
2046 }
2047 }
2048
2049 /**
2050 * Set serial number stored in user directory inode.
2051 *
2052 * @throws IOException if serial number was already set
2053 */
2054 private static void setSerialNumber(File file, int serialNumber)
2055 throws IOException {
2056 try {
2057 final byte[] buf = Integer.toString(serialNumber).getBytes(StandardCharsets.UTF_8);
2058 Os.setxattr(file.getAbsolutePath(), XATTR_SERIAL, buf, OsConstants.XATTR_CREATE);
2059 } catch (ErrnoException e) {
2060 throw e.rethrowAsIOException();
2061 }
2062 }
2063
2064 /**
2065 * Return serial number stored in user directory inode.
2066 *
2067 * @return parsed serial number, or -1 if not set
2068 */
2069 private static int getSerialNumber(File file) throws IOException {
2070 try {
2071 final byte[] buf = new byte[256];
2072 final int len = Os.getxattr(file.getAbsolutePath(), XATTR_SERIAL, buf);
2073 final String serial = new String(buf, 0, len);
2074 try {
2075 return Integer.parseInt(serial);
2076 } catch (NumberFormatException e) {
2077 throw new IOException("Bad serial number: " + serial);
2078 }
2079 } catch (ErrnoException e) {
2080 if (e.errno == OsConstants.ENODATA) {
2081 return -1;
2082 } else {
2083 throw e.rethrowAsIOException();
2084 }
2085 }
2086 }
2087
Amith Yamasani920ace02012-09-20 22:15:37 -07002088 @Override
2089 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2090 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2091 != PackageManager.PERMISSION_GRANTED) {
2092 pw.println("Permission Denial: can't dump UserManager from from pid="
2093 + Binder.getCallingPid()
2094 + ", uid=" + Binder.getCallingUid()
2095 + " without permission "
2096 + android.Manifest.permission.DUMP);
2097 return;
2098 }
2099
2100 long now = System.currentTimeMillis();
2101 StringBuilder sb = new StringBuilder();
2102 synchronized (mPackagesLock) {
2103 pw.println("Users:");
2104 for (int i = 0; i < mUsers.size(); i++) {
2105 UserInfo user = mUsers.valueAt(i);
2106 if (user == null) continue;
Amith Yamasani634cf312012-10-04 17:34:21 -07002107 pw.print(" "); pw.print(user); pw.print(" serialNo="); pw.print(user.serialNumber);
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002108 if (mRemovingUserIds.get(mUsers.keyAt(i))) pw.print(" <removing> ");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002109 if (user.partial) pw.print(" <partial>");
2110 pw.println();
Amith Yamasani920ace02012-09-20 22:15:37 -07002111 pw.print(" Created: ");
2112 if (user.creationTime == 0) {
2113 pw.println("<unknown>");
2114 } else {
2115 sb.setLength(0);
2116 TimeUtils.formatDuration(now - user.creationTime, sb);
2117 sb.append(" ago");
2118 pw.println(sb);
2119 }
2120 pw.print(" Last logged in: ");
2121 if (user.lastLoggedInTime == 0) {
2122 pw.println("<unknown>");
2123 } else {
2124 sb.setLength(0);
2125 TimeUtils.formatDuration(now - user.lastLoggedInTime, sb);
2126 sb.append(" ago");
2127 pw.println(sb);
2128 }
2129 }
2130 }
2131 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002132
2133 final class MainHandler extends Handler {
2134
2135 @Override
2136 public void handleMessage(Message msg) {
2137 switch (msg.what) {
2138 case WRITE_USER_MSG:
2139 removeMessages(WRITE_USER_MSG, msg.obj);
2140 synchronized (mPackagesLock) {
2141 int userId = ((UserInfo) msg.obj).id;
2142 UserInfo userInfo = mUsers.get(userId);
2143 if (userInfo != null) {
2144 writeUserLocked(userInfo);
2145 }
2146 }
2147 }
2148 }
2149 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07002150
2151 /**
2152 * @param userId
2153 * @return whether the user has been initialized yet
2154 */
2155 boolean isInitialized(int userId) {
2156 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
2157 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002158}