blob: eb2109802181efb43ab4328674ce6415b15e02a0 [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
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070019import android.app.Activity;
Amith Yamasani2a003292012-08-14 18:25:45 -070020import android.app.ActivityManager;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070021import android.app.ActivityManagerNative;
22import android.app.IStopUserCallback;
Xiaohui Chen203243a2015-07-16 11:55:47 -070023import android.app.admin.DevicePolicyManager;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070024import android.content.BroadcastReceiver;
Amith Yamasani258848d2012-08-10 17:06:33 -070025import android.content.Context;
26import android.content.Intent;
Amith Yamasani1a7472e2013-07-02 11:17:30 -070027import android.content.pm.ApplicationInfo;
Amith Yamasani0b285492011-04-14 17:35:23 -070028import android.content.pm.PackageManager;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -080029import android.content.pm.PackageManager.NameNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070030import android.content.pm.UserInfo;
Amith Yamasanie928d7d2012-09-17 21:46:51 -070031import android.graphics.Bitmap;
Amith Yamasani258848d2012-08-10 17:06:33 -070032import android.os.Binder;
Amith Yamasanie4cf7342012-12-17 11:12:09 -080033import android.os.Bundle;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070034import android.os.Environment;
35import android.os.FileUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080036import android.os.Handler;
Amith Yamasani258848d2012-08-10 17:06:33 -070037import android.os.IUserManager;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -080038import android.os.Message;
Adrian Roos1bdff912015-02-17 15:51:35 +010039import android.os.ParcelFileDescriptor;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070040import android.os.Parcelable;
Amith Yamasani258848d2012-08-10 17:06:33 -070041import android.os.Process;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070042import android.os.RemoteException;
Jason Monk62062992014-05-06 09:55:28 -040043import android.os.ServiceManager;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070044import android.os.UserHandle;
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070045import android.os.UserManager;
Paul Crowley85e4e812015-05-19 12:42:00 +010046import android.os.storage.StorageManager;
Jeff Sharkey6dce4962015-07-03 18:08:41 -070047import android.os.storage.VolumeInfo;
48import android.system.ErrnoException;
49import android.system.Os;
50import android.system.OsConstants;
Amith Yamasani2a003292012-08-14 18:25:45 -070051import android.util.AtomicFile;
Amith Yamasani655d0e22013-06-12 14:19:10 -070052import android.util.Log;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070053import android.util.Slog;
54import android.util.SparseArray;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080055import android.util.SparseBooleanArray;
Amith Yamasani920ace02012-09-20 22:15:37 -070056import android.util.TimeUtils;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070057import android.util.Xml;
58
Fyodor Kupolovb5013302015-04-17 17:59:14 -070059import com.google.android.collect.Sets;
60
Fyodor Kupolov262f9952015-03-23 18:55:11 -070061import com.android.internal.annotations.VisibleForTesting;
Jason Monk62062992014-05-06 09:55:28 -040062import com.android.internal.app.IAppOpsService;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080063import com.android.internal.util.ArrayUtils;
64import com.android.internal.util.FastXmlSerializer;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070065import com.android.internal.util.XmlUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080066
67import org.xmlpull.v1.XmlPullParser;
68import org.xmlpull.v1.XmlPullParserException;
69import org.xmlpull.v1.XmlSerializer;
70
Amith Yamasani4b2e9342011-03-31 12:38:53 -070071import java.io.BufferedOutputStream;
72import java.io.File;
Amith Yamasani920ace02012-09-20 22:15:37 -070073import java.io.FileDescriptor;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070074import java.io.FileInputStream;
Amith Yamasanib8151ec2012-04-18 18:02:48 -070075import java.io.FileNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070076import java.io.FileOutputStream;
77import java.io.IOException;
Amith Yamasani920ace02012-09-20 22:15:37 -070078import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +010079import java.nio.charset.StandardCharsets;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070080import java.util.ArrayList;
81import java.util.List;
Fyodor Kupolovb5013302015-04-17 17:59:14 -070082import java.util.Set;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070083
Fyodor Kupolov262f9952015-03-23 18:55:11 -070084import libcore.io.IoUtils;
85
Amith Yamasani258848d2012-08-10 17:06:33 -070086public class UserManagerService extends IUserManager.Stub {
Amith Yamasanib8151ec2012-04-18 18:02:48 -070087
Amith Yamasani2a003292012-08-14 18:25:45 -070088 private static final String LOG_TAG = "UserManagerService";
Amith Yamasanib8151ec2012-04-18 18:02:48 -070089
Amith Yamasani16389312012-10-17 21:20:14 -070090 private static final boolean DBG = false;
91
Amith Yamasani4b2e9342011-03-31 12:38:53 -070092 private static final String TAG_NAME = "name";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070093 private static final String ATTR_FLAGS = "flags";
Amith Yamasanib8151ec2012-04-18 18:02:48 -070094 private static final String ATTR_ICON_PATH = "icon";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070095 private static final String ATTR_ID = "id";
Amith Yamasani920ace02012-09-20 22:15:37 -070096 private static final String ATTR_CREATION_TIME = "created";
97 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
Amith Yamasani2a003292012-08-14 18:25:45 -070098 private static final String ATTR_SERIAL_NO = "serialNumber";
99 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700100 private static final String ATTR_PARTIAL = "partial";
Adam Lesinskieddeb492014-09-08 17:50:03 -0700101 private static final String ATTR_GUEST_TO_REMOVE = "guestToRemove";
Amith Yamasani6f34b412012-10-22 18:19:27 -0700102 private static final String ATTR_USER_VERSION = "version";
Kenny Guy2a764942014-04-02 13:29:20 +0100103 private static final String ATTR_PROFILE_GROUP_ID = "profileGroupId";
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530104 private static final String TAG_GUEST_RESTRICTIONS = "guestRestrictions";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700105 private static final String TAG_USERS = "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700106 private static final String TAG_USER = "user";
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800107 private static final String TAG_RESTRICTIONS = "restrictions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800108 private static final String TAG_ENTRY = "entry";
109 private static final String TAG_VALUE = "value";
110 private static final String ATTR_KEY = "key";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700111 private static final String ATTR_VALUE_TYPE = "type";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800112 private static final String ATTR_MULTIPLE = "m";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700113
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700114 private static final String ATTR_TYPE_STRING_ARRAY = "sa";
115 private static final String ATTR_TYPE_STRING = "s";
116 private static final String ATTR_TYPE_BOOLEAN = "b";
Amith Yamasani5b5aa402014-06-01 20:10:14 -0700117 private static final String ATTR_TYPE_INTEGER = "i";
Fyodor Kupolov262f9952015-03-23 18:55:11 -0700118 private static final String ATTR_TYPE_BUNDLE = "B";
119 private static final String ATTR_TYPE_BUNDLE_ARRAY = "BA";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700120
Amith Yamasani0b285492011-04-14 17:35:23 -0700121 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700122 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700123 private static final String USER_PHOTO_FILENAME = "photo.png";
Adrian Roos1bdff912015-02-17 15:51:35 +0100124 private static final String USER_PHOTO_FILENAME_TMP = USER_PHOTO_FILENAME + ".tmp";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700125
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800126 private static final String RESTRICTIONS_FILE_PREFIX = "res_";
Amith Yamasanifc95e702013-09-26 13:20:17 -0700127 private static final String XML_SUFFIX = ".xml";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800128
Amith Yamasani634cf312012-10-04 17:34:21 -0700129 private static final int MIN_USER_ID = 10;
130
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700131 private static final int USER_VERSION = 5;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700132
Amith Yamasani920ace02012-09-20 22:15:37 -0700133 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
134
Amith Yamasani95ab7842014-08-11 17:09:26 -0700135 // Maximum number of managed profiles permitted is 1. This cannot be increased
136 // without first making sure that the rest of the framework is prepared for it.
137 private static final int MAX_MANAGED_PROFILES = 1;
138
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700139 // Set of user restrictions, which can only be enforced by the system
140 private static final Set<String> SYSTEM_CONTROLLED_RESTRICTIONS = Sets.newArraySet(
141 UserManager.DISALLOW_RECORD_AUDIO);
142
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800143 static final int WRITE_USER_MSG = 1;
144 static final int WRITE_USER_DELAY = 2*1000; // 2 seconds
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530145
Jeff Sharkey6dce4962015-07-03 18:08:41 -0700146 private static final String XATTR_SERIAL = "user.serial";
147
Dianne Hackborn4428e172012-08-24 17:43:05 -0700148 private final Context mContext;
149 private final PackageManagerService mPm;
150 private final Object mInstallLock;
151 private final Object mPackagesLock;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700152
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800153 private final Handler mHandler;
154
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700155 private final File mUsersDir;
156 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700157
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800158 private final SparseArray<UserInfo> mUsers = new SparseArray<UserInfo>();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800159 private final SparseArray<Bundle> mUserRestrictions = new SparseArray<Bundle>();
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530160 private final Bundle mGuestRestrictions = new Bundle();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800161
162 /**
163 * Set of user IDs being actively removed. Removed IDs linger in this set
164 * for several seconds to work around a VFS caching issue.
165 */
166 // @GuardedBy("mPackagesLock")
167 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700168
Amith Yamasani0b285492011-04-14 17:35:23 -0700169 private int[] mUserIds;
Amith Yamasani2a003292012-08-14 18:25:45 -0700170 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700171 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700172
Jason Monk62062992014-05-06 09:55:28 -0400173 private IAppOpsService mAppOpsService;
174
Amith Yamasani258848d2012-08-10 17:06:33 -0700175 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700176
Dianne Hackborn4428e172012-08-24 17:43:05 -0700177 public static UserManagerService getInstance() {
178 synchronized (UserManagerService.class) {
179 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700180 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700181 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700182
183 /**
184 * Available for testing purposes.
185 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700186 UserManagerService(File dataDir, File baseUserPath) {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700187 this(null, null, new Object(), new Object(), dataDir, baseUserPath);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700188 }
189
Dianne Hackborn4428e172012-08-24 17:43:05 -0700190 /**
191 * Called by package manager to create the service. This is closely
192 * associated with the package manager, and the given lock is the
193 * package manager's own lock.
194 */
195 UserManagerService(Context context, PackageManagerService pm,
196 Object installLock, Object packagesLock) {
197 this(context, pm, installLock, packagesLock,
198 Environment.getDataDirectory(),
199 new File(Environment.getDataDirectory(), "user"));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700200 }
201
Dianne Hackborn4428e172012-08-24 17:43:05 -0700202 /**
203 * Available for testing purposes.
204 */
205 private UserManagerService(Context context, PackageManagerService pm,
206 Object installLock, Object packagesLock,
207 File dataDir, File baseUserPath) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700208 mContext = context;
209 mPm = pm;
210 mInstallLock = installLock;
211 mPackagesLock = packagesLock;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800212 mHandler = new MainHandler();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700213 synchronized (mInstallLock) {
214 synchronized (mPackagesLock) {
215 mUsersDir = new File(dataDir, USER_INFO_DIR);
216 mUsersDir.mkdirs();
217 // Make zeroth user directory, for services to migrate their files to that location
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700218 File userZeroDir = new File(mUsersDir, String.valueOf(UserHandle.USER_SYSTEM));
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700219 userZeroDir.mkdirs();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700220 FileUtils.setPermissions(mUsersDir.toString(),
221 FileUtils.S_IRWXU|FileUtils.S_IRWXG
222 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
223 -1, -1);
224 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
Amith Yamasanida0b1682014-11-21 12:58:17 -0800225 initDefaultGuestRestrictions();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700226 readUserListLocked();
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700227 sInstance = this;
228 }
229 }
230 }
231
232 void systemReady() {
233 synchronized (mInstallLock) {
234 synchronized (mPackagesLock) {
Amith Yamasani756901d2012-10-12 12:30:07 -0700235 // Prune out any partially created/partially removed users.
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700236 ArrayList<UserInfo> partials = new ArrayList<UserInfo>();
237 for (int i = 0; i < mUsers.size(); i++) {
238 UserInfo ui = mUsers.valueAt(i);
Adam Lesinskieddeb492014-09-08 17:50:03 -0700239 if ((ui.partial || ui.guestToRemove) && i != 0) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700240 partials.add(ui);
241 }
242 }
243 for (int i = 0; i < partials.size(); i++) {
244 UserInfo ui = partials.get(i);
245 Slog.w(LOG_TAG, "Removing partially created user #" + i
246 + " (name=" + ui.name + ")");
247 removeUserStateLocked(ui.id);
248 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700249 }
Dianne Hackborn4428e172012-08-24 17:43:05 -0700250 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700251 onUserForeground(UserHandle.USER_SYSTEM);
Jason Monk62062992014-05-06 09:55:28 -0400252 mAppOpsService = IAppOpsService.Stub.asInterface(
253 ServiceManager.getService(Context.APP_OPS_SERVICE));
254 for (int i = 0; i < mUserIds.length; ++i) {
255 try {
256 mAppOpsService.setUserRestrictions(mUserRestrictions.get(mUserIds[i]), mUserIds[i]);
257 } catch (RemoteException e) {
258 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
259 }
260 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700261 }
262
263 @Override
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700264 public UserInfo getPrimaryUser() {
265 checkManageUsersPermission("query users");
266 synchronized (mPackagesLock) {
267 for (int i = 0; i < mUsers.size(); i++) {
268 UserInfo ui = mUsers.valueAt(i);
269 if (ui.isPrimary()) {
270 return ui;
271 }
272 }
273 }
274 return null;
275 }
276
277 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -0700278 public List<UserInfo> getUsers(boolean excludeDying) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700279 checkManageUsersPermission("query users");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700280 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700281 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
282 for (int i = 0; i < mUsers.size(); i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700283 UserInfo ui = mUsers.valueAt(i);
284 if (ui.partial) {
285 continue;
286 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800287 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700288 users.add(ui);
Amith Yamasani920ace02012-09-20 22:15:37 -0700289 }
Amith Yamasani13593602012-03-22 16:16:17 -0700290 }
291 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700292 }
Amith Yamasani13593602012-03-22 16:16:17 -0700293 }
294
Amith Yamasani258848d2012-08-10 17:06:33 -0700295 @Override
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100296 public List<UserInfo> getProfiles(int userId, boolean enabledOnly) {
Amith Yamasani4f582632014-02-19 14:31:52 -0800297 if (userId != UserHandle.getCallingUserId()) {
298 checkManageUsersPermission("getting profiles related to user " + userId);
299 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700300 final long ident = Binder.clearCallingIdentity();
301 try {
302 synchronized (mPackagesLock) {
303 return getProfilesLocked(userId, enabledOnly);
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100304 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700305 } finally {
306 Binder.restoreCallingIdentity(ident);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000307 }
308 }
309
Amith Yamasanibe465322014-04-24 13:45:17 -0700310 /** Assume permissions already checked and caller's identity cleared */
311 private List<UserInfo> getProfilesLocked(int userId, boolean enabledOnly) {
Amith Yamasanibe465322014-04-24 13:45:17 -0700312 UserInfo user = getUserInfoLocked(userId);
313 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasanidda003f2014-08-28 18:06:51 -0700314 if (user == null) {
315 // Probably a dying user
316 return users;
317 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700318 for (int i = 0; i < mUsers.size(); i++) {
319 UserInfo profile = mUsers.valueAt(i);
320 if (!isProfileOf(user, profile)) {
321 continue;
322 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100323 if (enabledOnly && !profile.isEnabled()) {
324 continue;
Amith Yamasanibe465322014-04-24 13:45:17 -0700325 }
Amith Yamasani70fcf0c2014-07-11 08:40:19 -0700326 if (mRemovingUserIds.get(profile.id)) {
327 continue;
328 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700329 users.add(profile);
330 }
331 return users;
332 }
333
Jessica Hummelbe81c802014-04-22 15:49:22 +0100334 @Override
335 public UserInfo getProfileParent(int userHandle) {
336 checkManageUsersPermission("get the profile parent");
337 synchronized (mPackagesLock) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700338 return getProfileParentLocked(userHandle);
339 }
340 }
341
342 private UserInfo getProfileParentLocked(int userHandle) {
343 UserInfo profile = getUserInfoLocked(userHandle);
344 if (profile == null) {
345 return null;
346 }
347 int parentUserId = profile.profileGroupId;
348 if (parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
349 return null;
350 } else {
351 return getUserInfoLocked(parentUserId);
Jessica Hummelbe81c802014-04-22 15:49:22 +0100352 }
353 }
354
Kenny Guy2a764942014-04-02 13:29:20 +0100355 private boolean isProfileOf(UserInfo user, UserInfo profile) {
356 return user.id == profile.id ||
357 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
358 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000359 }
360
361 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100362 public void setUserEnabled(int userId) {
363 checkManageUsersPermission("enable user");
364 synchronized (mPackagesLock) {
365 UserInfo info = getUserInfoLocked(userId);
366 if (info != null && !info.isEnabled()) {
367 info.flags ^= UserInfo.FLAG_DISABLED;
368 writeUserLocked(info);
369 }
370 }
371 }
372
373 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700374 public UserInfo getUserInfo(int userId) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700375 checkManageUsersPermission("query user");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700376 synchronized (mPackagesLock) {
Amith Yamasani195263742012-08-21 15:40:12 -0700377 return getUserInfoLocked(userId);
Amith Yamasani13593602012-03-22 16:16:17 -0700378 }
379 }
380
Amith Yamasani71e6c692013-03-24 17:39:28 -0700381 @Override
382 public boolean isRestricted() {
383 synchronized (mPackagesLock) {
384 return getUserInfoLocked(UserHandle.getCallingUserId()).isRestricted();
385 }
386 }
387
Amith Yamasani195263742012-08-21 15:40:12 -0700388 /*
389 * Should be locked on mUsers before calling this.
390 */
391 private UserInfo getUserInfoLocked(int userId) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700392 UserInfo ui = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -0700393 // If it is partial and not in the process of being removed, return as unknown user.
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800394 if (ui != null && ui.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700395 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
396 return null;
397 }
398 return ui;
Amith Yamasani195263742012-08-21 15:40:12 -0700399 }
400
Amith Yamasani13593602012-03-22 16:16:17 -0700401 public boolean exists(int userId) {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700402 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700403 return ArrayUtils.contains(mUserIds, userId);
404 }
405 }
406
Amith Yamasani258848d2012-08-10 17:06:33 -0700407 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700408 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700409 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700410 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700411 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700412 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700413 if (info == null || info.partial) {
414 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
415 return;
416 }
Amith Yamasani13593602012-03-22 16:16:17 -0700417 if (name != null && !name.equals(info.name)) {
418 info.name = name;
419 writeUserLocked(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700420 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -0700421 }
422 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700423 if (changed) {
424 sendUserInfoChangedBroadcast(userId);
425 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700426 }
427
Amith Yamasani258848d2012-08-10 17:06:33 -0700428 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700429 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700430 checkManageUsersPermission("update users");
Jason Monk9a944532014-07-08 09:31:21 -0400431 long ident = Binder.clearCallingIdentity();
432 try {
433 synchronized (mPackagesLock) {
434 UserInfo info = mUsers.get(userId);
435 if (info == null || info.partial) {
436 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
437 return;
438 }
439 writeBitmapLocked(info, bitmap);
440 writeUserLocked(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700441 }
Jason Monk9a944532014-07-08 09:31:21 -0400442 sendUserInfoChangedBroadcast(userId);
443 } finally {
444 Binder.restoreCallingIdentity(ident);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700445 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700446 }
447
448 private void sendUserInfoChangedBroadcast(int userId) {
449 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
450 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
451 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -0700452 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700453 }
454
Amith Yamasani258848d2012-08-10 17:06:33 -0700455 @Override
Adrian Roos1bdff912015-02-17 15:51:35 +0100456 public ParcelFileDescriptor getUserIcon(int userId) {
457 String iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700458 synchronized (mPackagesLock) {
459 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700460 if (info == null || info.partial) {
461 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + userId);
462 return null;
463 }
Nicolas Prevot88cc3462014-05-14 14:51:48 +0100464 int callingGroupId = mUsers.get(UserHandle.getCallingUserId()).profileGroupId;
465 if (callingGroupId == UserInfo.NO_PROFILE_GROUP_ID
466 || callingGroupId != info.profileGroupId) {
467 checkManageUsersPermission("get the icon of a user who is not related");
468 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700469 if (info.iconPath == null) {
470 return null;
471 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100472 iconPath = info.iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700473 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100474
475 try {
476 return ParcelFileDescriptor.open(
477 new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
478 } catch (FileNotFoundException e) {
479 Log.e(LOG_TAG, "Couldn't find icon file", e);
480 }
481 return null;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700482 }
483
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700484 public void makeInitialized(int userId) {
485 checkManageUsersPermission("makeInitialized");
486 synchronized (mPackagesLock) {
487 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700488 if (info == null || info.partial) {
489 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
490 }
491 if ((info.flags&UserInfo.FLAG_INITIALIZED) == 0) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700492 info.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800493 scheduleWriteUserLocked(info);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700494 }
495 }
496 }
497
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700498 /**
499 * If default guest restrictions haven't been initialized yet, add the basic
500 * restrictions.
501 */
502 private void initDefaultGuestRestrictions() {
503 if (mGuestRestrictions.isEmpty()) {
504 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
Amith Yamasanida0b1682014-11-21 12:58:17 -0800505 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700506 }
507 }
508
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800509 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530510 public Bundle getDefaultGuestRestrictions() {
511 checkManageUsersPermission("getDefaultGuestRestrictions");
512 synchronized (mPackagesLock) {
513 return new Bundle(mGuestRestrictions);
514 }
515 }
516
517 @Override
518 public void setDefaultGuestRestrictions(Bundle restrictions) {
519 checkManageUsersPermission("setDefaultGuestRestrictions");
520 synchronized (mPackagesLock) {
521 mGuestRestrictions.clear();
522 mGuestRestrictions.putAll(restrictions);
523 writeUserListLocked();
524 }
525 }
526
527 @Override
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700528 public boolean hasUserRestriction(String restrictionKey, int userId) {
529 synchronized (mPackagesLock) {
530 Bundle restrictions = mUserRestrictions.get(userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700531 return restrictions != null && restrictions.getBoolean(restrictionKey);
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700532 }
533 }
534
535 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800536 public Bundle getUserRestrictions(int userId) {
537 // checkManageUsersPermission("getUserRestrictions");
538
539 synchronized (mPackagesLock) {
540 Bundle restrictions = mUserRestrictions.get(userId);
Amith Yamasanibe465322014-04-24 13:45:17 -0700541 return restrictions != null ? new Bundle(restrictions) : new Bundle();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800542 }
543 }
544
545 @Override
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700546 public void setUserRestriction(String key, boolean value, int userId) {
547 synchronized (mPackagesLock) {
548 if (!SYSTEM_CONTROLLED_RESTRICTIONS.contains(key)) {
549 Bundle restrictions = getUserRestrictions(userId);
550 restrictions.putBoolean(key, value);
551 setUserRestrictionsInternalLocked(restrictions, userId);
552 }
553 }
554 }
555
556 @Override
557 public void setSystemControlledUserRestriction(String key, boolean value, int userId) {
558 checkSystemOrRoot("setSystemControlledUserRestriction");
559 synchronized (mPackagesLock) {
560 Bundle restrictions = getUserRestrictions(userId);
561 restrictions.putBoolean(key, value);
562 setUserRestrictionsInternalLocked(restrictions, userId);
563 }
564 }
565
566 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800567 public void setUserRestrictions(Bundle restrictions, int userId) {
Amith Yamasanibe465322014-04-24 13:45:17 -0700568 checkManageUsersPermission("setUserRestrictions");
Amith Yamasani0343ec32013-07-22 14:52:06 -0700569 if (restrictions == null) return;
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800570
571 synchronized (mPackagesLock) {
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700572 final Bundle oldUserRestrictions = mUserRestrictions.get(userId);
573 // Restore the original state of system controlled restrictions from oldUserRestrictions
574 for (String key : SYSTEM_CONTROLLED_RESTRICTIONS) {
575 restrictions.remove(key);
576 if (oldUserRestrictions.containsKey(key)) {
577 restrictions.putBoolean(key, oldUserRestrictions.getBoolean(key));
578 }
Jason Monk62062992014-05-06 09:55:28 -0400579 }
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700580 setUserRestrictionsInternalLocked(restrictions, userId);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800581 }
582 }
583
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700584 private void setUserRestrictionsInternalLocked(Bundle restrictions, int userId) {
585 final Bundle userRestrictions = mUserRestrictions.get(userId);
586 userRestrictions.clear();
587 userRestrictions.putAll(restrictions);
588 long token = Binder.clearCallingIdentity();
589 try {
590 mAppOpsService.setUserRestrictions(userRestrictions, userId);
591 } catch (RemoteException e) {
592 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
593 } finally {
594 Binder.restoreCallingIdentity(token);
595 }
596 scheduleWriteUserLocked(mUsers.get(userId));
597 }
598
Amith Yamasani258848d2012-08-10 17:06:33 -0700599 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700600 * Check if we've hit the limit of how many users can be created.
601 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700602 private boolean isUserLimitReachedLocked() {
Nicolas Prevot12678a92015-05-13 12:15:03 -0700603 return getAliveUsersExcludingGuestsCountLocked() >= UserManager.getMaxSupportedUsers();
604 }
605
606 @Override
607 public boolean canAddMoreManagedProfiles() {
608 checkManageUsersPermission("check if more managed profiles can be added.");
609 if (ActivityManager.isLowRamDeviceStatic()) {
610 return false;
611 }
Fyodor Kupolovb6157992015-06-05 15:32:28 -0700612 if (!mContext.getPackageManager().hasSystemFeature(
613 PackageManager.FEATURE_MANAGED_USERS)) {
614 return false;
615 }
Nicolas Prevot12678a92015-05-13 12:15:03 -0700616 synchronized(mPackagesLock) {
617 // Limit number of managed profiles that can be created
618 if (numberOfUsersOfTypeLocked(UserInfo.FLAG_MANAGED_PROFILE, true)
619 >= MAX_MANAGED_PROFILES) {
620 return false;
621 }
622 int usersCount = getAliveUsersExcludingGuestsCountLocked();
623 // We allow creating a managed profile in the special case where there is only one user.
624 return usersCount == 1 || usersCount < UserManager.getMaxSupportedUsers();
625 }
626 }
627
628 private int getAliveUsersExcludingGuestsCountLocked() {
Amith Yamasanif584f012014-05-19 17:57:25 -0700629 int aliveUserCount = 0;
630 final int totalUserCount = mUsers.size();
631 // Skip over users being removed
632 for (int i = 0; i < totalUserCount; i++) {
633 UserInfo user = mUsers.valueAt(i);
Amith Yamasani95ab7842014-08-11 17:09:26 -0700634 if (!mRemovingUserIds.get(user.id)
Amith Yamasani1df14732014-08-29 21:37:27 -0700635 && !user.isGuest() && !user.partial) {
Amith Yamasanif584f012014-05-19 17:57:25 -0700636 aliveUserCount++;
637 }
638 }
Nicolas Prevot12678a92015-05-13 12:15:03 -0700639 return aliveUserCount;
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700640 }
641
642 /**
Amith Yamasani195263742012-08-21 15:40:12 -0700643 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -0700644 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -0700645 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -0700646 *
647 * @param message used as message if SecurityException is thrown
648 * @throws SecurityException if the caller is not system or root
649 */
Amith Yamasanibe465322014-04-24 13:45:17 -0700650 private static final void checkManageUsersPermission(String message) {
Amith Yamasani258848d2012-08-10 17:06:33 -0700651 final int uid = Binder.getCallingUid();
Amith Yamasanibe465322014-04-24 13:45:17 -0700652 if (uid != Process.SYSTEM_UID && uid != 0
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400653 && ActivityManager.checkComponentPermission(
654 android.Manifest.permission.MANAGE_USERS,
Amith Yamasanibe465322014-04-24 13:45:17 -0700655 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
656 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
657 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400658 }
659
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700660 private static void checkSystemOrRoot(String message) {
661 final int uid = Binder.getCallingUid();
662 if (uid != Process.SYSTEM_UID && uid != 0) {
663 throw new SecurityException("Only system may call: " + message);
664 }
665 }
666
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700667 private void writeBitmapLocked(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700668 try {
669 File dir = new File(mUsersDir, Integer.toString(info.id));
670 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +0100671 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700672 if (!dir.exists()) {
673 dir.mkdir();
674 FileUtils.setPermissions(
675 dir.getPath(),
676 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
677 -1, -1);
678 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700679 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +0100680 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
681 && tmp.renameTo(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -0700682 info.iconPath = file.getAbsolutePath();
683 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700684 try {
685 os.close();
686 } catch (IOException ioe) {
687 // What the ... !
688 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100689 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700690 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700691 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700692 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700693 }
694
Amith Yamasani0b285492011-04-14 17:35:23 -0700695 /**
696 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
697 * cache it elsewhere.
698 * @return the array of user ids.
699 */
Dianne Hackborn1676c852012-09-10 14:52:30 -0700700 public int[] getUserIds() {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700701 synchronized (mPackagesLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700702 return mUserIds;
703 }
Amith Yamasani0b285492011-04-14 17:35:23 -0700704 }
705
Dianne Hackborn4428e172012-08-24 17:43:05 -0700706 int[] getUserIdsLPr() {
707 return mUserIds;
708 }
709
Amith Yamasani13593602012-03-22 16:16:17 -0700710 private void readUserListLocked() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700711 if (!mUserListFile.exists()) {
Amith Yamasani13593602012-03-22 16:16:17 -0700712 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700713 return;
714 }
715 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700716 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700717 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700718 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700719 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100720 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700721 int type;
722 while ((type = parser.next()) != XmlPullParser.START_TAG
723 && type != XmlPullParser.END_DOCUMENT) {
724 ;
725 }
726
727 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700728 Slog.e(LOG_TAG, "Unable to read user list");
Amith Yamasani13593602012-03-22 16:16:17 -0700729 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700730 return;
731 }
732
Amith Yamasani2a003292012-08-14 18:25:45 -0700733 mNextSerialNumber = -1;
734 if (parser.getName().equals(TAG_USERS)) {
735 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
736 if (lastSerialNumber != null) {
737 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
738 }
Amith Yamasani6f34b412012-10-22 18:19:27 -0700739 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
740 if (versionNumber != null) {
741 mUserVersion = Integer.parseInt(versionNumber);
742 }
Amith Yamasani2a003292012-08-14 18:25:45 -0700743 }
744
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700745 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530746 if (type == XmlPullParser.START_TAG) {
747 final String name = parser.getName();
748 if (name.equals(TAG_USER)) {
749 String id = parser.getAttributeValue(null, ATTR_ID);
750 UserInfo user = readUserLocked(Integer.parseInt(id));
Amith Yamasani6f34b412012-10-22 18:19:27 -0700751
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530752 if (user != null) {
753 mUsers.put(user.id, user);
754 if (mNextSerialNumber < 0 || mNextSerialNumber <= user.id) {
755 mNextSerialNumber = user.id + 1;
756 }
Amith Yamasani2a003292012-08-14 18:25:45 -0700757 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530758 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -0800759 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
760 && type != XmlPullParser.END_TAG) {
761 if (type == XmlPullParser.START_TAG) {
762 if (parser.getName().equals(TAG_RESTRICTIONS)) {
763 readRestrictionsLocked(parser, mGuestRestrictions);
764 }
765 break;
766 }
767 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700768 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700769 }
770 }
Amith Yamasani13593602012-03-22 16:16:17 -0700771 updateUserIdsLocked();
Amith Yamasani350962c2013-08-06 11:18:53 -0700772 upgradeIfNecessaryLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700773 } catch (IOException ioe) {
Amith Yamasani13593602012-03-22 16:16:17 -0700774 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700775 } catch (XmlPullParserException pe) {
Amith Yamasani13593602012-03-22 16:16:17 -0700776 fallbackToSingleUserLocked();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -0800777 } finally {
778 if (fis != null) {
779 try {
780 fis.close();
781 } catch (IOException e) {
782 }
783 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700784 }
785 }
786
Amith Yamasani6f34b412012-10-22 18:19:27 -0700787 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -0800788 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -0700789 */
Amith Yamasani350962c2013-08-06 11:18:53 -0700790 private void upgradeIfNecessaryLocked() {
Amith Yamasani6f34b412012-10-22 18:19:27 -0700791 int userVersion = mUserVersion;
792 if (userVersion < 1) {
793 // Assign a proper name for the owner, if not initialized correctly before
794 UserInfo user = mUsers.get(UserHandle.USER_OWNER);
795 if ("Primary".equals(user.name)) {
796 user.name = mContext.getResources().getString(com.android.internal.R.string.owner_name);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800797 scheduleWriteUserLocked(user);
Amith Yamasani6f34b412012-10-22 18:19:27 -0700798 }
799 userVersion = 1;
800 }
801
Amith Yamasanibc9625052012-11-15 14:39:18 -0800802 if (userVersion < 2) {
803 // Owner should be marked as initialized
804 UserInfo user = mUsers.get(UserHandle.USER_OWNER);
805 if ((user.flags & UserInfo.FLAG_INITIALIZED) == 0) {
806 user.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800807 scheduleWriteUserLocked(user);
Amith Yamasanibc9625052012-11-15 14:39:18 -0800808 }
809 userVersion = 2;
810 }
811
Amith Yamasani350962c2013-08-06 11:18:53 -0700812
Amith Yamasani5e486f52013-08-07 11:06:44 -0700813 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -0700814 userVersion = 4;
815 }
816
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700817 if (userVersion < 5) {
818 initDefaultGuestRestrictions();
819 userVersion = 5;
820 }
821
Amith Yamasani6f34b412012-10-22 18:19:27 -0700822 if (userVersion < USER_VERSION) {
823 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
824 + USER_VERSION);
825 } else {
826 mUserVersion = userVersion;
827 writeUserListLocked();
828 }
829 }
830
Amith Yamasani13593602012-03-22 16:16:17 -0700831 private void fallbackToSingleUserLocked() {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -0700832 int flags = UserInfo.FLAG_INITIALIZED;
833 // In split system user mode, the admin and primary flags are assigned to the first human
834 // user.
835 if (!UserManager.isSplitSystemUser()) {
836 flags |= UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY;
837 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700838 // Create the system user
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700839 UserInfo system = new UserInfo(UserHandle.USER_SYSTEM,
Amith Yamasani6f34b412012-10-22 18:19:27 -0700840 mContext.getResources().getString(com.android.internal.R.string.owner_name), null,
Xiaohui Chenb31e14a2015-07-13 16:04:55 -0700841 flags);
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700842 mUsers.put(system.id, system);
Amith Yamasani634cf312012-10-04 17:34:21 -0700843 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -0400844 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -0800845
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -0500846 Bundle restrictions = new Bundle();
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700847 mUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions);
Amith Yamasani67df64b2012-12-14 12:09:36 -0800848
Amith Yamasani13593602012-03-22 16:16:17 -0700849 updateUserIdsLocked();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700850 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700851
Amith Yamasani13593602012-03-22 16:16:17 -0700852 writeUserListLocked();
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700853 writeUserLocked(system);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700854 }
855
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800856 private void scheduleWriteUserLocked(UserInfo userInfo) {
857 if (!mHandler.hasMessages(WRITE_USER_MSG, userInfo)) {
858 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, userInfo);
859 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
860 }
861 }
862
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700863 /*
864 * Writes the user file in this format:
865 *
866 * <user flags="20039023" id="0">
867 * <name>Primary</name>
868 * </user>
869 */
Amith Yamasani13593602012-03-22 16:16:17 -0700870 private void writeUserLocked(UserInfo userInfo) {
Amith Yamasani742a6712011-05-04 14:49:28 -0700871 FileOutputStream fos = null;
Amith Yamasanifc95e702013-09-26 13:20:17 -0700872 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userInfo.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700873 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700874 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700875 final BufferedOutputStream bos = new BufferedOutputStream(fos);
876
877 // XmlSerializer serializer = XmlUtils.serializerInstance();
878 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100879 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700880 serializer.startDocument(null, true);
881 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
882
883 serializer.startTag(null, TAG_USER);
884 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
Amith Yamasani2a003292012-08-14 18:25:45 -0700885 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700886 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Amith Yamasani920ace02012-09-20 22:15:37 -0700887 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
888 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
889 Long.toString(userInfo.lastLoggedInTime));
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700890 if (userInfo.iconPath != null) {
891 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
892 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700893 if (userInfo.partial) {
894 serializer.attribute(null, ATTR_PARTIAL, "true");
895 }
Adam Lesinskieddeb492014-09-08 17:50:03 -0700896 if (userInfo.guestToRemove) {
897 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
898 }
Kenny Guy2a764942014-04-02 13:29:20 +0100899 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
900 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
901 Integer.toString(userInfo.profileGroupId));
Kenny Guya52dc3e2014-02-11 15:33:14 +0000902 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700903
904 serializer.startTag(null, TAG_NAME);
905 serializer.text(userInfo.name);
906 serializer.endTag(null, TAG_NAME);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800907 Bundle restrictions = mUserRestrictions.get(userInfo.id);
908 if (restrictions != null) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530909 writeRestrictionsLocked(serializer, restrictions);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800910 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700911 serializer.endTag(null, TAG_USER);
912
913 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -0700914 userFile.finishWrite(fos);
915 } catch (Exception ioe) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700916 Slog.e(LOG_TAG, "Error writing user info " + userInfo.id + "\n" + ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -0700917 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700918 }
919 }
920
921 /*
922 * Writes the user list file in this format:
923 *
Amith Yamasani2a003292012-08-14 18:25:45 -0700924 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700925 * <user id="0"></user>
926 * <user id="2"></user>
927 * </users>
928 */
Amith Yamasani13593602012-03-22 16:16:17 -0700929 private void writeUserListLocked() {
Amith Yamasani742a6712011-05-04 14:49:28 -0700930 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700931 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700932 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700933 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700934 final BufferedOutputStream bos = new BufferedOutputStream(fos);
935
936 // XmlSerializer serializer = XmlUtils.serializerInstance();
937 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100938 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700939 serializer.startDocument(null, true);
940 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
941
942 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -0700943 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -0700944 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700945
Adam Lesinskieddeb492014-09-08 17:50:03 -0700946 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530947 writeRestrictionsLocked(serializer, mGuestRestrictions);
948 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700949 for (int i = 0; i < mUsers.size(); i++) {
950 UserInfo user = mUsers.valueAt(i);
951 serializer.startTag(null, TAG_USER);
952 serializer.attribute(null, ATTR_ID, Integer.toString(user.id));
953 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700954 }
955
956 serializer.endTag(null, TAG_USERS);
957
958 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -0700959 userListFile.finishWrite(fos);
960 } catch (Exception e) {
961 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -0700962 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700963 }
964 }
965
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530966 private void writeRestrictionsLocked(XmlSerializer serializer, Bundle restrictions)
967 throws IOException {
968 serializer.startTag(null, TAG_RESTRICTIONS);
969 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_WIFI);
970 writeBoolean(serializer, restrictions, UserManager.DISALLOW_MODIFY_ACCOUNTS);
971 writeBoolean(serializer, restrictions, UserManager.DISALLOW_INSTALL_APPS);
972 writeBoolean(serializer, restrictions, UserManager.DISALLOW_UNINSTALL_APPS);
973 writeBoolean(serializer, restrictions, UserManager.DISALLOW_SHARE_LOCATION);
974 writeBoolean(serializer, restrictions,
975 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
976 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_BLUETOOTH);
977 writeBoolean(serializer, restrictions, UserManager.DISALLOW_USB_FILE_TRANSFER);
978 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_CREDENTIALS);
979 writeBoolean(serializer, restrictions, UserManager.DISALLOW_REMOVE_USER);
980 writeBoolean(serializer, restrictions, UserManager.DISALLOW_DEBUGGING_FEATURES);
981 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_VPN);
982 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_TETHERING);
Stuart Scott94b038b2015-04-20 14:07:45 -0700983 writeBoolean(serializer, restrictions, UserManager.DISALLOW_NETWORK_RESET);
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530984 writeBoolean(serializer, restrictions, UserManager.DISALLOW_FACTORY_RESET);
985 writeBoolean(serializer, restrictions, UserManager.DISALLOW_ADD_USER);
986 writeBoolean(serializer, restrictions, UserManager.ENSURE_VERIFY_APPS);
987 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_CELL_BROADCASTS);
988 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS);
989 writeBoolean(serializer, restrictions, UserManager.DISALLOW_APPS_CONTROL);
990 writeBoolean(serializer, restrictions, UserManager.DISALLOW_MOUNT_PHYSICAL_MEDIA);
991 writeBoolean(serializer, restrictions, UserManager.DISALLOW_UNMUTE_MICROPHONE);
992 writeBoolean(serializer, restrictions, UserManager.DISALLOW_ADJUST_VOLUME);
Amith Yamasani390989d2014-07-17 10:52:03 -0700993 writeBoolean(serializer, restrictions, UserManager.DISALLOW_OUTGOING_CALLS);
994 writeBoolean(serializer, restrictions, UserManager.DISALLOW_SMS);
Jeff Sharkey2cc03e52015-03-20 11:24:04 -0700995 writeBoolean(serializer, restrictions, UserManager.DISALLOW_FUN);
Jason Monk1c7c3192014-06-26 12:52:18 -0400996 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CREATE_WINDOWS);
Amith Yamasani26af8292014-09-09 09:57:27 -0700997 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CROSS_PROFILE_COPY_PASTE);
998 writeBoolean(serializer, restrictions, UserManager.DISALLOW_OUTGOING_BEAM);
Benjamin Franzf3ece362015-02-11 10:51:10 +0000999 writeBoolean(serializer, restrictions, UserManager.DISALLOW_WALLPAPER);
Benjamin Franzbff46ba2015-03-05 18:33:51 +00001000 writeBoolean(serializer, restrictions, UserManager.DISALLOW_SAFE_BOOT);
Nicolas Prevotf0029c12015-06-25 14:25:41 -07001001 writeBoolean(serializer, restrictions, UserManager.ALLOW_PARENT_PROFILE_APP_LINKING);
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301002 serializer.endTag(null, TAG_RESTRICTIONS);
1003 }
1004
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001005 private UserInfo readUserLocked(int id) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001006 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -07001007 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001008 String name = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001009 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -07001010 long creationTime = 0L;
1011 long lastLoggedInTime = 0L;
Kenny Guy2a764942014-04-02 13:29:20 +01001012 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001013 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001014 boolean guestToRemove = false;
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001015 Bundle restrictions = new Bundle();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001016
1017 FileInputStream fis = null;
1018 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001019 AtomicFile userFile =
Amith Yamasanifc95e702013-09-26 13:20:17 -07001020 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
Amith Yamasani2a003292012-08-14 18:25:45 -07001021 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001022 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001023 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001024 int type;
1025 while ((type = parser.next()) != XmlPullParser.START_TAG
1026 && type != XmlPullParser.END_DOCUMENT) {
1027 ;
1028 }
1029
1030 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001031 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001032 return null;
1033 }
1034
1035 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001036 int storedId = readIntAttribute(parser, ATTR_ID, -1);
1037 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001038 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001039 return null;
1040 }
Amith Yamasani920ace02012-09-20 22:15:37 -07001041 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
1042 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001043 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -07001044 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
1045 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Kenny Guy2a764942014-04-02 13:29:20 +01001046 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
1047 UserInfo.NO_PROFILE_GROUP_ID);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001048 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
1049 if ("true".equals(valueString)) {
1050 partial = true;
1051 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001052 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
1053 if ("true".equals(valueString)) {
1054 guestToRemove = true;
1055 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001056
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001057 int outerDepth = parser.getDepth();
1058 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1059 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1060 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1061 continue;
1062 }
1063 String tag = parser.getName();
1064 if (TAG_NAME.equals(tag)) {
1065 type = parser.next();
1066 if (type == XmlPullParser.TEXT) {
1067 name = parser.getText();
1068 }
1069 } else if (TAG_RESTRICTIONS.equals(tag)) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301070 readRestrictionsLocked(parser, restrictions);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001071 }
1072 }
1073 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001074
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001075 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -07001076 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -07001077 userInfo.creationTime = creationTime;
1078 userInfo.lastLoggedInTime = lastLoggedInTime;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001079 userInfo.partial = partial;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001080 userInfo.guestToRemove = guestToRemove;
Kenny Guy2a764942014-04-02 13:29:20 +01001081 userInfo.profileGroupId = profileGroupId;
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001082 mUserRestrictions.append(id, restrictions);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001083 return userInfo;
1084
1085 } catch (IOException ioe) {
1086 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001087 } finally {
1088 if (fis != null) {
1089 try {
1090 fis.close();
1091 } catch (IOException e) {
1092 }
1093 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001094 }
1095 return null;
1096 }
1097
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301098 private void readRestrictionsLocked(XmlPullParser parser, Bundle restrictions)
1099 throws IOException {
1100 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_WIFI);
1101 readBoolean(parser, restrictions, UserManager.DISALLOW_MODIFY_ACCOUNTS);
1102 readBoolean(parser, restrictions, UserManager.DISALLOW_INSTALL_APPS);
1103 readBoolean(parser, restrictions, UserManager.DISALLOW_UNINSTALL_APPS);
1104 readBoolean(parser, restrictions, UserManager.DISALLOW_SHARE_LOCATION);
1105 readBoolean(parser, restrictions,
1106 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
1107 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_BLUETOOTH);
1108 readBoolean(parser, restrictions, UserManager.DISALLOW_USB_FILE_TRANSFER);
1109 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_CREDENTIALS);
1110 readBoolean(parser, restrictions, UserManager.DISALLOW_REMOVE_USER);
1111 readBoolean(parser, restrictions, UserManager.DISALLOW_DEBUGGING_FEATURES);
1112 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_VPN);
1113 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_TETHERING);
Stuart Scott94b038b2015-04-20 14:07:45 -07001114 readBoolean(parser, restrictions, UserManager.DISALLOW_NETWORK_RESET);
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301115 readBoolean(parser, restrictions, UserManager.DISALLOW_FACTORY_RESET);
1116 readBoolean(parser, restrictions, UserManager.DISALLOW_ADD_USER);
1117 readBoolean(parser, restrictions, UserManager.ENSURE_VERIFY_APPS);
1118 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_CELL_BROADCASTS);
1119 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS);
1120 readBoolean(parser, restrictions, UserManager.DISALLOW_APPS_CONTROL);
1121 readBoolean(parser, restrictions,
1122 UserManager.DISALLOW_MOUNT_PHYSICAL_MEDIA);
1123 readBoolean(parser, restrictions, UserManager.DISALLOW_UNMUTE_MICROPHONE);
1124 readBoolean(parser, restrictions, UserManager.DISALLOW_ADJUST_VOLUME);
Amith Yamasani390989d2014-07-17 10:52:03 -07001125 readBoolean(parser, restrictions, UserManager.DISALLOW_OUTGOING_CALLS);
1126 readBoolean(parser, restrictions, UserManager.DISALLOW_SMS);
Jeff Sharkey2cc03e52015-03-20 11:24:04 -07001127 readBoolean(parser, restrictions, UserManager.DISALLOW_FUN);
Jason Monk1c7c3192014-06-26 12:52:18 -04001128 readBoolean(parser, restrictions, UserManager.DISALLOW_CREATE_WINDOWS);
Amith Yamasani26af8292014-09-09 09:57:27 -07001129 readBoolean(parser, restrictions, UserManager.DISALLOW_CROSS_PROFILE_COPY_PASTE);
1130 readBoolean(parser, restrictions, UserManager.DISALLOW_OUTGOING_BEAM);
Benjamin Franzf3ece362015-02-11 10:51:10 +00001131 readBoolean(parser, restrictions, UserManager.DISALLOW_WALLPAPER);
Benjamin Franzbff46ba2015-03-05 18:33:51 +00001132 readBoolean(parser, restrictions, UserManager.DISALLOW_SAFE_BOOT);
Nicolas Prevotf0029c12015-06-25 14:25:41 -07001133 readBoolean(parser, restrictions, UserManager.ALLOW_PARENT_PROFILE_APP_LINKING);
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301134 }
1135
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001136 private void readBoolean(XmlPullParser parser, Bundle restrictions,
1137 String restrictionKey) {
1138 String value = parser.getAttributeValue(null, restrictionKey);
Amith Yamasani71e6c692013-03-24 17:39:28 -07001139 if (value != null) {
1140 restrictions.putBoolean(restrictionKey, Boolean.parseBoolean(value));
1141 }
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001142 }
1143
1144 private void writeBoolean(XmlSerializer xml, Bundle restrictions, String restrictionKey)
1145 throws IOException {
1146 if (restrictions.containsKey(restrictionKey)) {
1147 xml.attribute(null, restrictionKey,
1148 Boolean.toString(restrictions.getBoolean(restrictionKey)));
1149 }
1150 }
1151
Amith Yamasani920ace02012-09-20 22:15:37 -07001152 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
1153 String valueString = parser.getAttributeValue(null, attr);
1154 if (valueString == null) return defaultValue;
1155 try {
1156 return Integer.parseInt(valueString);
1157 } catch (NumberFormatException nfe) {
1158 return defaultValue;
1159 }
1160 }
1161
1162 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
1163 String valueString = parser.getAttributeValue(null, attr);
1164 if (valueString == null) return defaultValue;
1165 try {
1166 return Long.parseLong(valueString);
1167 } catch (NumberFormatException nfe) {
1168 return defaultValue;
1169 }
1170 }
1171
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001172 private boolean isPackageInstalled(String pkg, int userId) {
1173 final ApplicationInfo info = mPm.getApplicationInfo(pkg,
1174 PackageManager.GET_UNINSTALLED_PACKAGES,
1175 userId);
1176 if (info == null || (info.flags&ApplicationInfo.FLAG_INSTALLED) == 0) {
1177 return false;
1178 }
1179 return true;
1180 }
1181
Amith Yamasanib82add22013-07-09 11:24:44 -07001182 /**
Kenny Guyd21b2182014-07-17 16:38:55 +01001183 * Removes all the restrictions files (res_<packagename>) for a given user.
Amith Yamasanib82add22013-07-09 11:24:44 -07001184 * Does not do any permissions checking.
1185 */
Kenny Guyd21b2182014-07-17 16:38:55 +01001186 private void cleanAppRestrictions(int userId) {
Amith Yamasanib82add22013-07-09 11:24:44 -07001187 synchronized (mPackagesLock) {
1188 File dir = Environment.getUserSystemDirectory(userId);
1189 String[] files = dir.list();
1190 if (files == null) return;
1191 for (String fileName : files) {
1192 if (fileName.startsWith(RESTRICTIONS_FILE_PREFIX)) {
1193 File resFile = new File(dir, fileName);
1194 if (resFile.exists()) {
Kenny Guyd21b2182014-07-17 16:38:55 +01001195 resFile.delete();
Amith Yamasanib82add22013-07-09 11:24:44 -07001196 }
1197 }
1198 }
1199 }
1200 }
1201
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001202 /**
1203 * Removes the app restrictions file for a specific package and user id, if it exists.
1204 */
1205 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
1206 synchronized (mPackagesLock) {
1207 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07001208 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001209 if (resFile.exists()) {
1210 resFile.delete();
1211 }
1212 }
1213 }
1214
Kenny Guya52dc3e2014-02-11 15:33:14 +00001215 @Override
Kenny Guy2a764942014-04-02 13:29:20 +01001216 public UserInfo createProfileForUser(String name, int flags, int userId) {
Kenny Guya52dc3e2014-02-11 15:33:14 +00001217 checkManageUsersPermission("Only the system can create users");
Kenny Guy2a764942014-04-02 13:29:20 +01001218 if (userId != UserHandle.USER_OWNER) {
1219 Slog.w(LOG_TAG, "Only user owner can have profiles");
Kenny Guya52dc3e2014-02-11 15:33:14 +00001220 return null;
1221 }
Kenny Guy2a764942014-04-02 13:29:20 +01001222 return createUserInternal(name, flags, userId);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001223 }
1224
Amith Yamasani258848d2012-08-10 17:06:33 -07001225 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07001226 public UserInfo createUser(String name, int flags) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001227 checkManageUsersPermission("Only the system can create users");
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001228 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001229 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001230
Jessica Hummelbe81c802014-04-22 15:49:22 +01001231 private UserInfo createUserInternal(String name, int flags, int parentId) {
Julia Reynolds75175022014-06-26 16:35:00 -04001232 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1233 UserManager.DISALLOW_ADD_USER, false)) {
1234 Log.w(LOG_TAG, "Cannot add user. DISALLOW_ADD_USER is enabled.");
1235 return null;
1236 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001237 if (ActivityManager.isLowRamDeviceStatic()) {
1238 return null;
1239 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07001240 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001241 final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001242 final long ident = Binder.clearCallingIdentity();
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001243 UserInfo userInfo = null;
Amith Yamasanibb054c92015-07-09 14:16:27 -07001244 final int userId;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001245 try {
1246 synchronized (mInstallLock) {
1247 synchronized (mPackagesLock) {
Jessica Hummelbe81c802014-04-22 15:49:22 +01001248 UserInfo parent = null;
1249 if (parentId != UserHandle.USER_NULL) {
1250 parent = getUserInfoLocked(parentId);
1251 if (parent == null) return null;
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001252 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001253 if (isManagedProfile && !canAddMoreManagedProfiles()) {
1254 return null;
1255 }
1256 if (!isGuest && !isManagedProfile && isUserLimitReachedLocked()) {
1257 // If we're not adding a guest user or a managed profile and the limit has
1258 // been reached, cannot add a user.
Amith Yamasani95ab7842014-08-11 17:09:26 -07001259 return null;
1260 }
1261 // If we're adding a guest and there already exists one, bail.
Adam Lesinskieddeb492014-09-08 17:50:03 -07001262 if (isGuest && findCurrentGuestUserLocked() != null) {
Amith Yamasani95ab7842014-08-11 17:09:26 -07001263 return null;
1264 }
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001265 // In split system user mode, we assign the first human user the primary flag.
Xiaohui Chen203243a2015-07-16 11:55:47 -07001266 // And if there is no device owner, we also assign the admin flag to primary
1267 // user.
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001268 if (UserManager.isSplitSystemUser()
Xiaohui Chen203243a2015-07-16 11:55:47 -07001269 && !isGuest && !isManagedProfile && getPrimaryUser() == null) {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001270 flags |= UserInfo.FLAG_PRIMARY;
Xiaohui Chen203243a2015-07-16 11:55:47 -07001271 DevicePolicyManager devicePolicyManager = (DevicePolicyManager)
1272 mContext.getSystemService(Context.DEVICE_POLICY_SERVICE);
1273 if (devicePolicyManager == null
1274 || devicePolicyManager.getDeviceOwner() == null) {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001275 flags |= UserInfo.FLAG_ADMIN;
1276 }
1277 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07001278 userId = getNextAvailableIdLocked();
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001279 userInfo = new UserInfo(userId, name, null, flags);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001280 userInfo.serialNumber = mNextSerialNumber++;
Amith Yamasani920ace02012-09-20 22:15:37 -07001281 long now = System.currentTimeMillis();
1282 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001283 userInfo.partial = true;
Amith Yamasani16389312012-10-17 21:20:14 -07001284 Environment.getUserSystemDirectory(userInfo.id).mkdirs();
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001285 mUsers.put(userId, userInfo);
1286 writeUserListLocked();
Jessica Hummelbe81c802014-04-22 15:49:22 +01001287 if (parent != null) {
1288 if (parent.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
1289 parent.profileGroupId = parent.id;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001290 scheduleWriteUserLocked(parent);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001291 }
Jessica Hummelbe81c802014-04-22 15:49:22 +01001292 userInfo.profileGroupId = parent.profileGroupId;
Kenny Guya52dc3e2014-02-11 15:33:14 +00001293 }
Jeff Sharkey6dce4962015-07-03 18:08:41 -07001294 final StorageManager storage = mContext.getSystemService(StorageManager.class);
1295 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
1296 final String volumeUuid = vol.getFsUuid();
1297 try {
1298 final File userDir = Environment.getDataUserDirectory(volumeUuid,
1299 userId);
Jeff Sharkey3bb8c852015-07-06 16:44:23 -07001300 prepareUserDirectory(mContext, volumeUuid, userId);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07001301 enforceSerialNumber(userDir, userInfo.serialNumber);
1302 } catch (IOException e) {
1303 Log.wtf(LOG_TAG, "Failed to create user directory on " + volumeUuid, e);
1304 }
1305 }
1306 mPm.createNewUserLILPw(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001307 userInfo.partial = false;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001308 scheduleWriteUserLocked(userInfo);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001309 updateUserIdsLocked();
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001310 Bundle restrictions = new Bundle();
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001311 mUserRestrictions.append(userId, restrictions);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001312 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07001313 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07001314 mPm.newUserCreated(userId);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001315 if (userInfo != null) {
1316 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
1317 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userInfo.id);
1318 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
1319 android.Manifest.permission.MANAGE_USERS);
1320 }
1321 } finally {
1322 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07001323 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001324 return userInfo;
1325 }
1326
Amith Yamasani95ab7842014-08-11 17:09:26 -07001327 private int numberOfUsersOfTypeLocked(int flags, boolean excludeDying) {
1328 int count = 0;
1329 for (int i = mUsers.size() - 1; i >= 0; i--) {
1330 UserInfo user = mUsers.valueAt(i);
1331 if (!excludeDying || !mRemovingUserIds.get(user.id)) {
1332 if ((user.flags & flags) != 0) {
1333 count++;
1334 }
1335 }
1336 }
1337 return count;
1338 }
1339
Amith Yamasani0b285492011-04-14 17:35:23 -07001340 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07001341 * Find the current guest user. If the Guest user is partial,
1342 * then do not include it in the results as it is about to die.
1343 * This is different than {@link #numberOfUsersOfTypeLocked(int, boolean)} due to
1344 * the special handling of Guests being removed.
1345 */
1346 private UserInfo findCurrentGuestUserLocked() {
1347 final int size = mUsers.size();
1348 for (int i = 0; i < size; i++) {
1349 final UserInfo user = mUsers.valueAt(i);
1350 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
1351 return user;
1352 }
1353 }
1354 return null;
1355 }
1356
1357 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07001358 * Mark this guest user for deletion to allow us to create another guest
1359 * and switch to that user before actually removing this guest.
1360 * @param userHandle the userid of the current guest
1361 * @return whether the user could be marked for deletion
1362 */
1363 public boolean markGuestForDeletion(int userHandle) {
1364 checkManageUsersPermission("Only the system can remove users");
1365 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1366 UserManager.DISALLOW_REMOVE_USER, false)) {
1367 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1368 return false;
1369 }
1370
1371 long ident = Binder.clearCallingIdentity();
1372 try {
1373 final UserInfo user;
1374 synchronized (mPackagesLock) {
1375 user = mUsers.get(userHandle);
1376 if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
1377 return false;
1378 }
1379 if (!user.isGuest()) {
1380 return false;
1381 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001382 // We set this to a guest user that is to be removed. This is a temporary state
1383 // where we are allowed to add new Guest users, even if this one is still not
1384 // removed. This user will still show up in getUserInfo() calls.
1385 // If we don't get around to removing this Guest user, it will be purged on next
1386 // startup.
1387 user.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07001388 // Mark it as disabled, so that it isn't returned any more when
1389 // profiles are queried.
1390 user.flags |= UserInfo.FLAG_DISABLED;
Amith Yamasani1df14732014-08-29 21:37:27 -07001391 writeUserLocked(user);
1392 }
1393 } finally {
1394 Binder.restoreCallingIdentity(ident);
1395 }
1396 return true;
1397 }
1398
1399 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07001400 * Removes a user and all data directories created for that user. This method should be called
1401 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001402 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07001403 */
Amith Yamasani258848d2012-08-10 17:06:33 -07001404 public boolean removeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001405 checkManageUsersPermission("Only the system can remove users");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04001406 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1407 UserManager.DISALLOW_REMOVE_USER, false)) {
1408 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1409 return false;
1410 }
1411
Kenny Guyee58b4f2014-05-23 15:19:53 +01001412 long ident = Binder.clearCallingIdentity();
1413 try {
1414 final UserInfo user;
1415 synchronized (mPackagesLock) {
1416 user = mUsers.get(userHandle);
Kenny Guy17c9d692014-06-13 13:51:42 +01001417 if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01001418 return false;
1419 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08001420
1421 // We remember deleted user IDs to prevent them from being
1422 // reused during the current boot; they can still be reused
1423 // after a reboot.
Kenny Guyee58b4f2014-05-23 15:19:53 +01001424 mRemovingUserIds.put(userHandle, true);
Jeff Sharkey6eb09392014-11-14 15:57:59 -08001425
Kenny Guyee58b4f2014-05-23 15:19:53 +01001426 try {
1427 mAppOpsService.removeUser(userHandle);
1428 } catch (RemoteException e) {
1429 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
1430 }
1431 // Set this to a partially created user, so that the user will be purged
1432 // on next startup, in case the runtime stops now before stopping and
1433 // removing the user completely.
1434 user.partial = true;
1435 // Mark it as disabled, so that it isn't returned any more when
1436 // profiles are queried.
1437 user.flags |= UserInfo.FLAG_DISABLED;
1438 writeUserLocked(user);
1439 }
1440
1441 if (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
1442 && user.isManagedProfile()) {
1443 // Send broadcast to notify system that the user removed was a
1444 // managed user.
1445 sendProfileRemovedBroadcast(user.profileGroupId, user.id);
1446 }
1447
1448 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
1449 int res;
1450 try {
1451 res = ActivityManagerNative.getDefault().stopUser(userHandle,
1452 new IStopUserCallback.Stub() {
1453 @Override
1454 public void userStopped(int userId) {
1455 finishRemoveUser(userId);
1456 }
1457 @Override
1458 public void userStopAborted(int userId) {
1459 }
1460 });
1461 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001462 return false;
1463 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01001464 return res == ActivityManager.USER_OP_SUCCESS;
1465 } finally {
1466 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001467 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001468 }
1469
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001470 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07001471 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001472 // Let other services shutdown any activity and clean up their state before completely
1473 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001474 long ident = Binder.clearCallingIdentity();
1475 try {
1476 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
1477 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001478 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
1479 android.Manifest.permission.MANAGE_USERS,
1480
1481 new BroadcastReceiver() {
1482 @Override
1483 public void onReceive(Context context, Intent intent) {
1484 if (DBG) {
1485 Slog.i(LOG_TAG,
1486 "USER_REMOVED broadcast sent, cleaning up user data "
1487 + userHandle);
1488 }
1489 new Thread() {
1490 public void run() {
1491 synchronized (mInstallLock) {
1492 synchronized (mPackagesLock) {
1493 removeUserStateLocked(userHandle);
1494 }
1495 }
1496 }
1497 }.start();
1498 }
1499 },
1500
1501 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001502 } finally {
1503 Binder.restoreCallingIdentity(ident);
1504 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001505 }
1506
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001507 private void removeUserStateLocked(final int userHandle) {
Paul Crowley85e4e812015-05-19 12:42:00 +01001508 mContext.getSystemService(StorageManager.class)
1509 .deleteUserKey(userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001510 // Cleanup package manager settings
Amith Yamasanidda003f2014-08-28 18:06:51 -07001511 mPm.cleanUpUserLILPw(this, userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001512
1513 // Remove this user from the list
1514 mUsers.remove(userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001515 // Remove user file
Amith Yamasanifc95e702013-09-26 13:20:17 -07001516 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001517 userFile.delete();
1518 // Update the user list
1519 writeUserListLocked();
1520 updateUserIdsLocked();
1521 removeDirectoryRecursive(Environment.getUserSystemDirectory(userHandle));
1522 }
1523
Amith Yamasani61f57372012-08-31 12:12:28 -07001524 private void removeDirectoryRecursive(File parent) {
1525 if (parent.isDirectory()) {
1526 String[] files = parent.list();
1527 for (String filename : files) {
1528 File child = new File(parent, filename);
1529 removeDirectoryRecursive(child);
1530 }
1531 }
1532 parent.delete();
1533 }
1534
Kenny Guyf8d3a232014-05-15 16:09:52 +01001535 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01001536 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01001537 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
1538 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01001539 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
1540 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01001541 }
1542
Amith Yamasani2a003292012-08-14 18:25:45 -07001543 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001544 public Bundle getApplicationRestrictions(String packageName) {
1545 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
1546 }
1547
1548 @Override
1549 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001550 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07001551 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001552 checkManageUsersPermission("Only system can get restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001553 }
1554 synchronized (mPackagesLock) {
1555 // Read the restrictions from XML
1556 return readApplicationRestrictionsLocked(packageName, userId);
1557 }
1558 }
1559
1560 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001561 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001562 int userId) {
1563 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07001564 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001565 checkManageUsersPermission("Only system can set restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001566 }
1567 synchronized (mPackagesLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01001568 if (restrictions == null || restrictions.isEmpty()) {
1569 cleanAppRestrictionsForPackage(packageName, userId);
1570 } else {
1571 // Write the restrictions to XML
1572 writeApplicationRestrictionsLocked(packageName, restrictions, userId);
1573 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001574 }
Robin Lee66e5d962014-04-09 16:44:21 +01001575
Kenny Guyd21b2182014-07-17 16:38:55 +01001576 if (isPackageInstalled(packageName, userId)) {
1577 // Notify package of changes via an intent - only sent to explicitly registered receivers.
1578 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
1579 changeIntent.setPackage(packageName);
1580 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
1581 mContext.sendBroadcastAsUser(changeIntent, new UserHandle(userId));
1582 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001583 }
1584
Amith Yamasani655d0e22013-06-12 14:19:10 -07001585 @Override
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001586 public void removeRestrictions() {
Amith Yamasanibe465322014-04-24 13:45:17 -07001587 checkManageUsersPermission("Only system can remove restrictions");
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001588 final int userHandle = UserHandle.getCallingUserId();
Amith Yamasani5e486f52013-08-07 11:06:44 -07001589 removeRestrictionsForUser(userHandle, true);
Amith Yamasani350962c2013-08-06 11:18:53 -07001590 }
1591
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001592 private void removeRestrictionsForUser(final int userHandle, boolean unhideApps) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001593 synchronized (mPackagesLock) {
1594 // Remove all user restrictions
1595 setUserRestrictions(new Bundle(), userHandle);
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001596 // Remove any app restrictions
Kenny Guyd21b2182014-07-17 16:38:55 +01001597 cleanAppRestrictions(userHandle);
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001598 }
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001599 if (unhideApps) {
1600 unhideAllInstalledAppsForUser(userHandle);
Amith Yamasani5e486f52013-08-07 11:06:44 -07001601 }
1602 }
1603
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001604 private void unhideAllInstalledAppsForUser(final int userHandle) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001605 mHandler.post(new Runnable() {
1606 @Override
1607 public void run() {
1608 List<ApplicationInfo> apps =
1609 mPm.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES,
1610 userHandle).getList();
1611 final long ident = Binder.clearCallingIdentity();
1612 try {
1613 for (ApplicationInfo appInfo : apps) {
1614 if ((appInfo.flags & ApplicationInfo.FLAG_INSTALLED) != 0
Alex Klyubinb9f8a522015-02-03 11:12:59 -08001615 && (appInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HIDDEN)
1616 != 0) {
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001617 mPm.setApplicationHiddenSettingAsUser(appInfo.packageName, false,
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001618 userHandle);
1619 }
1620 }
1621 } finally {
1622 Binder.restoreCallingIdentity(ident);
1623 }
1624 }
1625 });
1626 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001627 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07001628 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001629 try {
1630 return mContext.getPackageManager().getApplicationInfo(packageName,
1631 PackageManager.GET_UNINSTALLED_PACKAGES).uid;
1632 } catch (NameNotFoundException nnfe) {
1633 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07001634 } finally {
1635 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001636 }
1637 }
1638
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001639 private Bundle readApplicationRestrictionsLocked(String packageName,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001640 int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001641 AtomicFile restrictionsFile =
1642 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
1643 packageToRestrictionsFileName(packageName)));
1644 return readApplicationRestrictionsLocked(restrictionsFile);
1645 }
1646
1647 @VisibleForTesting
1648 static Bundle readApplicationRestrictionsLocked(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001649 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001650 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07001651 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07001652 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07001653 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001654
1655 FileInputStream fis = null;
1656 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001657 fis = restrictionsFile.openRead();
1658 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001659 parser.setInput(fis, StandardCharsets.UTF_8.name());
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001660 XmlUtils.nextElement(parser);
1661 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001662 Slog.e(LOG_TAG, "Unable to read restrictions file "
1663 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001664 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001665 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001666 while (parser.next() != XmlPullParser.END_DOCUMENT) {
1667 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001668 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001669 } catch (IOException|XmlPullParserException e) {
1670 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001671 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001672 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001673 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001674 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001675 }
1676
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001677 private static void readEntry(Bundle restrictions, ArrayList<String> values,
1678 XmlPullParser parser) throws XmlPullParserException, IOException {
1679 int type = parser.getEventType();
1680 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
1681 String key = parser.getAttributeValue(null, ATTR_KEY);
1682 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
1683 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
1684 if (multiple != null) {
1685 values.clear();
1686 int count = Integer.parseInt(multiple);
1687 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1688 if (type == XmlPullParser.START_TAG
1689 && parser.getName().equals(TAG_VALUE)) {
1690 values.add(parser.nextText().trim());
1691 count--;
1692 }
1693 }
1694 String [] valueStrings = new String[values.size()];
1695 values.toArray(valueStrings);
1696 restrictions.putStringArray(key, valueStrings);
1697 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
1698 restrictions.putBundle(key, readBundleEntry(parser, values));
1699 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
1700 final int outerDepth = parser.getDepth();
1701 ArrayList<Bundle> bundleList = new ArrayList<>();
1702 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
1703 Bundle childBundle = readBundleEntry(parser, values);
1704 bundleList.add(childBundle);
1705 }
1706 restrictions.putParcelableArray(key,
1707 bundleList.toArray(new Bundle[bundleList.size()]));
1708 } else {
1709 String value = parser.nextText().trim();
1710 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
1711 restrictions.putBoolean(key, Boolean.parseBoolean(value));
1712 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
1713 restrictions.putInt(key, Integer.parseInt(value));
1714 } else {
1715 restrictions.putString(key, value);
1716 }
1717 }
1718 }
1719 }
1720
1721 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
1722 throws IOException, XmlPullParserException {
1723 Bundle childBundle = new Bundle();
1724 final int outerDepth = parser.getDepth();
1725 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
1726 readEntry(childBundle, values, parser);
1727 }
1728 return childBundle;
1729 }
1730
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001731 private void writeApplicationRestrictionsLocked(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001732 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001733 AtomicFile restrictionsFile = new AtomicFile(
1734 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07001735 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001736 writeApplicationRestrictionsLocked(restrictions, restrictionsFile);
1737 }
1738
1739 @VisibleForTesting
1740 static void writeApplicationRestrictionsLocked(Bundle restrictions,
1741 AtomicFile restrictionsFile) {
1742 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001743 try {
1744 fos = restrictionsFile.startWrite();
1745 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1746
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001747 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001748 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001749 serializer.startDocument(null, true);
1750 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1751
1752 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001753 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001754 serializer.endTag(null, TAG_RESTRICTIONS);
1755
1756 serializer.endDocument();
1757 restrictionsFile.finishWrite(fos);
1758 } catch (Exception e) {
1759 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001760 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
1761 }
1762 }
1763
1764 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
1765 throws IOException {
1766 for (String key : restrictions.keySet()) {
1767 Object value = restrictions.get(key);
1768 serializer.startTag(null, TAG_ENTRY);
1769 serializer.attribute(null, ATTR_KEY, key);
1770
1771 if (value instanceof Boolean) {
1772 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
1773 serializer.text(value.toString());
1774 } else if (value instanceof Integer) {
1775 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
1776 serializer.text(value.toString());
1777 } else if (value == null || value instanceof String) {
1778 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
1779 serializer.text(value != null ? (String) value : "");
1780 } else if (value instanceof Bundle) {
1781 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
1782 writeBundle((Bundle) value, serializer);
1783 } else if (value instanceof Parcelable[]) {
1784 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
1785 Parcelable[] array = (Parcelable[]) value;
1786 for (Parcelable parcelable : array) {
1787 if (!(parcelable instanceof Bundle)) {
1788 throw new IllegalArgumentException("bundle-array can only hold Bundles");
1789 }
1790 serializer.startTag(null, TAG_ENTRY);
1791 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
1792 writeBundle((Bundle) parcelable, serializer);
1793 serializer.endTag(null, TAG_ENTRY);
1794 }
1795 } else {
1796 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
1797 String[] values = (String[]) value;
1798 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
1799 for (String choice : values) {
1800 serializer.startTag(null, TAG_VALUE);
1801 serializer.text(choice != null ? choice : "");
1802 serializer.endTag(null, TAG_VALUE);
1803 }
1804 }
1805 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001806 }
1807 }
1808
1809 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07001810 public int getUserSerialNumber(int userHandle) {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001811 synchronized (mPackagesLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001812 if (!exists(userHandle)) return -1;
Amith Yamasani195263742012-08-21 15:40:12 -07001813 return getUserInfoLocked(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07001814 }
1815 }
1816
1817 @Override
1818 public int getUserHandle(int userSerialNumber) {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001819 synchronized (mPackagesLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001820 for (int userId : mUserIds) {
Kenny Guy945f8832015-02-10 15:17:26 +00001821 UserInfo info = getUserInfoLocked(userId);
1822 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07001823 }
1824 // Not found
1825 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07001826 }
1827 }
1828
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07001829 @Override
1830 public long getUserCreationTime(int userHandle) {
1831 int callingUserId = UserHandle.getCallingUserId();
1832 UserInfo userInfo = null;
1833 synchronized (mPackagesLock) {
1834 if (callingUserId == userHandle) {
1835 userInfo = getUserInfoLocked(userHandle);
1836 } else {
1837 UserInfo parent = getProfileParentLocked(userHandle);
1838 if (parent != null && parent.id == callingUserId) {
1839 userInfo = getUserInfoLocked(userHandle);
1840 }
1841 }
1842 }
1843 if (userInfo == null) {
1844 throw new SecurityException("userHandle can only be the calling user or a managed "
1845 + "profile associated with this user");
1846 }
1847 return userInfo.creationTime;
1848 }
1849
Amith Yamasani0b285492011-04-14 17:35:23 -07001850 /**
1851 * Caches the list of user ids in an array, adjusting the array size when necessary.
1852 */
Amith Yamasani13593602012-03-22 16:16:17 -07001853 private void updateUserIdsLocked() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001854 int num = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -07001855 for (int i = 0; i < mUsers.size(); i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001856 if (!mUsers.valueAt(i).partial) {
1857 num++;
1858 }
1859 }
Amith Yamasani16389312012-10-17 21:20:14 -07001860 final int[] newUsers = new int[num];
1861 int n = 0;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001862 for (int i = 0; i < mUsers.size(); i++) {
1863 if (!mUsers.valueAt(i).partial) {
Amith Yamasani16389312012-10-17 21:20:14 -07001864 newUsers[n++] = mUsers.keyAt(i);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001865 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001866 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001867 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07001868 }
1869
1870 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001871 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasani920ace02012-09-20 22:15:37 -07001872 * @param userId the user that was just foregrounded
1873 */
Amith Yamasani06bf8242015-05-08 16:36:21 -07001874 public void onUserForeground(int userId) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001875 synchronized (mPackagesLock) {
1876 UserInfo user = mUsers.get(userId);
1877 long now = System.currentTimeMillis();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001878 if (user == null || user.partial) {
1879 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
1880 return;
1881 }
1882 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001883 user.lastLoggedInTime = now;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001884 scheduleWriteUserLocked(user);
Amith Yamasani920ace02012-09-20 22:15:37 -07001885 }
1886 }
1887 }
1888
1889 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07001890 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani742a6712011-05-04 14:49:28 -07001891 * TODO: May not be a good idea to recycle ids, in case it results in confusion
1892 * for data and battery stats collection, or unexpected cross-talk.
Amith Yamasani0b285492011-04-14 17:35:23 -07001893 * @return
1894 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001895 private int getNextAvailableIdLocked() {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001896 synchronized (mPackagesLock) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001897 int i = MIN_USER_ID;
Amith Yamasani195263742012-08-21 15:40:12 -07001898 while (i < Integer.MAX_VALUE) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001899 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
Amith Yamasani195263742012-08-21 15:40:12 -07001900 break;
1901 }
1902 i++;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001903 }
Amith Yamasani195263742012-08-21 15:40:12 -07001904 return i;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001905 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001906 }
Amith Yamasani920ace02012-09-20 22:15:37 -07001907
Amith Yamasanifc95e702013-09-26 13:20:17 -07001908 private String packageToRestrictionsFileName(String packageName) {
1909 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
1910 }
1911
Jeff Sharkey6dce4962015-07-03 18:08:41 -07001912 /**
1913 * Create new {@code /data/user/[id]} directory and sets default
1914 * permissions.
1915 */
Jeff Sharkey3bb8c852015-07-06 16:44:23 -07001916 public static void prepareUserDirectory(Context context, String volumeUuid, int userId) {
1917 final StorageManager storage = context.getSystemService(StorageManager.class);
1918 final File userDir = Environment.getDataUserDirectory(volumeUuid, userId);
1919 storage.createNewUserDir(userId, userDir);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07001920 }
1921
1922 /**
1923 * Enforce that serial number stored in user directory inode matches the
1924 * given expected value. Gracefully sets the serial number if currently
1925 * undefined.
1926 *
1927 * @throws IOException when problem extracting serial number, or serial
1928 * number is mismatched.
1929 */
1930 public static void enforceSerialNumber(File file, int serialNumber) throws IOException {
1931 final int foundSerial = getSerialNumber(file);
1932 Slog.v(LOG_TAG, "Found " + file + " with serial number " + foundSerial);
1933
1934 if (foundSerial == -1) {
1935 Slog.d(LOG_TAG, "Serial number missing on " + file + "; assuming current is valid");
1936 try {
1937 setSerialNumber(file, serialNumber);
1938 } catch (IOException e) {
1939 Slog.w(LOG_TAG, "Failed to set serial number on " + file, e);
1940 }
1941
1942 } else if (foundSerial != serialNumber) {
1943 throw new IOException("Found serial number " + foundSerial
1944 + " doesn't match expected " + serialNumber);
1945 }
1946 }
1947
1948 /**
1949 * Set serial number stored in user directory inode.
1950 *
1951 * @throws IOException if serial number was already set
1952 */
1953 private static void setSerialNumber(File file, int serialNumber)
1954 throws IOException {
1955 try {
1956 final byte[] buf = Integer.toString(serialNumber).getBytes(StandardCharsets.UTF_8);
1957 Os.setxattr(file.getAbsolutePath(), XATTR_SERIAL, buf, OsConstants.XATTR_CREATE);
1958 } catch (ErrnoException e) {
1959 throw e.rethrowAsIOException();
1960 }
1961 }
1962
1963 /**
1964 * Return serial number stored in user directory inode.
1965 *
1966 * @return parsed serial number, or -1 if not set
1967 */
1968 private static int getSerialNumber(File file) throws IOException {
1969 try {
1970 final byte[] buf = new byte[256];
1971 final int len = Os.getxattr(file.getAbsolutePath(), XATTR_SERIAL, buf);
1972 final String serial = new String(buf, 0, len);
1973 try {
1974 return Integer.parseInt(serial);
1975 } catch (NumberFormatException e) {
1976 throw new IOException("Bad serial number: " + serial);
1977 }
1978 } catch (ErrnoException e) {
1979 if (e.errno == OsConstants.ENODATA) {
1980 return -1;
1981 } else {
1982 throw e.rethrowAsIOException();
1983 }
1984 }
1985 }
1986
Amith Yamasani920ace02012-09-20 22:15:37 -07001987 @Override
1988 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1989 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1990 != PackageManager.PERMISSION_GRANTED) {
1991 pw.println("Permission Denial: can't dump UserManager from from pid="
1992 + Binder.getCallingPid()
1993 + ", uid=" + Binder.getCallingUid()
1994 + " without permission "
1995 + android.Manifest.permission.DUMP);
1996 return;
1997 }
1998
1999 long now = System.currentTimeMillis();
2000 StringBuilder sb = new StringBuilder();
2001 synchronized (mPackagesLock) {
2002 pw.println("Users:");
2003 for (int i = 0; i < mUsers.size(); i++) {
2004 UserInfo user = mUsers.valueAt(i);
2005 if (user == null) continue;
Amith Yamasani634cf312012-10-04 17:34:21 -07002006 pw.print(" "); pw.print(user); pw.print(" serialNo="); pw.print(user.serialNumber);
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002007 if (mRemovingUserIds.get(mUsers.keyAt(i))) pw.print(" <removing> ");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002008 if (user.partial) pw.print(" <partial>");
2009 pw.println();
Amith Yamasani920ace02012-09-20 22:15:37 -07002010 pw.print(" Created: ");
2011 if (user.creationTime == 0) {
2012 pw.println("<unknown>");
2013 } else {
2014 sb.setLength(0);
2015 TimeUtils.formatDuration(now - user.creationTime, sb);
2016 sb.append(" ago");
2017 pw.println(sb);
2018 }
2019 pw.print(" Last logged in: ");
2020 if (user.lastLoggedInTime == 0) {
2021 pw.println("<unknown>");
2022 } else {
2023 sb.setLength(0);
2024 TimeUtils.formatDuration(now - user.lastLoggedInTime, sb);
2025 sb.append(" ago");
2026 pw.println(sb);
2027 }
2028 }
2029 }
2030 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002031
2032 final class MainHandler extends Handler {
2033
2034 @Override
2035 public void handleMessage(Message msg) {
2036 switch (msg.what) {
2037 case WRITE_USER_MSG:
2038 removeMessages(WRITE_USER_MSG, msg.obj);
2039 synchronized (mPackagesLock) {
2040 int userId = ((UserInfo) msg.obj).id;
2041 UserInfo userInfo = mUsers.get(userId);
2042 if (userInfo != null) {
2043 writeUserLocked(userInfo);
2044 }
2045 }
2046 }
2047 }
2048 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07002049
2050 /**
2051 * @param userId
2052 * @return whether the user has been initialized yet
2053 */
2054 boolean isInitialized(int userId) {
2055 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
2056 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002057}