blob: c1f827fa733cc3b60d139162b6936198a5d8aae4 [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
Xiaohui Chen594f2082015-08-18 11:04:20 -070019import android.annotation.NonNull;
Makoto Onuki068c54a2015-10-13 14:34:03 -070020import android.annotation.Nullable;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070021import android.app.Activity;
Amith Yamasani2a003292012-08-14 18:25:45 -070022import android.app.ActivityManager;
Amith Yamasani515d4062015-09-28 11:30:06 -070023import android.app.ActivityManagerInternal;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070024import android.app.ActivityManagerNative;
25import android.app.IStopUserCallback;
Xiaohui Chen203243a2015-07-16 11:55:47 -070026import android.app.admin.DevicePolicyManager;
Makoto Onuki068c54a2015-10-13 14:34:03 -070027import android.app.admin.DevicePolicyManagerInternal;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070028import android.content.BroadcastReceiver;
Amith Yamasani258848d2012-08-10 17:06:33 -070029import android.content.Context;
30import android.content.Intent;
Amith Yamasani1a7472e2013-07-02 11:17:30 -070031import android.content.pm.ApplicationInfo;
Amith Yamasani0b285492011-04-14 17:35:23 -070032import android.content.pm.PackageManager;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -080033import android.content.pm.PackageManager.NameNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070034import android.content.pm.UserInfo;
Amith Yamasanie928d7d2012-09-17 21:46:51 -070035import android.graphics.Bitmap;
Amith Yamasani258848d2012-08-10 17:06:33 -070036import android.os.Binder;
Amith Yamasanie4cf7342012-12-17 11:12:09 -080037import android.os.Bundle;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070038import android.os.Environment;
39import android.os.FileUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080040import android.os.Handler;
Amith Yamasani258848d2012-08-10 17:06:33 -070041import android.os.IUserManager;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -080042import android.os.Message;
Adrian Roos1bdff912015-02-17 15:51:35 +010043import android.os.ParcelFileDescriptor;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070044import android.os.Parcelable;
Amith Yamasani258848d2012-08-10 17:06:33 -070045import android.os.Process;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070046import android.os.RemoteException;
Jason Monk62062992014-05-06 09:55:28 -040047import android.os.ServiceManager;
Clara Bayarrif05b9d02015-10-23 13:25:19 +010048import android.os.SystemProperties;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070049import android.os.UserHandle;
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070050import android.os.UserManager;
Makoto Onuki068c54a2015-10-13 14:34:03 -070051import android.os.UserManagerInternal;
Paul Crowley85e4e812015-05-19 12:42:00 +010052import android.os.storage.StorageManager;
Jeff Sharkey6dce4962015-07-03 18:08:41 -070053import android.os.storage.VolumeInfo;
54import android.system.ErrnoException;
55import android.system.Os;
56import android.system.OsConstants;
Amith Yamasani2a003292012-08-14 18:25:45 -070057import android.util.AtomicFile;
Amith Yamasani655d0e22013-06-12 14:19:10 -070058import android.util.Log;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070059import android.util.Slog;
60import android.util.SparseArray;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080061import android.util.SparseBooleanArray;
Amith Yamasani920ace02012-09-20 22:15:37 -070062import android.util.TimeUtils;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070063import android.util.Xml;
64
Makoto Onuki068c54a2015-10-13 14:34:03 -070065import com.android.internal.annotations.GuardedBy;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070066import com.android.internal.annotations.VisibleForTesting;
Jason Monk62062992014-05-06 09:55:28 -040067import com.android.internal.app.IAppOpsService;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080068import com.android.internal.util.FastXmlSerializer;
Makoto Onuki068c54a2015-10-13 14:34:03 -070069import com.android.internal.util.Preconditions;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070070import com.android.internal.util.XmlUtils;
Amith Yamasani515d4062015-09-28 11:30:06 -070071import com.android.server.LocalServices;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080072
73import org.xmlpull.v1.XmlPullParser;
74import org.xmlpull.v1.XmlPullParserException;
75import org.xmlpull.v1.XmlSerializer;
76
Amith Yamasani4b2e9342011-03-31 12:38:53 -070077import java.io.BufferedOutputStream;
78import java.io.File;
Amith Yamasani920ace02012-09-20 22:15:37 -070079import java.io.FileDescriptor;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070080import java.io.FileInputStream;
Amith Yamasanib8151ec2012-04-18 18:02:48 -070081import java.io.FileNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070082import java.io.FileOutputStream;
83import java.io.IOException;
Amith Yamasani920ace02012-09-20 22:15:37 -070084import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +010085import java.nio.charset.StandardCharsets;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070086import java.util.ArrayList;
87import java.util.List;
88
Fyodor Kupolov262f9952015-03-23 18:55:11 -070089import libcore.io.IoUtils;
90
Makoto Onuki068c54a2015-10-13 14:34:03 -070091/**
92 * Service for {@link UserManager}.
93 *
94 * Method naming convention:
95 * - Methods suffixed with "Locked" should be called within the {@code this} lock.
96 * - Methods suffixed with "RL" should be called within the {@link #mRestrictionsLock} lock.
97 */
Amith Yamasani258848d2012-08-10 17:06:33 -070098public class UserManagerService extends IUserManager.Stub {
Amith Yamasanib8151ec2012-04-18 18:02:48 -070099
Amith Yamasani2a003292012-08-14 18:25:45 -0700100 private static final String LOG_TAG = "UserManagerService";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700101
Makoto Onuki068c54a2015-10-13 14:34:03 -0700102 private static final boolean DBG = false; // DO NOT SUBMIT WITH TRUE
Amith Yamasani16389312012-10-17 21:20:14 -0700103
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700104 private static final String TAG_NAME = "name";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700105 private static final String ATTR_FLAGS = "flags";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700106 private static final String ATTR_ICON_PATH = "icon";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700107 private static final String ATTR_ID = "id";
Amith Yamasani920ace02012-09-20 22:15:37 -0700108 private static final String ATTR_CREATION_TIME = "created";
109 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
Amith Yamasani2a003292012-08-14 18:25:45 -0700110 private static final String ATTR_SERIAL_NO = "serialNumber";
111 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700112 private static final String ATTR_PARTIAL = "partial";
Adam Lesinskieddeb492014-09-08 17:50:03 -0700113 private static final String ATTR_GUEST_TO_REMOVE = "guestToRemove";
Amith Yamasani6f34b412012-10-22 18:19:27 -0700114 private static final String ATTR_USER_VERSION = "version";
Kenny Guy2a764942014-04-02 13:29:20 +0100115 private static final String ATTR_PROFILE_GROUP_ID = "profileGroupId";
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700116 private static final String ATTR_RESTRICTED_PROFILE_PARENT_ID = "restrictedProfileParentId";
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530117 private static final String TAG_GUEST_RESTRICTIONS = "guestRestrictions";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700118 private static final String TAG_USERS = "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700119 private static final String TAG_USER = "user";
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800120 private static final String TAG_RESTRICTIONS = "restrictions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800121 private static final String TAG_ENTRY = "entry";
122 private static final String TAG_VALUE = "value";
123 private static final String ATTR_KEY = "key";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700124 private static final String ATTR_VALUE_TYPE = "type";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800125 private static final String ATTR_MULTIPLE = "m";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700126
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700127 private static final String ATTR_TYPE_STRING_ARRAY = "sa";
128 private static final String ATTR_TYPE_STRING = "s";
129 private static final String ATTR_TYPE_BOOLEAN = "b";
Amith Yamasani5b5aa402014-06-01 20:10:14 -0700130 private static final String ATTR_TYPE_INTEGER = "i";
Fyodor Kupolov262f9952015-03-23 18:55:11 -0700131 private static final String ATTR_TYPE_BUNDLE = "B";
132 private static final String ATTR_TYPE_BUNDLE_ARRAY = "BA";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700133
Amith Yamasani0b285492011-04-14 17:35:23 -0700134 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700135 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700136 private static final String USER_PHOTO_FILENAME = "photo.png";
Adrian Roos1bdff912015-02-17 15:51:35 +0100137 private static final String USER_PHOTO_FILENAME_TMP = USER_PHOTO_FILENAME + ".tmp";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700138
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800139 private static final String RESTRICTIONS_FILE_PREFIX = "res_";
Amith Yamasanifc95e702013-09-26 13:20:17 -0700140 private static final String XML_SUFFIX = ".xml";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800141
Amith Yamasani634cf312012-10-04 17:34:21 -0700142 private static final int MIN_USER_ID = 10;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700143 // We need to keep process uid within Integer.MAX_VALUE.
144 private static final int MAX_USER_ID = Integer.MAX_VALUE / UserHandle.PER_USER_RANGE;
Amith Yamasani634cf312012-10-04 17:34:21 -0700145
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700146 private static final int USER_VERSION = 6;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700147
Amith Yamasani920ace02012-09-20 22:15:37 -0700148 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
149
Nicolas Prevotb8186812015-08-06 15:00:03 +0100150 // Maximum number of managed profiles permitted per user is 1. This cannot be increased
Amith Yamasani95ab7842014-08-11 17:09:26 -0700151 // without first making sure that the rest of the framework is prepared for it.
152 private static final int MAX_MANAGED_PROFILES = 1;
153
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800154 static final int WRITE_USER_MSG = 1;
155 static final int WRITE_USER_DELAY = 2*1000; // 2 seconds
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530156
Jeff Sharkey6dce4962015-07-03 18:08:41 -0700157 private static final String XATTR_SERIAL = "user.serial";
158
Dianne Hackborn4428e172012-08-24 17:43:05 -0700159 private final Context mContext;
160 private final PackageManagerService mPm;
161 private final Object mInstallLock;
162 private final Object mPackagesLock;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700163
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800164 private final Handler mHandler;
165
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700166 private final File mUsersDir;
167 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700168
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800169 private final SparseArray<UserInfo> mUsers = new SparseArray<UserInfo>();
Makoto Onuki068c54a2015-10-13 14:34:03 -0700170
171 private final Object mRestrictionsLock = new Object();
172
173 /**
174 * User restrictions set via UserManager. This doesn't include restrictions set by
175 * device owner / profile owners.
176 *
177 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
178 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
179 * maybe shared between {@link #mBaseUserRestrictions} and
180 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
181 * (Otherwise we won't be able to detect what restrictions have changed in
182 * {@link #updateUserRestrictionsInternalRL).
183 */
184 @GuardedBy("mRestrictionsLock")
185 private final SparseArray<Bundle> mBaseUserRestrictions = new SparseArray<>();
186
187 /**
188 * Cached user restrictions that are in effect -- i.e. {@link #mBaseUserRestrictions} combined
189 * with device / profile owner restrictions. We'll initialize it lazily; use
190 * {@link #getEffectiveUserRestrictions} to access it.
191 *
192 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
193 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
194 * maybe shared between {@link #mBaseUserRestrictions} and
195 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
196 * (Otherwise we won't be able to detect what restrictions have changed in
197 * {@link #updateUserRestrictionsInternalRL).
198 */
199 @GuardedBy("mRestrictionsLock")
200 private final SparseArray<Bundle> mCachedEffectiveUserRestrictions = new SparseArray<>();
201
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530202 private final Bundle mGuestRestrictions = new Bundle();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800203
204 /**
205 * Set of user IDs being actively removed. Removed IDs linger in this set
206 * for several seconds to work around a VFS caching issue.
207 */
208 // @GuardedBy("mPackagesLock")
209 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700210
Amith Yamasani0b285492011-04-14 17:35:23 -0700211 private int[] mUserIds;
Amith Yamasani2a003292012-08-14 18:25:45 -0700212 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700213 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700214
Jason Monk62062992014-05-06 09:55:28 -0400215 private IAppOpsService mAppOpsService;
216
Makoto Onuki068c54a2015-10-13 14:34:03 -0700217 private final LocalService mLocalService;
218
Amith Yamasani258848d2012-08-10 17:06:33 -0700219 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700220
Dianne Hackborn4428e172012-08-24 17:43:05 -0700221 public static UserManagerService getInstance() {
222 synchronized (UserManagerService.class) {
223 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700224 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700225 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700226
227 /**
228 * Available for testing purposes.
229 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700230 UserManagerService(File dataDir, File baseUserPath) {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700231 this(null, null, new Object(), new Object(), dataDir, baseUserPath);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700232 }
233
Dianne Hackborn4428e172012-08-24 17:43:05 -0700234 /**
235 * Called by package manager to create the service. This is closely
236 * associated with the package manager, and the given lock is the
237 * package manager's own lock.
238 */
239 UserManagerService(Context context, PackageManagerService pm,
240 Object installLock, Object packagesLock) {
241 this(context, pm, installLock, packagesLock,
242 Environment.getDataDirectory(),
243 new File(Environment.getDataDirectory(), "user"));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700244 }
245
Dianne Hackborn4428e172012-08-24 17:43:05 -0700246 /**
247 * Available for testing purposes.
248 */
249 private UserManagerService(Context context, PackageManagerService pm,
250 Object installLock, Object packagesLock,
251 File dataDir, File baseUserPath) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700252 mContext = context;
253 mPm = pm;
254 mInstallLock = installLock;
255 mPackagesLock = packagesLock;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800256 mHandler = new MainHandler();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700257 synchronized (mInstallLock) {
258 synchronized (mPackagesLock) {
259 mUsersDir = new File(dataDir, USER_INFO_DIR);
260 mUsersDir.mkdirs();
261 // Make zeroth user directory, for services to migrate their files to that location
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700262 File userZeroDir = new File(mUsersDir, String.valueOf(UserHandle.USER_SYSTEM));
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700263 userZeroDir.mkdirs();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700264 FileUtils.setPermissions(mUsersDir.toString(),
265 FileUtils.S_IRWXU|FileUtils.S_IRWXG
266 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
267 -1, -1);
268 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
Amith Yamasanida0b1682014-11-21 12:58:17 -0800269 initDefaultGuestRestrictions();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700270 readUserListLocked();
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700271 sInstance = this;
272 }
273 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700274 mLocalService = new LocalService();
275 LocalServices.addService(UserManagerInternal.class, mLocalService);
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700276 }
277
278 void systemReady() {
279 synchronized (mInstallLock) {
280 synchronized (mPackagesLock) {
Amith Yamasani756901d2012-10-12 12:30:07 -0700281 // Prune out any partially created/partially removed users.
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700282 ArrayList<UserInfo> partials = new ArrayList<UserInfo>();
Amith Yamasani515d4062015-09-28 11:30:06 -0700283 final int userSize = mUsers.size();
284 for (int i = 0; i < userSize; i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700285 UserInfo ui = mUsers.valueAt(i);
Adam Lesinskieddeb492014-09-08 17:50:03 -0700286 if ((ui.partial || ui.guestToRemove) && i != 0) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700287 partials.add(ui);
288 }
289 }
Amith Yamasani515d4062015-09-28 11:30:06 -0700290 final int partialsSize = partials.size();
291 for (int i = 0; i < partialsSize; i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700292 UserInfo ui = partials.get(i);
Amith Yamasania7892482015-08-07 11:09:05 -0700293 Slog.w(LOG_TAG, "Removing partially created user " + ui.id
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700294 + " (name=" + ui.name + ")");
295 removeUserStateLocked(ui.id);
296 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700297 }
Dianne Hackborn4428e172012-08-24 17:43:05 -0700298 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700299 onUserForeground(UserHandle.USER_SYSTEM);
Jason Monk62062992014-05-06 09:55:28 -0400300 mAppOpsService = IAppOpsService.Stub.asInterface(
301 ServiceManager.getService(Context.APP_OPS_SERVICE));
302 for (int i = 0; i < mUserIds.length; ++i) {
Makoto Onuki068c54a2015-10-13 14:34:03 -0700303 final int userId = mUserIds[i];
Jason Monk62062992014-05-06 09:55:28 -0400304 try {
Makoto Onuki068c54a2015-10-13 14:34:03 -0700305 mAppOpsService.setUserRestrictions(getEffectiveUserRestrictions(userId), userId);
Jason Monk62062992014-05-06 09:55:28 -0400306 } catch (RemoteException e) {
307 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
308 }
309 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700310 }
311
312 @Override
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700313 public UserInfo getPrimaryUser() {
314 checkManageUsersPermission("query users");
315 synchronized (mPackagesLock) {
Amith Yamasani515d4062015-09-28 11:30:06 -0700316 final int userSize = mUsers.size();
317 for (int i = 0; i < userSize; i++) {
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700318 UserInfo ui = mUsers.valueAt(i);
319 if (ui.isPrimary()) {
320 return ui;
321 }
322 }
323 }
324 return null;
325 }
326
327 @Override
Xiaohui Chen594f2082015-08-18 11:04:20 -0700328 public @NonNull List<UserInfo> getUsers(boolean excludeDying) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700329 checkManageUsersPermission("query users");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700330 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700331 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasani515d4062015-09-28 11:30:06 -0700332 final int userSize = mUsers.size();
333 for (int i = 0; i < userSize; i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700334 UserInfo ui = mUsers.valueAt(i);
335 if (ui.partial) {
336 continue;
337 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800338 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700339 users.add(ui);
Amith Yamasani920ace02012-09-20 22:15:37 -0700340 }
Amith Yamasani13593602012-03-22 16:16:17 -0700341 }
342 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700343 }
Amith Yamasani13593602012-03-22 16:16:17 -0700344 }
345
Amith Yamasani258848d2012-08-10 17:06:33 -0700346 @Override
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100347 public List<UserInfo> getProfiles(int userId, boolean enabledOnly) {
Amith Yamasani4f582632014-02-19 14:31:52 -0800348 if (userId != UserHandle.getCallingUserId()) {
349 checkManageUsersPermission("getting profiles related to user " + userId);
350 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700351 final long ident = Binder.clearCallingIdentity();
352 try {
353 synchronized (mPackagesLock) {
354 return getProfilesLocked(userId, enabledOnly);
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100355 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700356 } finally {
357 Binder.restoreCallingIdentity(ident);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000358 }
359 }
360
Amith Yamasanibe465322014-04-24 13:45:17 -0700361 /** Assume permissions already checked and caller's identity cleared */
362 private List<UserInfo> getProfilesLocked(int userId, boolean enabledOnly) {
Amith Yamasanibe465322014-04-24 13:45:17 -0700363 UserInfo user = getUserInfoLocked(userId);
364 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasanidda003f2014-08-28 18:06:51 -0700365 if (user == null) {
366 // Probably a dying user
367 return users;
368 }
Amith Yamasani515d4062015-09-28 11:30:06 -0700369 final int userSize = mUsers.size();
370 for (int i = 0; i < userSize; i++) {
Amith Yamasanibe465322014-04-24 13:45:17 -0700371 UserInfo profile = mUsers.valueAt(i);
372 if (!isProfileOf(user, profile)) {
373 continue;
374 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100375 if (enabledOnly && !profile.isEnabled()) {
376 continue;
Amith Yamasanibe465322014-04-24 13:45:17 -0700377 }
Amith Yamasani70fcf0c2014-07-11 08:40:19 -0700378 if (mRemovingUserIds.get(profile.id)) {
379 continue;
380 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700381 users.add(profile);
382 }
383 return users;
384 }
385
Jessica Hummelbe81c802014-04-22 15:49:22 +0100386 @Override
Andres Moralesc5548c02015-08-05 10:23:12 -0700387 public int getCredentialOwnerProfile(int userHandle) {
388 checkManageUsersPermission("get the credential owner");
Clara Bayarrif05b9d02015-10-23 13:25:19 +0100389 if (!"file".equals(SystemProperties.get("ro.crypto.type", "none"))) {
Andres Moralesc5548c02015-08-05 10:23:12 -0700390 synchronized (mPackagesLock) {
391 UserInfo profileParent = getProfileParentLocked(userHandle);
392 if (profileParent != null) {
393 return profileParent.id;
394 }
395 }
396 }
397
398 return userHandle;
399 }
400
401 @Override
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700402 public boolean isSameProfileGroup(int userId, int otherUserId) {
403 if (userId == otherUserId) return true;
404 checkManageUsersPermission("check if in the same profile group");
405 synchronized (mPackagesLock) {
406 return isSameProfileGroupLocked(userId, otherUserId);
407 }
408 }
409
410 private boolean isSameProfileGroupLocked(int userId, int otherUserId) {
411 UserInfo userInfo = getUserInfoLocked(userId);
412 if (userInfo == null || userInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
413 return false;
414 }
415 UserInfo otherUserInfo = getUserInfoLocked(otherUserId);
416 if (otherUserInfo == null || otherUserInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
417 return false;
418 }
419 return userInfo.profileGroupId == otherUserInfo.profileGroupId;
420 }
421
422 @Override
Jessica Hummelbe81c802014-04-22 15:49:22 +0100423 public UserInfo getProfileParent(int userHandle) {
424 checkManageUsersPermission("get the profile parent");
425 synchronized (mPackagesLock) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700426 return getProfileParentLocked(userHandle);
427 }
428 }
429
430 private UserInfo getProfileParentLocked(int userHandle) {
431 UserInfo profile = getUserInfoLocked(userHandle);
432 if (profile == null) {
433 return null;
434 }
435 int parentUserId = profile.profileGroupId;
436 if (parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
437 return null;
438 } else {
439 return getUserInfoLocked(parentUserId);
Jessica Hummelbe81c802014-04-22 15:49:22 +0100440 }
441 }
442
Kenny Guy2a764942014-04-02 13:29:20 +0100443 private boolean isProfileOf(UserInfo user, UserInfo profile) {
444 return user.id == profile.id ||
445 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
446 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000447 }
448
449 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100450 public void setUserEnabled(int userId) {
451 checkManageUsersPermission("enable user");
452 synchronized (mPackagesLock) {
453 UserInfo info = getUserInfoLocked(userId);
454 if (info != null && !info.isEnabled()) {
455 info.flags ^= UserInfo.FLAG_DISABLED;
456 writeUserLocked(info);
457 }
458 }
459 }
460
461 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700462 public UserInfo getUserInfo(int userId) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700463 checkManageUsersPermission("query user");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700464 synchronized (mPackagesLock) {
Amith Yamasani195263742012-08-21 15:40:12 -0700465 return getUserInfoLocked(userId);
Amith Yamasani13593602012-03-22 16:16:17 -0700466 }
467 }
468
Amith Yamasani71e6c692013-03-24 17:39:28 -0700469 @Override
470 public boolean isRestricted() {
471 synchronized (mPackagesLock) {
472 return getUserInfoLocked(UserHandle.getCallingUserId()).isRestricted();
473 }
474 }
475
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700476 @Override
477 public boolean canHaveRestrictedProfile(int userId) {
478 checkManageUsersPermission("canHaveRestrictedProfile");
479 synchronized (mPackagesLock) {
480 final UserInfo userInfo = getUserInfoLocked(userId);
481 if (userInfo == null || !userInfo.canHaveProfile()) {
482 return false;
483 }
484 if (!userInfo.isAdmin()) {
485 return false;
486 }
487 }
488 DevicePolicyManager dpm = (DevicePolicyManager) mContext.getSystemService(
489 Context.DEVICE_POLICY_SERVICE);
490 // restricted profile can be created if there is no DO set and the admin user has no PO
491 return dpm.getDeviceOwner() == null && dpm.getProfileOwnerAsUser(userId) == null;
492 }
493
Amith Yamasani195263742012-08-21 15:40:12 -0700494 /*
495 * Should be locked on mUsers before calling this.
496 */
497 private UserInfo getUserInfoLocked(int userId) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700498 UserInfo ui = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -0700499 // If it is partial and not in the process of being removed, return as unknown user.
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800500 if (ui != null && ui.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700501 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
502 return null;
503 }
504 return ui;
Amith Yamasani195263742012-08-21 15:40:12 -0700505 }
506
Amith Yamasani236b2b52015-08-18 14:32:14 -0700507 /** Called by PackageManagerService */
Amith Yamasani13593602012-03-22 16:16:17 -0700508 public boolean exists(int userId) {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700509 synchronized (mPackagesLock) {
Amith Yamasani236b2b52015-08-18 14:32:14 -0700510 return mUsers.get(userId) != null;
Amith Yamasani13593602012-03-22 16:16:17 -0700511 }
512 }
513
Amith Yamasani258848d2012-08-10 17:06:33 -0700514 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700515 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700516 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700517 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700518 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700519 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700520 if (info == null || info.partial) {
521 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
522 return;
523 }
Amith Yamasani13593602012-03-22 16:16:17 -0700524 if (name != null && !name.equals(info.name)) {
525 info.name = name;
526 writeUserLocked(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700527 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -0700528 }
529 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700530 if (changed) {
531 sendUserInfoChangedBroadcast(userId);
532 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700533 }
534
Amith Yamasani258848d2012-08-10 17:06:33 -0700535 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700536 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700537 checkManageUsersPermission("update users");
Jason Monk9a944532014-07-08 09:31:21 -0400538 long ident = Binder.clearCallingIdentity();
539 try {
540 synchronized (mPackagesLock) {
541 UserInfo info = mUsers.get(userId);
542 if (info == null || info.partial) {
543 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
544 return;
545 }
546 writeBitmapLocked(info, bitmap);
547 writeUserLocked(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700548 }
Jason Monk9a944532014-07-08 09:31:21 -0400549 sendUserInfoChangedBroadcast(userId);
550 } finally {
551 Binder.restoreCallingIdentity(ident);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700552 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700553 }
554
555 private void sendUserInfoChangedBroadcast(int userId) {
556 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
557 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
558 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -0700559 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700560 }
561
Amith Yamasani258848d2012-08-10 17:06:33 -0700562 @Override
Adrian Roos1bdff912015-02-17 15:51:35 +0100563 public ParcelFileDescriptor getUserIcon(int userId) {
564 String iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700565 synchronized (mPackagesLock) {
566 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700567 if (info == null || info.partial) {
568 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + userId);
569 return null;
570 }
Nicolas Prevot88cc3462014-05-14 14:51:48 +0100571 int callingGroupId = mUsers.get(UserHandle.getCallingUserId()).profileGroupId;
572 if (callingGroupId == UserInfo.NO_PROFILE_GROUP_ID
573 || callingGroupId != info.profileGroupId) {
574 checkManageUsersPermission("get the icon of a user who is not related");
575 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700576 if (info.iconPath == null) {
577 return null;
578 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100579 iconPath = info.iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700580 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100581
582 try {
583 return ParcelFileDescriptor.open(
584 new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
585 } catch (FileNotFoundException e) {
586 Log.e(LOG_TAG, "Couldn't find icon file", e);
587 }
588 return null;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700589 }
590
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700591 public void makeInitialized(int userId) {
592 checkManageUsersPermission("makeInitialized");
593 synchronized (mPackagesLock) {
594 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700595 if (info == null || info.partial) {
596 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
597 }
598 if ((info.flags&UserInfo.FLAG_INITIALIZED) == 0) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700599 info.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800600 scheduleWriteUserLocked(info);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700601 }
602 }
603 }
604
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700605 /**
606 * If default guest restrictions haven't been initialized yet, add the basic
607 * restrictions.
608 */
609 private void initDefaultGuestRestrictions() {
610 if (mGuestRestrictions.isEmpty()) {
611 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
Amith Yamasanida0b1682014-11-21 12:58:17 -0800612 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700613 }
614 }
615
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800616 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530617 public Bundle getDefaultGuestRestrictions() {
618 checkManageUsersPermission("getDefaultGuestRestrictions");
619 synchronized (mPackagesLock) {
620 return new Bundle(mGuestRestrictions);
621 }
622 }
623
624 @Override
625 public void setDefaultGuestRestrictions(Bundle restrictions) {
626 checkManageUsersPermission("setDefaultGuestRestrictions");
627 synchronized (mPackagesLock) {
628 mGuestRestrictions.clear();
629 mGuestRestrictions.putAll(restrictions);
630 writeUserListLocked();
631 }
632 }
633
Makoto Onuki068c54a2015-10-13 14:34:03 -0700634 @GuardedBy("mRestrictionsLock")
635 private Bundle computeEffectiveUserRestrictionsRL(int userId) {
636 final DevicePolicyManagerInternal dpmi =
637 LocalServices.getService(DevicePolicyManagerInternal.class);
638 final Bundle systemRestrictions = mBaseUserRestrictions.get(userId);
639
640 final Bundle effective;
641 if (dpmi == null) {
642 // TODO Make sure it's because DPMS is disabled and not because we called it too early.
643 effective = systemRestrictions;
644 } else {
645 effective = dpmi.getComposedUserRestrictions(userId, systemRestrictions);
646 }
647 return effective;
648 }
649
650 @GuardedBy("mRestrictionsLock")
651 private void invalidateEffectiveUserRestrictionsRL(int userId) {
652 if (DBG) {
653 Log.d(LOG_TAG, "invalidateEffectiveUserRestrictions userId=" + userId);
654 }
655 mCachedEffectiveUserRestrictions.remove(userId);
656 }
657
658 private Bundle getEffectiveUserRestrictions(int userId) {
659 synchronized (mRestrictionsLock) {
660 Bundle restrictions = mCachedEffectiveUserRestrictions.get(userId);
661 if (restrictions == null) {
662 restrictions = computeEffectiveUserRestrictionsRL(userId);
663 mCachedEffectiveUserRestrictions.put(userId, restrictions);
664 }
665 return restrictions;
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700666 }
667 }
668
Makoto Onuki068c54a2015-10-13 14:34:03 -0700669 /** @return a specific user restriction that's in effect currently. */
670 @Override
671 public boolean hasUserRestriction(String restrictionKey, int userId) {
672 Bundle restrictions = getEffectiveUserRestrictions(userId);
673 return restrictions != null && restrictions.getBoolean(restrictionKey);
674 }
675
676 /**
677 * @return UserRestrictions that are in effect currently. This always returns a new
678 * {@link Bundle}.
679 */
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700680 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800681 public Bundle getUserRestrictions(int userId) {
Makoto Onuki068c54a2015-10-13 14:34:03 -0700682 Bundle restrictions = getEffectiveUserRestrictions(userId);
683 return restrictions != null ? new Bundle(restrictions) : new Bundle();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800684 }
685
686 @Override
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700687 public void setUserRestriction(String key, boolean value, int userId) {
Fyodor Kupolovd4b26042015-07-27 14:30:59 -0700688 checkManageUsersPermission("setUserRestriction");
Makoto Onuki068c54a2015-10-13 14:34:03 -0700689 if (!UserRestrictionsUtils.SYSTEM_CONTROLLED_USER_RESTRICTIONS.contains(key)) {
690 setUserRestrictionNoCheck(key, value, userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700691 }
692 }
693
694 @Override
695 public void setSystemControlledUserRestriction(String key, boolean value, int userId) {
696 checkSystemOrRoot("setSystemControlledUserRestriction");
Makoto Onuki068c54a2015-10-13 14:34:03 -0700697 setUserRestrictionNoCheck(key, value, userId);
698 }
699
700 private void setUserRestrictionNoCheck(String key, boolean value, int userId) {
701 synchronized (mRestrictionsLock) {
702 // Note we can't modify Bundles stored in mBaseUserRestrictions directly, so create
703 // a copy.
704 final Bundle newRestrictions = new Bundle();
705 UserRestrictionsUtils.merge(newRestrictions, mBaseUserRestrictions.get(userId));
706 newRestrictions.putBoolean(key, value);
707
708 updateUserRestrictionsInternalRL(newRestrictions, userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700709 }
710 }
711
Makoto Onuki068c54a2015-10-13 14:34:03 -0700712 /**
713 * Optionally updating user restrictions, calculate the effective user restrictions by
714 * consulting {@link com.android.server.devicepolicy.DevicePolicyManagerService} and also
715 * apply it to {@link com.android.server.AppOpsService}.
716 * TODO applyUserRestrictionsLocked() should also apply to system settings.
717 *
718 * @param newRestrictions User restrictions to set. If null, only the effective restrictions
719 * will be updated. Note don't pass an existing Bundle in {@link #mBaseUserRestrictions}
720 * or {@link #mCachedEffectiveUserRestrictions}; that'll most likely cause a sub
721 * @param userId target user ID.
722 */
723 @GuardedBy("mRestrictionsLock")
724 private void updateUserRestrictionsInternalRL(
725 @Nullable Bundle newRestrictions, int userId) {
726 if (DBG) {
727 Log.d(LOG_TAG, "updateUserRestrictionsInternalLocked userId=" + userId
728 + " bundle=" + newRestrictions);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800729 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700730 final Bundle prevRestrictions = getEffectiveUserRestrictions(userId);
731
732 // Update system restrictions.
733 if (newRestrictions != null) {
734 // If newRestrictions == the current one, it's probably a bug.
735 Preconditions.checkState(mBaseUserRestrictions.get(userId) != newRestrictions);
736 Preconditions.checkState(mCachedEffectiveUserRestrictions.get(userId)
737 != newRestrictions);
738 mBaseUserRestrictions.put(userId, newRestrictions);
739 }
740
Makoto Onuki759a7632015-10-28 16:43:10 -0700741 final Bundle effective = computeEffectiveUserRestrictionsRL(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700742
Makoto Onuki759a7632015-10-28 16:43:10 -0700743 mCachedEffectiveUserRestrictions.put(userId, effective);
744
745 applyUserRestrictionsRL(userId, effective, prevRestrictions);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800746 }
747
Makoto Onuki068c54a2015-10-13 14:34:03 -0700748 @GuardedBy("mRestrictionsLock")
749 private void applyUserRestrictionsRL(int userId,
750 Bundle newRestrictions, Bundle prevRestrictions) {
751 final long token = Binder.clearCallingIdentity();
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700752 try {
Makoto Onuki068c54a2015-10-13 14:34:03 -0700753 mAppOpsService.setUserRestrictions(newRestrictions, userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700754 } catch (RemoteException e) {
755 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
756 } finally {
757 Binder.restoreCallingIdentity(token);
758 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700759
760 // TODO Move the code from DPMS.setUserRestriction().
761 }
762
763 @GuardedBy("mRestrictionsLock")
764 private void updateEffectiveUserRestrictionsRL(int userId) {
765 updateUserRestrictionsInternalRL(null, userId);
766 }
767
768 @GuardedBy("mRestrictionsLock")
769 private void updateEffectiveUserRestrictionsForAllUsersRL() {
770 // First, invalidate all cached values.
771 synchronized (mRestrictionsLock) {
772 mCachedEffectiveUserRestrictions.clear();
773 }
774 // We don't want to call into ActivityManagerNative while taking a lock, so we'll call
775 // it on a handler.
776 final Runnable r = new Runnable() {
777 @Override
778 public void run() {
779 // Then get the list of running users.
780 final int[] runningUsers;
781 try {
782 runningUsers = ActivityManagerNative.getDefault().getRunningUserIds();
783 } catch (RemoteException e) {
784 Log.w(LOG_TAG, "Unable to access ActivityManagerNative");
785 return;
786 }
787 // Then re-calculate the effective restrictions and apply, only for running users.
788 // It's okay if a new user has started after the getRunningUserIds() call,
789 // because we'll do the same thing (re-calculate the restrictions and apply)
790 // when we start a user.
791 // TODO: "Apply restrictions upon user start hasn't been implemented. Implement it.
792 synchronized (mRestrictionsLock) {
793 for (int i = 0; i < runningUsers.length; i++) {
794 updateUserRestrictionsInternalRL(null, runningUsers[i]);
795 }
796 }
797 }
798 };
799 mHandler.post(r);
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700800 }
801
Amith Yamasani258848d2012-08-10 17:06:33 -0700802 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700803 * Check if we've hit the limit of how many users can be created.
804 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700805 private boolean isUserLimitReachedLocked() {
Nicolas Prevot12678a92015-05-13 12:15:03 -0700806 return getAliveUsersExcludingGuestsCountLocked() >= UserManager.getMaxSupportedUsers();
807 }
808
809 @Override
Nicolas Prevotb8186812015-08-06 15:00:03 +0100810 public boolean canAddMoreManagedProfiles(int userId) {
Nicolas Prevot12678a92015-05-13 12:15:03 -0700811 checkManageUsersPermission("check if more managed profiles can be added.");
812 if (ActivityManager.isLowRamDeviceStatic()) {
813 return false;
814 }
Fyodor Kupolovb6157992015-06-05 15:32:28 -0700815 if (!mContext.getPackageManager().hasSystemFeature(
816 PackageManager.FEATURE_MANAGED_USERS)) {
817 return false;
818 }
Nicolas Prevotb8186812015-08-06 15:00:03 +0100819 // Limit number of managed profiles that can be created
820 int managedProfilesCount = getProfiles(userId, true).size() - 1;
821 if (managedProfilesCount >= MAX_MANAGED_PROFILES) {
822 return false;
823 }
Nicolas Prevot12678a92015-05-13 12:15:03 -0700824 synchronized(mPackagesLock) {
Nicolas Prevotb8186812015-08-06 15:00:03 +0100825 UserInfo userInfo = getUserInfoLocked(userId);
826 if (!userInfo.canHaveProfile()) {
Nicolas Prevot12678a92015-05-13 12:15:03 -0700827 return false;
828 }
829 int usersCount = getAliveUsersExcludingGuestsCountLocked();
830 // We allow creating a managed profile in the special case where there is only one user.
831 return usersCount == 1 || usersCount < UserManager.getMaxSupportedUsers();
832 }
833 }
834
835 private int getAliveUsersExcludingGuestsCountLocked() {
Amith Yamasanif584f012014-05-19 17:57:25 -0700836 int aliveUserCount = 0;
837 final int totalUserCount = mUsers.size();
838 // Skip over users being removed
839 for (int i = 0; i < totalUserCount; i++) {
840 UserInfo user = mUsers.valueAt(i);
Amith Yamasani95ab7842014-08-11 17:09:26 -0700841 if (!mRemovingUserIds.get(user.id)
Amith Yamasani1df14732014-08-29 21:37:27 -0700842 && !user.isGuest() && !user.partial) {
Amith Yamasanif584f012014-05-19 17:57:25 -0700843 aliveUserCount++;
844 }
845 }
Nicolas Prevot12678a92015-05-13 12:15:03 -0700846 return aliveUserCount;
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700847 }
848
849 /**
Amith Yamasani195263742012-08-21 15:40:12 -0700850 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -0700851 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -0700852 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -0700853 *
854 * @param message used as message if SecurityException is thrown
855 * @throws SecurityException if the caller is not system or root
856 */
Amith Yamasanibe465322014-04-24 13:45:17 -0700857 private static final void checkManageUsersPermission(String message) {
Amith Yamasani258848d2012-08-10 17:06:33 -0700858 final int uid = Binder.getCallingUid();
Amith Yamasanibe465322014-04-24 13:45:17 -0700859 if (uid != Process.SYSTEM_UID && uid != 0
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400860 && ActivityManager.checkComponentPermission(
861 android.Manifest.permission.MANAGE_USERS,
Amith Yamasanibe465322014-04-24 13:45:17 -0700862 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
863 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
864 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400865 }
866
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700867 private static void checkSystemOrRoot(String message) {
868 final int uid = Binder.getCallingUid();
869 if (uid != Process.SYSTEM_UID && uid != 0) {
870 throw new SecurityException("Only system may call: " + message);
871 }
872 }
873
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700874 private void writeBitmapLocked(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700875 try {
876 File dir = new File(mUsersDir, Integer.toString(info.id));
877 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +0100878 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700879 if (!dir.exists()) {
880 dir.mkdir();
881 FileUtils.setPermissions(
882 dir.getPath(),
883 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
884 -1, -1);
885 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700886 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +0100887 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
888 && tmp.renameTo(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -0700889 info.iconPath = file.getAbsolutePath();
890 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700891 try {
892 os.close();
893 } catch (IOException ioe) {
894 // What the ... !
895 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100896 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700897 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700898 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700899 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700900 }
901
Amith Yamasani0b285492011-04-14 17:35:23 -0700902 /**
903 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
904 * cache it elsewhere.
905 * @return the array of user ids.
906 */
Dianne Hackborn1676c852012-09-10 14:52:30 -0700907 public int[] getUserIds() {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700908 synchronized (mPackagesLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700909 return mUserIds;
910 }
Amith Yamasani0b285492011-04-14 17:35:23 -0700911 }
912
Dianne Hackborn4428e172012-08-24 17:43:05 -0700913 int[] getUserIdsLPr() {
914 return mUserIds;
915 }
916
Amith Yamasani13593602012-03-22 16:16:17 -0700917 private void readUserListLocked() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700918 if (!mUserListFile.exists()) {
Amith Yamasani13593602012-03-22 16:16:17 -0700919 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700920 return;
921 }
922 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700923 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700924 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700925 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700926 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100927 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700928 int type;
929 while ((type = parser.next()) != XmlPullParser.START_TAG
930 && type != XmlPullParser.END_DOCUMENT) {
931 ;
932 }
933
934 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700935 Slog.e(LOG_TAG, "Unable to read user list");
Amith Yamasani13593602012-03-22 16:16:17 -0700936 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700937 return;
938 }
939
Amith Yamasani2a003292012-08-14 18:25:45 -0700940 mNextSerialNumber = -1;
941 if (parser.getName().equals(TAG_USERS)) {
942 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
943 if (lastSerialNumber != null) {
944 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
945 }
Amith Yamasani6f34b412012-10-22 18:19:27 -0700946 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
947 if (versionNumber != null) {
948 mUserVersion = Integer.parseInt(versionNumber);
949 }
Amith Yamasani2a003292012-08-14 18:25:45 -0700950 }
951
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700952 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530953 if (type == XmlPullParser.START_TAG) {
954 final String name = parser.getName();
955 if (name.equals(TAG_USER)) {
956 String id = parser.getAttributeValue(null, ATTR_ID);
957 UserInfo user = readUserLocked(Integer.parseInt(id));
Amith Yamasani6f34b412012-10-22 18:19:27 -0700958
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530959 if (user != null) {
960 mUsers.put(user.id, user);
961 if (mNextSerialNumber < 0 || mNextSerialNumber <= user.id) {
962 mNextSerialNumber = user.id + 1;
963 }
Amith Yamasani2a003292012-08-14 18:25:45 -0700964 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530965 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -0800966 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
967 && type != XmlPullParser.END_TAG) {
968 if (type == XmlPullParser.START_TAG) {
969 if (parser.getName().equals(TAG_RESTRICTIONS)) {
Makoto Onukia4f11972015-10-01 13:19:58 -0700970 UserRestrictionsUtils
971 .readRestrictions(parser, mGuestRestrictions);
Amith Yamasanida0b1682014-11-21 12:58:17 -0800972 }
973 break;
974 }
975 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700976 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700977 }
978 }
Amith Yamasani13593602012-03-22 16:16:17 -0700979 updateUserIdsLocked();
Amith Yamasani350962c2013-08-06 11:18:53 -0700980 upgradeIfNecessaryLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700981 } catch (IOException ioe) {
Amith Yamasani13593602012-03-22 16:16:17 -0700982 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700983 } catch (XmlPullParserException pe) {
Amith Yamasani13593602012-03-22 16:16:17 -0700984 fallbackToSingleUserLocked();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -0800985 } finally {
986 if (fis != null) {
987 try {
988 fis.close();
989 } catch (IOException e) {
990 }
991 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700992 }
993 }
994
Amith Yamasani6f34b412012-10-22 18:19:27 -0700995 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -0800996 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -0700997 */
Amith Yamasani350962c2013-08-06 11:18:53 -0700998 private void upgradeIfNecessaryLocked() {
Amith Yamasani6f34b412012-10-22 18:19:27 -0700999 int userVersion = mUserVersion;
1000 if (userVersion < 1) {
1001 // Assign a proper name for the owner, if not initialized correctly before
Xiaohui Chen47f07952015-10-02 14:40:27 -07001002 UserInfo user = mUsers.get(UserHandle.USER_SYSTEM);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001003 if ("Primary".equals(user.name)) {
1004 user.name = mContext.getResources().getString(com.android.internal.R.string.owner_name);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001005 scheduleWriteUserLocked(user);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001006 }
1007 userVersion = 1;
1008 }
1009
Amith Yamasanibc9625052012-11-15 14:39:18 -08001010 if (userVersion < 2) {
1011 // Owner should be marked as initialized
Xiaohui Chen47f07952015-10-02 14:40:27 -07001012 UserInfo user = mUsers.get(UserHandle.USER_SYSTEM);
Amith Yamasanibc9625052012-11-15 14:39:18 -08001013 if ((user.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1014 user.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001015 scheduleWriteUserLocked(user);
Amith Yamasanibc9625052012-11-15 14:39:18 -08001016 }
1017 userVersion = 2;
1018 }
1019
Amith Yamasani350962c2013-08-06 11:18:53 -07001020
Amith Yamasani5e486f52013-08-07 11:06:44 -07001021 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -07001022 userVersion = 4;
1023 }
1024
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001025 if (userVersion < 5) {
1026 initDefaultGuestRestrictions();
1027 userVersion = 5;
1028 }
1029
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001030 if (userVersion < 6) {
1031 final boolean splitSystemUser = UserManager.isSplitSystemUser();
1032 for (int i = 0; i < mUsers.size(); i++) {
1033 UserInfo user = mUsers.valueAt(i);
1034 // In non-split mode, only user 0 can have restricted profiles
1035 if (!splitSystemUser && user.isRestricted()
1036 && (user.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID)) {
1037 user.restrictedProfileParentId = UserHandle.USER_SYSTEM;
1038 scheduleWriteUserLocked(user);
1039 }
1040 }
1041 userVersion = 6;
1042 }
1043
Amith Yamasani6f34b412012-10-22 18:19:27 -07001044 if (userVersion < USER_VERSION) {
1045 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
1046 + USER_VERSION);
1047 } else {
1048 mUserVersion = userVersion;
1049 writeUserListLocked();
1050 }
1051 }
1052
Amith Yamasani13593602012-03-22 16:16:17 -07001053 private void fallbackToSingleUserLocked() {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001054 int flags = UserInfo.FLAG_INITIALIZED;
1055 // In split system user mode, the admin and primary flags are assigned to the first human
1056 // user.
1057 if (!UserManager.isSplitSystemUser()) {
1058 flags |= UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY;
1059 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001060 // Create the system user
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001061 UserInfo system = new UserInfo(UserHandle.USER_SYSTEM,
Amith Yamasani6f34b412012-10-22 18:19:27 -07001062 mContext.getResources().getString(com.android.internal.R.string.owner_name), null,
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001063 flags);
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001064 mUsers.put(system.id, system);
Amith Yamasani634cf312012-10-04 17:34:21 -07001065 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -04001066 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -08001067
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001068 Bundle restrictions = new Bundle();
Makoto Onuki068c54a2015-10-13 14:34:03 -07001069 synchronized (mRestrictionsLock) {
1070 mBaseUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions);
1071 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001072
Amith Yamasani13593602012-03-22 16:16:17 -07001073 updateUserIdsLocked();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001074 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001075
Amith Yamasani13593602012-03-22 16:16:17 -07001076 writeUserListLocked();
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001077 writeUserLocked(system);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001078 }
1079
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001080 private void scheduleWriteUserLocked(UserInfo userInfo) {
1081 if (!mHandler.hasMessages(WRITE_USER_MSG, userInfo)) {
1082 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, userInfo);
1083 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
1084 }
1085 }
1086
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001087 /*
1088 * Writes the user file in this format:
1089 *
1090 * <user flags="20039023" id="0">
1091 * <name>Primary</name>
1092 * </user>
1093 */
Amith Yamasani13593602012-03-22 16:16:17 -07001094 private void writeUserLocked(UserInfo userInfo) {
Amith Yamasani742a6712011-05-04 14:49:28 -07001095 FileOutputStream fos = null;
Amith Yamasanifc95e702013-09-26 13:20:17 -07001096 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userInfo.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001097 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001098 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001099 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1100
1101 // XmlSerializer serializer = XmlUtils.serializerInstance();
1102 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001103 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001104 serializer.startDocument(null, true);
1105 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1106
1107 serializer.startTag(null, TAG_USER);
1108 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
Amith Yamasani2a003292012-08-14 18:25:45 -07001109 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001110 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Amith Yamasani920ace02012-09-20 22:15:37 -07001111 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
1112 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
1113 Long.toString(userInfo.lastLoggedInTime));
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001114 if (userInfo.iconPath != null) {
1115 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
1116 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001117 if (userInfo.partial) {
1118 serializer.attribute(null, ATTR_PARTIAL, "true");
1119 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001120 if (userInfo.guestToRemove) {
1121 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
1122 }
Kenny Guy2a764942014-04-02 13:29:20 +01001123 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
1124 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
1125 Integer.toString(userInfo.profileGroupId));
Kenny Guya52dc3e2014-02-11 15:33:14 +00001126 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001127 if (userInfo.restrictedProfileParentId != UserInfo.NO_PROFILE_GROUP_ID) {
1128 serializer.attribute(null, ATTR_RESTRICTED_PROFILE_PARENT_ID,
1129 Integer.toString(userInfo.restrictedProfileParentId));
1130 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001131 serializer.startTag(null, TAG_NAME);
1132 serializer.text(userInfo.name);
1133 serializer.endTag(null, TAG_NAME);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001134 Bundle restrictions;
1135 synchronized (mRestrictionsLock) {
1136 restrictions = mBaseUserRestrictions.get(userInfo.id);
1137 }
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001138 if (restrictions != null) {
Makoto Onuki068c54a2015-10-13 14:34:03 -07001139 UserRestrictionsUtils
1140 .writeRestrictions(serializer, restrictions, TAG_RESTRICTIONS);
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001141 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001142 serializer.endTag(null, TAG_USER);
1143
1144 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001145 userFile.finishWrite(fos);
1146 } catch (Exception ioe) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001147 Slog.e(LOG_TAG, "Error writing user info " + userInfo.id + "\n" + ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -07001148 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001149 }
1150 }
1151
1152 /*
1153 * Writes the user list file in this format:
1154 *
Amith Yamasani2a003292012-08-14 18:25:45 -07001155 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001156 * <user id="0"></user>
1157 * <user id="2"></user>
1158 * </users>
1159 */
Amith Yamasani13593602012-03-22 16:16:17 -07001160 private void writeUserListLocked() {
Amith Yamasani742a6712011-05-04 14:49:28 -07001161 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001162 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001163 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001164 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001165 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1166
1167 // XmlSerializer serializer = XmlUtils.serializerInstance();
1168 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001169 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001170 serializer.startDocument(null, true);
1171 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1172
1173 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -07001174 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -07001175 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001176
Adam Lesinskieddeb492014-09-08 17:50:03 -07001177 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Makoto Onukia4f11972015-10-01 13:19:58 -07001178 UserRestrictionsUtils
1179 .writeRestrictions(serializer, mGuestRestrictions, TAG_RESTRICTIONS);
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301180 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Amith Yamasani515d4062015-09-28 11:30:06 -07001181 final int userSize = mUsers.size();
1182 for (int i = 0; i < userSize; i++) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001183 UserInfo user = mUsers.valueAt(i);
1184 serializer.startTag(null, TAG_USER);
1185 serializer.attribute(null, ATTR_ID, Integer.toString(user.id));
1186 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001187 }
1188
1189 serializer.endTag(null, TAG_USERS);
1190
1191 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001192 userListFile.finishWrite(fos);
1193 } catch (Exception e) {
1194 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -07001195 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001196 }
1197 }
1198
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001199 private UserInfo readUserLocked(int id) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001200 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -07001201 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001202 String name = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001203 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -07001204 long creationTime = 0L;
1205 long lastLoggedInTime = 0L;
Kenny Guy2a764942014-04-02 13:29:20 +01001206 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001207 int restrictedProfileParentId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001208 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001209 boolean guestToRemove = false;
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001210 Bundle restrictions = new Bundle();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001211
1212 FileInputStream fis = null;
1213 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001214 AtomicFile userFile =
Amith Yamasanifc95e702013-09-26 13:20:17 -07001215 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
Amith Yamasani2a003292012-08-14 18:25:45 -07001216 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001217 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001218 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001219 int type;
1220 while ((type = parser.next()) != XmlPullParser.START_TAG
1221 && type != XmlPullParser.END_DOCUMENT) {
1222 ;
1223 }
1224
1225 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001226 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001227 return null;
1228 }
1229
1230 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001231 int storedId = readIntAttribute(parser, ATTR_ID, -1);
1232 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001233 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001234 return null;
1235 }
Amith Yamasani920ace02012-09-20 22:15:37 -07001236 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
1237 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001238 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -07001239 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
1240 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Kenny Guy2a764942014-04-02 13:29:20 +01001241 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
1242 UserInfo.NO_PROFILE_GROUP_ID);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001243 restrictedProfileParentId = readIntAttribute(parser,
1244 ATTR_RESTRICTED_PROFILE_PARENT_ID, UserInfo.NO_PROFILE_GROUP_ID);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001245 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
1246 if ("true".equals(valueString)) {
1247 partial = true;
1248 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001249 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
1250 if ("true".equals(valueString)) {
1251 guestToRemove = true;
1252 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001253
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001254 int outerDepth = parser.getDepth();
1255 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1256 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1257 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1258 continue;
1259 }
1260 String tag = parser.getName();
1261 if (TAG_NAME.equals(tag)) {
1262 type = parser.next();
1263 if (type == XmlPullParser.TEXT) {
1264 name = parser.getText();
1265 }
1266 } else if (TAG_RESTRICTIONS.equals(tag)) {
Makoto Onukia4f11972015-10-01 13:19:58 -07001267 UserRestrictionsUtils.readRestrictions(parser, restrictions);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001268 }
1269 }
1270 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001271
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001272 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -07001273 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -07001274 userInfo.creationTime = creationTime;
1275 userInfo.lastLoggedInTime = lastLoggedInTime;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001276 userInfo.partial = partial;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001277 userInfo.guestToRemove = guestToRemove;
Kenny Guy2a764942014-04-02 13:29:20 +01001278 userInfo.profileGroupId = profileGroupId;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001279 userInfo.restrictedProfileParentId = restrictedProfileParentId;
Makoto Onuki068c54a2015-10-13 14:34:03 -07001280 synchronized (mRestrictionsLock) {
1281 mBaseUserRestrictions.append(id, restrictions);
1282 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001283 return userInfo;
1284
1285 } catch (IOException ioe) {
1286 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001287 } finally {
1288 if (fis != null) {
1289 try {
1290 fis.close();
1291 } catch (IOException e) {
1292 }
1293 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001294 }
1295 return null;
1296 }
1297
Amith Yamasani920ace02012-09-20 22:15:37 -07001298 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
1299 String valueString = parser.getAttributeValue(null, attr);
1300 if (valueString == null) return defaultValue;
1301 try {
1302 return Integer.parseInt(valueString);
1303 } catch (NumberFormatException nfe) {
1304 return defaultValue;
1305 }
1306 }
1307
1308 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
1309 String valueString = parser.getAttributeValue(null, attr);
1310 if (valueString == null) return defaultValue;
1311 try {
1312 return Long.parseLong(valueString);
1313 } catch (NumberFormatException nfe) {
1314 return defaultValue;
1315 }
1316 }
1317
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001318 private boolean isPackageInstalled(String pkg, int userId) {
1319 final ApplicationInfo info = mPm.getApplicationInfo(pkg,
1320 PackageManager.GET_UNINSTALLED_PACKAGES,
1321 userId);
1322 if (info == null || (info.flags&ApplicationInfo.FLAG_INSTALLED) == 0) {
1323 return false;
1324 }
1325 return true;
1326 }
1327
Amith Yamasanib82add22013-07-09 11:24:44 -07001328 /**
Kenny Guyd21b2182014-07-17 16:38:55 +01001329 * Removes all the restrictions files (res_<packagename>) for a given user.
Amith Yamasanib82add22013-07-09 11:24:44 -07001330 * Does not do any permissions checking.
1331 */
Kenny Guyd21b2182014-07-17 16:38:55 +01001332 private void cleanAppRestrictions(int userId) {
Amith Yamasanib82add22013-07-09 11:24:44 -07001333 synchronized (mPackagesLock) {
1334 File dir = Environment.getUserSystemDirectory(userId);
1335 String[] files = dir.list();
1336 if (files == null) return;
1337 for (String fileName : files) {
1338 if (fileName.startsWith(RESTRICTIONS_FILE_PREFIX)) {
1339 File resFile = new File(dir, fileName);
1340 if (resFile.exists()) {
Kenny Guyd21b2182014-07-17 16:38:55 +01001341 resFile.delete();
Amith Yamasanib82add22013-07-09 11:24:44 -07001342 }
1343 }
1344 }
1345 }
1346 }
1347
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001348 /**
1349 * Removes the app restrictions file for a specific package and user id, if it exists.
1350 */
1351 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
1352 synchronized (mPackagesLock) {
1353 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07001354 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001355 if (resFile.exists()) {
1356 resFile.delete();
1357 }
1358 }
1359 }
1360
Kenny Guya52dc3e2014-02-11 15:33:14 +00001361 @Override
Kenny Guy2a764942014-04-02 13:29:20 +01001362 public UserInfo createProfileForUser(String name, int flags, int userId) {
Kenny Guya52dc3e2014-02-11 15:33:14 +00001363 checkManageUsersPermission("Only the system can create users");
Kenny Guy2a764942014-04-02 13:29:20 +01001364 return createUserInternal(name, flags, userId);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001365 }
1366
Amith Yamasani258848d2012-08-10 17:06:33 -07001367 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07001368 public UserInfo createUser(String name, int flags) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001369 checkManageUsersPermission("Only the system can create users");
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001370 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001371 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001372
Jessica Hummelbe81c802014-04-22 15:49:22 +01001373 private UserInfo createUserInternal(String name, int flags, int parentId) {
Julia Reynolds75175022014-06-26 16:35:00 -04001374 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1375 UserManager.DISALLOW_ADD_USER, false)) {
1376 Log.w(LOG_TAG, "Cannot add user. DISALLOW_ADD_USER is enabled.");
1377 return null;
1378 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001379 if (ActivityManager.isLowRamDeviceStatic()) {
1380 return null;
1381 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07001382 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001383 final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001384 final boolean isRestricted = (flags & UserInfo.FLAG_RESTRICTED) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001385 final long ident = Binder.clearCallingIdentity();
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001386 UserInfo userInfo = null;
Amith Yamasanibb054c92015-07-09 14:16:27 -07001387 final int userId;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001388 try {
1389 synchronized (mInstallLock) {
1390 synchronized (mPackagesLock) {
Jessica Hummelbe81c802014-04-22 15:49:22 +01001391 UserInfo parent = null;
1392 if (parentId != UserHandle.USER_NULL) {
1393 parent = getUserInfoLocked(parentId);
1394 if (parent == null) return null;
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001395 }
Nicolas Prevotb8186812015-08-06 15:00:03 +01001396 if (isManagedProfile && !canAddMoreManagedProfiles(parentId)) {
1397 Log.e(LOG_TAG, "Cannot add more managed profiles for user " + parentId);
Nicolas Prevot12678a92015-05-13 12:15:03 -07001398 return null;
1399 }
1400 if (!isGuest && !isManagedProfile && isUserLimitReachedLocked()) {
1401 // If we're not adding a guest user or a managed profile and the limit has
1402 // been reached, cannot add a user.
Amith Yamasani95ab7842014-08-11 17:09:26 -07001403 return null;
1404 }
1405 // If we're adding a guest and there already exists one, bail.
Adam Lesinskieddeb492014-09-08 17:50:03 -07001406 if (isGuest && findCurrentGuestUserLocked() != null) {
Amith Yamasani95ab7842014-08-11 17:09:26 -07001407 return null;
1408 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001409 // In legacy mode, restricted profile's parent can only be the owner user
1410 if (isRestricted && !UserManager.isSplitSystemUser()
1411 && (parentId != UserHandle.USER_SYSTEM)) {
1412 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
1413 return null;
1414 }
1415 if (isRestricted && UserManager.isSplitSystemUser()) {
1416 if (parent == null) {
1417 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be "
1418 + "specified");
1419 return null;
1420 }
1421 if (!parent.canHaveProfile()) {
1422 Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be "
1423 + "created for the specified parent user id " + parentId);
1424 return null;
1425 }
1426 }
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001427 // In split system user mode, we assign the first human user the primary flag.
Xiaohui Chen203243a2015-07-16 11:55:47 -07001428 // And if there is no device owner, we also assign the admin flag to primary
1429 // user.
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001430 if (UserManager.isSplitSystemUser()
Xiaohui Chen203243a2015-07-16 11:55:47 -07001431 && !isGuest && !isManagedProfile && getPrimaryUser() == null) {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001432 flags |= UserInfo.FLAG_PRIMARY;
Xiaohui Chen203243a2015-07-16 11:55:47 -07001433 DevicePolicyManager devicePolicyManager = (DevicePolicyManager)
1434 mContext.getSystemService(Context.DEVICE_POLICY_SERVICE);
1435 if (devicePolicyManager == null
1436 || devicePolicyManager.getDeviceOwner() == null) {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001437 flags |= UserInfo.FLAG_ADMIN;
1438 }
1439 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07001440 userId = getNextAvailableIdLocked();
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001441 userInfo = new UserInfo(userId, name, null, flags);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001442 userInfo.serialNumber = mNextSerialNumber++;
Amith Yamasani920ace02012-09-20 22:15:37 -07001443 long now = System.currentTimeMillis();
1444 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001445 userInfo.partial = true;
Amith Yamasani16389312012-10-17 21:20:14 -07001446 Environment.getUserSystemDirectory(userInfo.id).mkdirs();
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001447 mUsers.put(userId, userInfo);
1448 writeUserListLocked();
Jessica Hummelbe81c802014-04-22 15:49:22 +01001449 if (parent != null) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001450 if (isManagedProfile) {
1451 if (parent.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
1452 parent.profileGroupId = parent.id;
1453 scheduleWriteUserLocked(parent);
1454 }
1455 userInfo.profileGroupId = parent.profileGroupId;
1456 } else if (isRestricted) {
1457 if (!parent.canHaveProfile()) {
1458 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
1459 }
1460 if (parent.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) {
1461 parent.restrictedProfileParentId = parent.id;
1462 scheduleWriteUserLocked(parent);
1463 }
1464 userInfo.restrictedProfileParentId = parent.restrictedProfileParentId;
Kenny Guya52dc3e2014-02-11 15:33:14 +00001465 }
Kenny Guya52dc3e2014-02-11 15:33:14 +00001466 }
Jeff Sharkey6dce4962015-07-03 18:08:41 -07001467 final StorageManager storage = mContext.getSystemService(StorageManager.class);
1468 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
1469 final String volumeUuid = vol.getFsUuid();
1470 try {
1471 final File userDir = Environment.getDataUserDirectory(volumeUuid,
1472 userId);
Jeff Sharkey3bb8c852015-07-06 16:44:23 -07001473 prepareUserDirectory(mContext, volumeUuid, userId);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07001474 enforceSerialNumber(userDir, userInfo.serialNumber);
1475 } catch (IOException e) {
1476 Log.wtf(LOG_TAG, "Failed to create user directory on " + volumeUuid, e);
1477 }
1478 }
1479 mPm.createNewUserLILPw(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001480 userInfo.partial = false;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001481 scheduleWriteUserLocked(userInfo);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001482 updateUserIdsLocked();
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001483 Bundle restrictions = new Bundle();
Makoto Onuki068c54a2015-10-13 14:34:03 -07001484 synchronized (mRestrictionsLock) {
1485 mBaseUserRestrictions.append(userId, restrictions);
1486 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001487 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07001488 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07001489 mPm.newUserCreated(userId);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001490 if (userInfo != null) {
1491 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
1492 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userInfo.id);
1493 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
1494 android.Manifest.permission.MANAGE_USERS);
1495 }
1496 } finally {
1497 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07001498 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001499 return userInfo;
1500 }
1501
Amith Yamasani0b285492011-04-14 17:35:23 -07001502 /**
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07001503 * @hide
1504 */
1505 public UserInfo createRestrictedProfile(String name, int parentUserId) {
1506 checkManageUsersPermission("setupRestrictedProfile");
1507 final UserInfo user = createProfileForUser(name, UserInfo.FLAG_RESTRICTED, parentUserId);
1508 if (user == null) {
1509 return null;
1510 }
1511 setUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, true, user.id);
1512 // Change the setting before applying the DISALLOW_SHARE_LOCATION restriction, otherwise
1513 // the putIntForUser() will fail.
1514 android.provider.Settings.Secure.putIntForUser(mContext.getContentResolver(),
1515 android.provider.Settings.Secure.LOCATION_MODE,
1516 android.provider.Settings.Secure.LOCATION_MODE_OFF, user.id);
1517 setUserRestriction(UserManager.DISALLOW_SHARE_LOCATION, true, user.id);
1518 return user;
1519 }
1520
1521 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07001522 * Find the current guest user. If the Guest user is partial,
1523 * then do not include it in the results as it is about to die.
Adam Lesinskieddeb492014-09-08 17:50:03 -07001524 */
1525 private UserInfo findCurrentGuestUserLocked() {
1526 final int size = mUsers.size();
1527 for (int i = 0; i < size; i++) {
1528 final UserInfo user = mUsers.valueAt(i);
1529 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
1530 return user;
1531 }
1532 }
1533 return null;
1534 }
1535
1536 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07001537 * Mark this guest user for deletion to allow us to create another guest
1538 * and switch to that user before actually removing this guest.
1539 * @param userHandle the userid of the current guest
1540 * @return whether the user could be marked for deletion
1541 */
1542 public boolean markGuestForDeletion(int userHandle) {
1543 checkManageUsersPermission("Only the system can remove users");
1544 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1545 UserManager.DISALLOW_REMOVE_USER, false)) {
1546 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1547 return false;
1548 }
1549
1550 long ident = Binder.clearCallingIdentity();
1551 try {
1552 final UserInfo user;
1553 synchronized (mPackagesLock) {
1554 user = mUsers.get(userHandle);
1555 if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
1556 return false;
1557 }
1558 if (!user.isGuest()) {
1559 return false;
1560 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001561 // We set this to a guest user that is to be removed. This is a temporary state
1562 // where we are allowed to add new Guest users, even if this one is still not
1563 // removed. This user will still show up in getUserInfo() calls.
1564 // If we don't get around to removing this Guest user, it will be purged on next
1565 // startup.
1566 user.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07001567 // Mark it as disabled, so that it isn't returned any more when
1568 // profiles are queried.
1569 user.flags |= UserInfo.FLAG_DISABLED;
Amith Yamasani1df14732014-08-29 21:37:27 -07001570 writeUserLocked(user);
1571 }
1572 } finally {
1573 Binder.restoreCallingIdentity(ident);
1574 }
1575 return true;
1576 }
1577
1578 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07001579 * Removes a user and all data directories created for that user. This method should be called
1580 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001581 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07001582 */
Amith Yamasani258848d2012-08-10 17:06:33 -07001583 public boolean removeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001584 checkManageUsersPermission("Only the system can remove users");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04001585 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1586 UserManager.DISALLOW_REMOVE_USER, false)) {
1587 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1588 return false;
1589 }
1590
Kenny Guyee58b4f2014-05-23 15:19:53 +01001591 long ident = Binder.clearCallingIdentity();
1592 try {
1593 final UserInfo user;
Fyodor Kupolov0df68cd2015-10-01 13:54:22 -07001594 int currentUser = ActivityManager.getCurrentUser();
1595 if (currentUser == userHandle) {
1596 Log.w(LOG_TAG, "Current user cannot be removed");
1597 return false;
1598 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01001599 synchronized (mPackagesLock) {
1600 user = mUsers.get(userHandle);
Kenny Guy17c9d692014-06-13 13:51:42 +01001601 if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01001602 return false;
1603 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08001604
1605 // We remember deleted user IDs to prevent them from being
1606 // reused during the current boot; they can still be reused
1607 // after a reboot.
Kenny Guyee58b4f2014-05-23 15:19:53 +01001608 mRemovingUserIds.put(userHandle, true);
Jeff Sharkey6eb09392014-11-14 15:57:59 -08001609
Kenny Guyee58b4f2014-05-23 15:19:53 +01001610 try {
1611 mAppOpsService.removeUser(userHandle);
1612 } catch (RemoteException e) {
1613 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
1614 }
1615 // Set this to a partially created user, so that the user will be purged
1616 // on next startup, in case the runtime stops now before stopping and
1617 // removing the user completely.
1618 user.partial = true;
1619 // Mark it as disabled, so that it isn't returned any more when
1620 // profiles are queried.
1621 user.flags |= UserInfo.FLAG_DISABLED;
1622 writeUserLocked(user);
1623 }
1624
1625 if (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
1626 && user.isManagedProfile()) {
1627 // Send broadcast to notify system that the user removed was a
1628 // managed user.
1629 sendProfileRemovedBroadcast(user.profileGroupId, user.id);
1630 }
1631
1632 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
1633 int res;
1634 try {
1635 res = ActivityManagerNative.getDefault().stopUser(userHandle,
1636 new IStopUserCallback.Stub() {
1637 @Override
1638 public void userStopped(int userId) {
1639 finishRemoveUser(userId);
1640 }
1641 @Override
1642 public void userStopAborted(int userId) {
1643 }
1644 });
1645 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001646 return false;
1647 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01001648 return res == ActivityManager.USER_OP_SUCCESS;
1649 } finally {
1650 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001651 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001652 }
1653
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001654 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07001655 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001656 // Let other services shutdown any activity and clean up their state before completely
1657 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001658 long ident = Binder.clearCallingIdentity();
1659 try {
1660 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
1661 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001662 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
1663 android.Manifest.permission.MANAGE_USERS,
1664
1665 new BroadcastReceiver() {
1666 @Override
1667 public void onReceive(Context context, Intent intent) {
1668 if (DBG) {
1669 Slog.i(LOG_TAG,
1670 "USER_REMOVED broadcast sent, cleaning up user data "
1671 + userHandle);
1672 }
1673 new Thread() {
1674 public void run() {
Amith Yamasani515d4062015-09-28 11:30:06 -07001675 // Clean up any ActivityManager state
1676 LocalServices.getService(ActivityManagerInternal.class)
1677 .onUserRemoved(userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001678 synchronized (mInstallLock) {
1679 synchronized (mPackagesLock) {
1680 removeUserStateLocked(userHandle);
1681 }
1682 }
1683 }
1684 }.start();
1685 }
1686 },
1687
1688 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001689 } finally {
1690 Binder.restoreCallingIdentity(ident);
1691 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001692 }
1693
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001694 private void removeUserStateLocked(final int userHandle) {
Paul Crowley85e4e812015-05-19 12:42:00 +01001695 mContext.getSystemService(StorageManager.class)
1696 .deleteUserKey(userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001697 // Cleanup package manager settings
Amith Yamasanidda003f2014-08-28 18:06:51 -07001698 mPm.cleanUpUserLILPw(this, userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001699
1700 // Remove this user from the list
1701 mUsers.remove(userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001702 // Remove user file
Amith Yamasanifc95e702013-09-26 13:20:17 -07001703 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001704 userFile.delete();
1705 // Update the user list
1706 writeUserListLocked();
1707 updateUserIdsLocked();
1708 removeDirectoryRecursive(Environment.getUserSystemDirectory(userHandle));
1709 }
1710
Amith Yamasani61f57372012-08-31 12:12:28 -07001711 private void removeDirectoryRecursive(File parent) {
1712 if (parent.isDirectory()) {
1713 String[] files = parent.list();
1714 for (String filename : files) {
1715 File child = new File(parent, filename);
1716 removeDirectoryRecursive(child);
1717 }
1718 }
1719 parent.delete();
1720 }
1721
Kenny Guyf8d3a232014-05-15 16:09:52 +01001722 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01001723 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01001724 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
1725 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01001726 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
1727 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01001728 }
1729
Amith Yamasani2a003292012-08-14 18:25:45 -07001730 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001731 public Bundle getApplicationRestrictions(String packageName) {
1732 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
1733 }
1734
1735 @Override
1736 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001737 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07001738 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Esteban Talavera2a5d6c62015-10-21 10:55:56 +01001739 checkManageUsersPermission("get application restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001740 }
1741 synchronized (mPackagesLock) {
1742 // Read the restrictions from XML
1743 return readApplicationRestrictionsLocked(packageName, userId);
1744 }
1745 }
1746
1747 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001748 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001749 int userId) {
Esteban Talavera2a5d6c62015-10-21 10:55:56 +01001750 checkManageUsersPermission("set application restrictions");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001751 synchronized (mPackagesLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01001752 if (restrictions == null || restrictions.isEmpty()) {
1753 cleanAppRestrictionsForPackage(packageName, userId);
1754 } else {
1755 // Write the restrictions to XML
1756 writeApplicationRestrictionsLocked(packageName, restrictions, userId);
1757 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001758 }
Robin Lee66e5d962014-04-09 16:44:21 +01001759
Kenny Guyd21b2182014-07-17 16:38:55 +01001760 if (isPackageInstalled(packageName, userId)) {
1761 // Notify package of changes via an intent - only sent to explicitly registered receivers.
1762 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
1763 changeIntent.setPackage(packageName);
1764 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
1765 mContext.sendBroadcastAsUser(changeIntent, new UserHandle(userId));
1766 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001767 }
1768
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001769 private void unhideAllInstalledAppsForUser(final int userHandle) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001770 mHandler.post(new Runnable() {
1771 @Override
1772 public void run() {
1773 List<ApplicationInfo> apps =
1774 mPm.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES,
1775 userHandle).getList();
1776 final long ident = Binder.clearCallingIdentity();
1777 try {
1778 for (ApplicationInfo appInfo : apps) {
1779 if ((appInfo.flags & ApplicationInfo.FLAG_INSTALLED) != 0
Alex Klyubinb9f8a522015-02-03 11:12:59 -08001780 && (appInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HIDDEN)
1781 != 0) {
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001782 mPm.setApplicationHiddenSettingAsUser(appInfo.packageName, false,
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001783 userHandle);
1784 }
1785 }
1786 } finally {
1787 Binder.restoreCallingIdentity(ident);
1788 }
1789 }
1790 });
1791 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001792 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07001793 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001794 try {
1795 return mContext.getPackageManager().getApplicationInfo(packageName,
1796 PackageManager.GET_UNINSTALLED_PACKAGES).uid;
1797 } catch (NameNotFoundException nnfe) {
1798 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07001799 } finally {
1800 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001801 }
1802 }
1803
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001804 private Bundle readApplicationRestrictionsLocked(String packageName,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001805 int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001806 AtomicFile restrictionsFile =
1807 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
1808 packageToRestrictionsFileName(packageName)));
1809 return readApplicationRestrictionsLocked(restrictionsFile);
1810 }
1811
1812 @VisibleForTesting
1813 static Bundle readApplicationRestrictionsLocked(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001814 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001815 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07001816 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07001817 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07001818 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001819
1820 FileInputStream fis = null;
1821 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001822 fis = restrictionsFile.openRead();
1823 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001824 parser.setInput(fis, StandardCharsets.UTF_8.name());
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001825 XmlUtils.nextElement(parser);
1826 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001827 Slog.e(LOG_TAG, "Unable to read restrictions file "
1828 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001829 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001830 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001831 while (parser.next() != XmlPullParser.END_DOCUMENT) {
1832 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001833 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001834 } catch (IOException|XmlPullParserException e) {
1835 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001836 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001837 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001838 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001839 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001840 }
1841
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001842 private static void readEntry(Bundle restrictions, ArrayList<String> values,
1843 XmlPullParser parser) throws XmlPullParserException, IOException {
1844 int type = parser.getEventType();
1845 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
1846 String key = parser.getAttributeValue(null, ATTR_KEY);
1847 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
1848 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
1849 if (multiple != null) {
1850 values.clear();
1851 int count = Integer.parseInt(multiple);
1852 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1853 if (type == XmlPullParser.START_TAG
1854 && parser.getName().equals(TAG_VALUE)) {
1855 values.add(parser.nextText().trim());
1856 count--;
1857 }
1858 }
1859 String [] valueStrings = new String[values.size()];
1860 values.toArray(valueStrings);
1861 restrictions.putStringArray(key, valueStrings);
1862 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
1863 restrictions.putBundle(key, readBundleEntry(parser, values));
1864 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
1865 final int outerDepth = parser.getDepth();
1866 ArrayList<Bundle> bundleList = new ArrayList<>();
1867 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
1868 Bundle childBundle = readBundleEntry(parser, values);
1869 bundleList.add(childBundle);
1870 }
1871 restrictions.putParcelableArray(key,
1872 bundleList.toArray(new Bundle[bundleList.size()]));
1873 } else {
1874 String value = parser.nextText().trim();
1875 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
1876 restrictions.putBoolean(key, Boolean.parseBoolean(value));
1877 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
1878 restrictions.putInt(key, Integer.parseInt(value));
1879 } else {
1880 restrictions.putString(key, value);
1881 }
1882 }
1883 }
1884 }
1885
1886 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
1887 throws IOException, XmlPullParserException {
1888 Bundle childBundle = new Bundle();
1889 final int outerDepth = parser.getDepth();
1890 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
1891 readEntry(childBundle, values, parser);
1892 }
1893 return childBundle;
1894 }
1895
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001896 private void writeApplicationRestrictionsLocked(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001897 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001898 AtomicFile restrictionsFile = new AtomicFile(
1899 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07001900 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001901 writeApplicationRestrictionsLocked(restrictions, restrictionsFile);
1902 }
1903
1904 @VisibleForTesting
1905 static void writeApplicationRestrictionsLocked(Bundle restrictions,
1906 AtomicFile restrictionsFile) {
1907 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001908 try {
1909 fos = restrictionsFile.startWrite();
1910 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1911
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001912 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001913 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001914 serializer.startDocument(null, true);
1915 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1916
1917 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001918 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001919 serializer.endTag(null, TAG_RESTRICTIONS);
1920
1921 serializer.endDocument();
1922 restrictionsFile.finishWrite(fos);
1923 } catch (Exception e) {
1924 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001925 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
1926 }
1927 }
1928
1929 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
1930 throws IOException {
1931 for (String key : restrictions.keySet()) {
1932 Object value = restrictions.get(key);
1933 serializer.startTag(null, TAG_ENTRY);
1934 serializer.attribute(null, ATTR_KEY, key);
1935
1936 if (value instanceof Boolean) {
1937 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
1938 serializer.text(value.toString());
1939 } else if (value instanceof Integer) {
1940 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
1941 serializer.text(value.toString());
1942 } else if (value == null || value instanceof String) {
1943 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
1944 serializer.text(value != null ? (String) value : "");
1945 } else if (value instanceof Bundle) {
1946 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
1947 writeBundle((Bundle) value, serializer);
1948 } else if (value instanceof Parcelable[]) {
1949 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
1950 Parcelable[] array = (Parcelable[]) value;
1951 for (Parcelable parcelable : array) {
1952 if (!(parcelable instanceof Bundle)) {
1953 throw new IllegalArgumentException("bundle-array can only hold Bundles");
1954 }
1955 serializer.startTag(null, TAG_ENTRY);
1956 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
1957 writeBundle((Bundle) parcelable, serializer);
1958 serializer.endTag(null, TAG_ENTRY);
1959 }
1960 } else {
1961 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
1962 String[] values = (String[]) value;
1963 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
1964 for (String choice : values) {
1965 serializer.startTag(null, TAG_VALUE);
1966 serializer.text(choice != null ? choice : "");
1967 serializer.endTag(null, TAG_VALUE);
1968 }
1969 }
1970 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001971 }
1972 }
1973
1974 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07001975 public int getUserSerialNumber(int userHandle) {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001976 synchronized (mPackagesLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001977 if (!exists(userHandle)) return -1;
Amith Yamasani195263742012-08-21 15:40:12 -07001978 return getUserInfoLocked(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07001979 }
1980 }
1981
1982 @Override
1983 public int getUserHandle(int userSerialNumber) {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001984 synchronized (mPackagesLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001985 for (int userId : mUserIds) {
Kenny Guy945f8832015-02-10 15:17:26 +00001986 UserInfo info = getUserInfoLocked(userId);
1987 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07001988 }
1989 // Not found
1990 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07001991 }
1992 }
1993
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07001994 @Override
1995 public long getUserCreationTime(int userHandle) {
1996 int callingUserId = UserHandle.getCallingUserId();
1997 UserInfo userInfo = null;
1998 synchronized (mPackagesLock) {
1999 if (callingUserId == userHandle) {
2000 userInfo = getUserInfoLocked(userHandle);
2001 } else {
2002 UserInfo parent = getProfileParentLocked(userHandle);
2003 if (parent != null && parent.id == callingUserId) {
2004 userInfo = getUserInfoLocked(userHandle);
2005 }
2006 }
2007 }
2008 if (userInfo == null) {
2009 throw new SecurityException("userHandle can only be the calling user or a managed "
2010 + "profile associated with this user");
2011 }
2012 return userInfo.creationTime;
2013 }
2014
Amith Yamasani0b285492011-04-14 17:35:23 -07002015 /**
2016 * Caches the list of user ids in an array, adjusting the array size when necessary.
2017 */
Amith Yamasani13593602012-03-22 16:16:17 -07002018 private void updateUserIdsLocked() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002019 int num = 0;
Amith Yamasani515d4062015-09-28 11:30:06 -07002020 final int userSize = mUsers.size();
2021 for (int i = 0; i < userSize; i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002022 if (!mUsers.valueAt(i).partial) {
2023 num++;
2024 }
2025 }
Amith Yamasani16389312012-10-17 21:20:14 -07002026 final int[] newUsers = new int[num];
2027 int n = 0;
Amith Yamasani515d4062015-09-28 11:30:06 -07002028 for (int i = 0; i < userSize; i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002029 if (!mUsers.valueAt(i).partial) {
Amith Yamasani16389312012-10-17 21:20:14 -07002030 newUsers[n++] = mUsers.keyAt(i);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002031 }
Amith Yamasani0b285492011-04-14 17:35:23 -07002032 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07002033 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07002034 }
2035
2036 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002037 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasani920ace02012-09-20 22:15:37 -07002038 * @param userId the user that was just foregrounded
2039 */
Amith Yamasani06bf8242015-05-08 16:36:21 -07002040 public void onUserForeground(int userId) {
Amith Yamasani920ace02012-09-20 22:15:37 -07002041 synchronized (mPackagesLock) {
2042 UserInfo user = mUsers.get(userId);
2043 long now = System.currentTimeMillis();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002044 if (user == null || user.partial) {
2045 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
2046 return;
2047 }
2048 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani920ace02012-09-20 22:15:37 -07002049 user.lastLoggedInTime = now;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002050 scheduleWriteUserLocked(user);
Amith Yamasani920ace02012-09-20 22:15:37 -07002051 }
2052 }
2053 }
2054
2055 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002056 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani742a6712011-05-04 14:49:28 -07002057 * TODO: May not be a good idea to recycle ids, in case it results in confusion
2058 * for data and battery stats collection, or unexpected cross-talk.
Amith Yamasani0b285492011-04-14 17:35:23 -07002059 * @return
2060 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002061 private int getNextAvailableIdLocked() {
Dianne Hackborn4428e172012-08-24 17:43:05 -07002062 synchronized (mPackagesLock) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002063 int i = MIN_USER_ID;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002064 while (i < MAX_USER_ID) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002065 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002066 return i;
Amith Yamasani195263742012-08-21 15:40:12 -07002067 }
2068 i++;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002069 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002070 }
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002071 throw new IllegalStateException("No user id available!");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002072 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002073
Amith Yamasanifc95e702013-09-26 13:20:17 -07002074 private String packageToRestrictionsFileName(String packageName) {
2075 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
2076 }
2077
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002078 /**
2079 * Create new {@code /data/user/[id]} directory and sets default
2080 * permissions.
2081 */
Jeff Sharkey3bb8c852015-07-06 16:44:23 -07002082 public static void prepareUserDirectory(Context context, String volumeUuid, int userId) {
2083 final StorageManager storage = context.getSystemService(StorageManager.class);
2084 final File userDir = Environment.getDataUserDirectory(volumeUuid, userId);
2085 storage.createNewUserDir(userId, userDir);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002086 }
2087
2088 /**
2089 * Enforce that serial number stored in user directory inode matches the
2090 * given expected value. Gracefully sets the serial number if currently
2091 * undefined.
2092 *
2093 * @throws IOException when problem extracting serial number, or serial
2094 * number is mismatched.
2095 */
2096 public static void enforceSerialNumber(File file, int serialNumber) throws IOException {
2097 final int foundSerial = getSerialNumber(file);
2098 Slog.v(LOG_TAG, "Found " + file + " with serial number " + foundSerial);
2099
2100 if (foundSerial == -1) {
2101 Slog.d(LOG_TAG, "Serial number missing on " + file + "; assuming current is valid");
2102 try {
2103 setSerialNumber(file, serialNumber);
2104 } catch (IOException e) {
2105 Slog.w(LOG_TAG, "Failed to set serial number on " + file, e);
2106 }
2107
2108 } else if (foundSerial != serialNumber) {
2109 throw new IOException("Found serial number " + foundSerial
2110 + " doesn't match expected " + serialNumber);
2111 }
2112 }
2113
2114 /**
2115 * Set serial number stored in user directory inode.
2116 *
2117 * @throws IOException if serial number was already set
2118 */
2119 private static void setSerialNumber(File file, int serialNumber)
2120 throws IOException {
2121 try {
2122 final byte[] buf = Integer.toString(serialNumber).getBytes(StandardCharsets.UTF_8);
2123 Os.setxattr(file.getAbsolutePath(), XATTR_SERIAL, buf, OsConstants.XATTR_CREATE);
2124 } catch (ErrnoException e) {
2125 throw e.rethrowAsIOException();
2126 }
2127 }
2128
2129 /**
2130 * Return serial number stored in user directory inode.
2131 *
2132 * @return parsed serial number, or -1 if not set
2133 */
2134 private static int getSerialNumber(File file) throws IOException {
2135 try {
2136 final byte[] buf = new byte[256];
2137 final int len = Os.getxattr(file.getAbsolutePath(), XATTR_SERIAL, buf);
2138 final String serial = new String(buf, 0, len);
2139 try {
2140 return Integer.parseInt(serial);
2141 } catch (NumberFormatException e) {
2142 throw new IOException("Bad serial number: " + serial);
2143 }
2144 } catch (ErrnoException e) {
2145 if (e.errno == OsConstants.ENODATA) {
2146 return -1;
2147 } else {
2148 throw e.rethrowAsIOException();
2149 }
2150 }
2151 }
2152
Amith Yamasani920ace02012-09-20 22:15:37 -07002153 @Override
2154 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2155 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2156 != PackageManager.PERMISSION_GRANTED) {
2157 pw.println("Permission Denial: can't dump UserManager from from pid="
2158 + Binder.getCallingPid()
2159 + ", uid=" + Binder.getCallingUid()
2160 + " without permission "
2161 + android.Manifest.permission.DUMP);
2162 return;
2163 }
2164
2165 long now = System.currentTimeMillis();
2166 StringBuilder sb = new StringBuilder();
2167 synchronized (mPackagesLock) {
2168 pw.println("Users:");
2169 for (int i = 0; i < mUsers.size(); i++) {
2170 UserInfo user = mUsers.valueAt(i);
2171 if (user == null) continue;
Amith Yamasani634cf312012-10-04 17:34:21 -07002172 pw.print(" "); pw.print(user); pw.print(" serialNo="); pw.print(user.serialNumber);
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002173 if (mRemovingUserIds.get(mUsers.keyAt(i))) pw.print(" <removing> ");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002174 if (user.partial) pw.print(" <partial>");
2175 pw.println();
Amith Yamasani920ace02012-09-20 22:15:37 -07002176 pw.print(" Created: ");
2177 if (user.creationTime == 0) {
2178 pw.println("<unknown>");
2179 } else {
2180 sb.setLength(0);
2181 TimeUtils.formatDuration(now - user.creationTime, sb);
2182 sb.append(" ago");
2183 pw.println(sb);
2184 }
2185 pw.print(" Last logged in: ");
2186 if (user.lastLoggedInTime == 0) {
2187 pw.println("<unknown>");
2188 } else {
2189 sb.setLength(0);
2190 TimeUtils.formatDuration(now - user.lastLoggedInTime, sb);
2191 sb.append(" ago");
2192 pw.println(sb);
2193 }
Makoto Onukia4f11972015-10-01 13:19:58 -07002194 pw.println(" Restrictions:");
2195 UserRestrictionsUtils.dumpRestrictions(
Makoto Onuki068c54a2015-10-13 14:34:03 -07002196 pw, " ", mBaseUserRestrictions.get(user.id));
2197 pw.println(" Effective restrictions:");
2198 UserRestrictionsUtils.dumpRestrictions(
2199 pw, " ", mCachedEffectiveUserRestrictions.get(user.id));
Amith Yamasani920ace02012-09-20 22:15:37 -07002200 }
Makoto Onukia4f11972015-10-01 13:19:58 -07002201 pw.println();
2202 pw.println("Guest restrictions:");
2203 UserRestrictionsUtils.dumpRestrictions(pw, " ", mGuestRestrictions);
Amith Yamasani920ace02012-09-20 22:15:37 -07002204 }
2205 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002206
2207 final class MainHandler extends Handler {
2208
2209 @Override
2210 public void handleMessage(Message msg) {
2211 switch (msg.what) {
2212 case WRITE_USER_MSG:
2213 removeMessages(WRITE_USER_MSG, msg.obj);
2214 synchronized (mPackagesLock) {
2215 int userId = ((UserInfo) msg.obj).id;
2216 UserInfo userInfo = mUsers.get(userId);
2217 if (userInfo != null) {
2218 writeUserLocked(userInfo);
2219 }
2220 }
2221 }
2222 }
2223 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07002224
2225 /**
2226 * @param userId
2227 * @return whether the user has been initialized yet
2228 */
2229 boolean isInitialized(int userId) {
2230 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
2231 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07002232
2233 private class LocalService extends UserManagerInternal {
2234
2235 @Override
2236 public Object getUserRestrictionsLock() {
2237 return mRestrictionsLock;
2238 }
2239
2240 @Override
2241 @GuardedBy("mRestrictionsLock")
2242 public void updateEffectiveUserRestrictionsRL(int userId) {
2243 UserManagerService.this.updateEffectiveUserRestrictionsRL(userId);
2244 }
2245
2246 @Override
2247 @GuardedBy("mRestrictionsLock")
2248 public void updateEffectiveUserRestrictionsForAllUsersRL() {
2249 UserManagerService.this.updateEffectiveUserRestrictionsForAllUsersRL();
2250 }
2251
2252 @Override
2253 public Bundle getBaseUserRestrictions(int userId) {
2254 synchronized (mRestrictionsLock) {
2255 return mBaseUserRestrictions.get(userId);
2256 }
2257 }
2258
2259 @Override
2260 public void setBaseUserRestrictionsByDpmsForMigration(
2261 int userId, Bundle baseRestrictions) {
2262 synchronized (mRestrictionsLock) {
2263 mBaseUserRestrictions.put(userId, new Bundle(baseRestrictions));
2264 invalidateEffectiveUserRestrictionsRL(userId);
2265 }
2266
2267 synchronized (mPackagesLock) {
2268 final UserInfo userInfo = mUsers.get(userId);
2269 if (userInfo != null) {
2270 writeUserLocked(userInfo);
2271 } else {
2272 Slog.w(LOG_TAG, "UserInfo not found for " + userId);
2273 }
2274 }
2275 }
2276 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002277}