blob: e1883432039045a192bc623ee0d80dbc3661dd78 [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;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070048import android.os.UserHandle;
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070049import android.os.UserManager;
Makoto Onuki068c54a2015-10-13 14:34:03 -070050import android.os.UserManagerInternal;
Paul Crowley85e4e812015-05-19 12:42:00 +010051import android.os.storage.StorageManager;
Jeff Sharkey6dce4962015-07-03 18:08:41 -070052import android.os.storage.VolumeInfo;
53import android.system.ErrnoException;
54import android.system.Os;
55import android.system.OsConstants;
Amith Yamasani2a003292012-08-14 18:25:45 -070056import android.util.AtomicFile;
Amith Yamasani655d0e22013-06-12 14:19:10 -070057import android.util.Log;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070058import android.util.Slog;
59import android.util.SparseArray;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080060import android.util.SparseBooleanArray;
Amith Yamasani920ace02012-09-20 22:15:37 -070061import android.util.TimeUtils;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070062import android.util.Xml;
63
Makoto Onuki068c54a2015-10-13 14:34:03 -070064import com.android.internal.annotations.GuardedBy;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070065import com.android.internal.annotations.VisibleForTesting;
Jason Monk62062992014-05-06 09:55:28 -040066import com.android.internal.app.IAppOpsService;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080067import com.android.internal.util.FastXmlSerializer;
Makoto Onuki068c54a2015-10-13 14:34:03 -070068import com.android.internal.util.Preconditions;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070069import com.android.internal.util.XmlUtils;
Amith Yamasani515d4062015-09-28 11:30:06 -070070import com.android.server.LocalServices;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080071
72import org.xmlpull.v1.XmlPullParser;
73import org.xmlpull.v1.XmlPullParserException;
74import org.xmlpull.v1.XmlSerializer;
75
Amith Yamasani4b2e9342011-03-31 12:38:53 -070076import java.io.BufferedOutputStream;
77import java.io.File;
Amith Yamasani920ace02012-09-20 22:15:37 -070078import java.io.FileDescriptor;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070079import java.io.FileInputStream;
Amith Yamasanib8151ec2012-04-18 18:02:48 -070080import java.io.FileNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070081import java.io.FileOutputStream;
82import java.io.IOException;
Amith Yamasani920ace02012-09-20 22:15:37 -070083import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +010084import java.nio.charset.StandardCharsets;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070085import java.util.ArrayList;
86import java.util.List;
87
Fyodor Kupolov262f9952015-03-23 18:55:11 -070088import libcore.io.IoUtils;
89
Makoto Onuki068c54a2015-10-13 14:34:03 -070090/**
91 * Service for {@link UserManager}.
92 *
93 * Method naming convention:
94 * - Methods suffixed with "Locked" should be called within the {@code this} lock.
95 * - Methods suffixed with "RL" should be called within the {@link #mRestrictionsLock} lock.
96 */
Amith Yamasani258848d2012-08-10 17:06:33 -070097public class UserManagerService extends IUserManager.Stub {
Amith Yamasanib8151ec2012-04-18 18:02:48 -070098
Amith Yamasani2a003292012-08-14 18:25:45 -070099 private static final String LOG_TAG = "UserManagerService";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700100
Makoto Onuki068c54a2015-10-13 14:34:03 -0700101 private static final boolean DBG = false; // DO NOT SUBMIT WITH TRUE
Amith Yamasani16389312012-10-17 21:20:14 -0700102
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700103 private static final String TAG_NAME = "name";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700104 private static final String ATTR_FLAGS = "flags";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700105 private static final String ATTR_ICON_PATH = "icon";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700106 private static final String ATTR_ID = "id";
Amith Yamasani920ace02012-09-20 22:15:37 -0700107 private static final String ATTR_CREATION_TIME = "created";
108 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
Amith Yamasani2a003292012-08-14 18:25:45 -0700109 private static final String ATTR_SERIAL_NO = "serialNumber";
110 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700111 private static final String ATTR_PARTIAL = "partial";
Adam Lesinskieddeb492014-09-08 17:50:03 -0700112 private static final String ATTR_GUEST_TO_REMOVE = "guestToRemove";
Amith Yamasani6f34b412012-10-22 18:19:27 -0700113 private static final String ATTR_USER_VERSION = "version";
Kenny Guy2a764942014-04-02 13:29:20 +0100114 private static final String ATTR_PROFILE_GROUP_ID = "profileGroupId";
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700115 private static final String ATTR_RESTRICTED_PROFILE_PARENT_ID = "restrictedProfileParentId";
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530116 private static final String TAG_GUEST_RESTRICTIONS = "guestRestrictions";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700117 private static final String TAG_USERS = "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700118 private static final String TAG_USER = "user";
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800119 private static final String TAG_RESTRICTIONS = "restrictions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800120 private static final String TAG_ENTRY = "entry";
121 private static final String TAG_VALUE = "value";
122 private static final String ATTR_KEY = "key";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700123 private static final String ATTR_VALUE_TYPE = "type";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800124 private static final String ATTR_MULTIPLE = "m";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700125
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700126 private static final String ATTR_TYPE_STRING_ARRAY = "sa";
127 private static final String ATTR_TYPE_STRING = "s";
128 private static final String ATTR_TYPE_BOOLEAN = "b";
Amith Yamasani5b5aa402014-06-01 20:10:14 -0700129 private static final String ATTR_TYPE_INTEGER = "i";
Fyodor Kupolov262f9952015-03-23 18:55:11 -0700130 private static final String ATTR_TYPE_BUNDLE = "B";
131 private static final String ATTR_TYPE_BUNDLE_ARRAY = "BA";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700132
Amith Yamasani0b285492011-04-14 17:35:23 -0700133 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700134 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700135 private static final String USER_PHOTO_FILENAME = "photo.png";
Adrian Roos1bdff912015-02-17 15:51:35 +0100136 private static final String USER_PHOTO_FILENAME_TMP = USER_PHOTO_FILENAME + ".tmp";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700137
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800138 private static final String RESTRICTIONS_FILE_PREFIX = "res_";
Amith Yamasanifc95e702013-09-26 13:20:17 -0700139 private static final String XML_SUFFIX = ".xml";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800140
Amith Yamasani634cf312012-10-04 17:34:21 -0700141 private static final int MIN_USER_ID = 10;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700142 // We need to keep process uid within Integer.MAX_VALUE.
143 private static final int MAX_USER_ID = Integer.MAX_VALUE / UserHandle.PER_USER_RANGE;
Amith Yamasani634cf312012-10-04 17:34:21 -0700144
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700145 private static final int USER_VERSION = 6;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700146
Amith Yamasani920ace02012-09-20 22:15:37 -0700147 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
148
Nicolas Prevotb8186812015-08-06 15:00:03 +0100149 // Maximum number of managed profiles permitted per user is 1. This cannot be increased
Amith Yamasani95ab7842014-08-11 17:09:26 -0700150 // without first making sure that the rest of the framework is prepared for it.
151 private static final int MAX_MANAGED_PROFILES = 1;
152
Andres Moralesc5548c02015-08-05 10:23:12 -0700153 /**
154 * Flag indicating whether device credentials are shared among same-user profiles.
155 */
156 private static final boolean CONFIG_PROFILES_SHARE_CREDENTIAL = true;
157
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800158 static final int WRITE_USER_MSG = 1;
159 static final int WRITE_USER_DELAY = 2*1000; // 2 seconds
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530160
Jeff Sharkey6dce4962015-07-03 18:08:41 -0700161 private static final String XATTR_SERIAL = "user.serial";
162
Dianne Hackborn4428e172012-08-24 17:43:05 -0700163 private final Context mContext;
164 private final PackageManagerService mPm;
165 private final Object mInstallLock;
166 private final Object mPackagesLock;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700167
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800168 private final Handler mHandler;
169
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700170 private final File mUsersDir;
171 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700172
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800173 private final SparseArray<UserInfo> mUsers = new SparseArray<UserInfo>();
Makoto Onuki068c54a2015-10-13 14:34:03 -0700174
175 private final Object mRestrictionsLock = new Object();
176
177 /**
178 * User restrictions set via UserManager. This doesn't include restrictions set by
179 * device owner / profile owners.
180 *
181 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
182 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
183 * maybe shared between {@link #mBaseUserRestrictions} and
184 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
185 * (Otherwise we won't be able to detect what restrictions have changed in
186 * {@link #updateUserRestrictionsInternalRL).
187 */
188 @GuardedBy("mRestrictionsLock")
189 private final SparseArray<Bundle> mBaseUserRestrictions = new SparseArray<>();
190
191 /**
192 * Cached user restrictions that are in effect -- i.e. {@link #mBaseUserRestrictions} combined
193 * with device / profile owner restrictions. We'll initialize it lazily; use
194 * {@link #getEffectiveUserRestrictions} to access it.
195 *
196 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
197 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
198 * maybe shared between {@link #mBaseUserRestrictions} and
199 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
200 * (Otherwise we won't be able to detect what restrictions have changed in
201 * {@link #updateUserRestrictionsInternalRL).
202 */
203 @GuardedBy("mRestrictionsLock")
204 private final SparseArray<Bundle> mCachedEffectiveUserRestrictions = new SparseArray<>();
205
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530206 private final Bundle mGuestRestrictions = new Bundle();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800207
208 /**
209 * Set of user IDs being actively removed. Removed IDs linger in this set
210 * for several seconds to work around a VFS caching issue.
211 */
212 // @GuardedBy("mPackagesLock")
213 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700214
Amith Yamasani0b285492011-04-14 17:35:23 -0700215 private int[] mUserIds;
Amith Yamasani2a003292012-08-14 18:25:45 -0700216 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700217 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700218
Jason Monk62062992014-05-06 09:55:28 -0400219 private IAppOpsService mAppOpsService;
220
Makoto Onuki068c54a2015-10-13 14:34:03 -0700221 private final LocalService mLocalService;
222
Amith Yamasani258848d2012-08-10 17:06:33 -0700223 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700224
Dianne Hackborn4428e172012-08-24 17:43:05 -0700225 public static UserManagerService getInstance() {
226 synchronized (UserManagerService.class) {
227 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700228 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700229 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700230
231 /**
232 * Available for testing purposes.
233 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700234 UserManagerService(File dataDir, File baseUserPath) {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700235 this(null, null, new Object(), new Object(), dataDir, baseUserPath);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700236 }
237
Dianne Hackborn4428e172012-08-24 17:43:05 -0700238 /**
239 * Called by package manager to create the service. This is closely
240 * associated with the package manager, and the given lock is the
241 * package manager's own lock.
242 */
243 UserManagerService(Context context, PackageManagerService pm,
244 Object installLock, Object packagesLock) {
245 this(context, pm, installLock, packagesLock,
246 Environment.getDataDirectory(),
247 new File(Environment.getDataDirectory(), "user"));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700248 }
249
Dianne Hackborn4428e172012-08-24 17:43:05 -0700250 /**
251 * Available for testing purposes.
252 */
253 private UserManagerService(Context context, PackageManagerService pm,
254 Object installLock, Object packagesLock,
255 File dataDir, File baseUserPath) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700256 mContext = context;
257 mPm = pm;
258 mInstallLock = installLock;
259 mPackagesLock = packagesLock;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800260 mHandler = new MainHandler();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700261 synchronized (mInstallLock) {
262 synchronized (mPackagesLock) {
263 mUsersDir = new File(dataDir, USER_INFO_DIR);
264 mUsersDir.mkdirs();
265 // Make zeroth user directory, for services to migrate their files to that location
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700266 File userZeroDir = new File(mUsersDir, String.valueOf(UserHandle.USER_SYSTEM));
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700267 userZeroDir.mkdirs();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700268 FileUtils.setPermissions(mUsersDir.toString(),
269 FileUtils.S_IRWXU|FileUtils.S_IRWXG
270 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
271 -1, -1);
272 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
Amith Yamasanida0b1682014-11-21 12:58:17 -0800273 initDefaultGuestRestrictions();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700274 readUserListLocked();
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700275 sInstance = this;
276 }
277 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700278 mLocalService = new LocalService();
279 LocalServices.addService(UserManagerInternal.class, mLocalService);
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700280 }
281
282 void systemReady() {
283 synchronized (mInstallLock) {
284 synchronized (mPackagesLock) {
Amith Yamasani756901d2012-10-12 12:30:07 -0700285 // Prune out any partially created/partially removed users.
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700286 ArrayList<UserInfo> partials = new ArrayList<UserInfo>();
Amith Yamasani515d4062015-09-28 11:30:06 -0700287 final int userSize = mUsers.size();
288 for (int i = 0; i < userSize; i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700289 UserInfo ui = mUsers.valueAt(i);
Adam Lesinskieddeb492014-09-08 17:50:03 -0700290 if ((ui.partial || ui.guestToRemove) && i != 0) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700291 partials.add(ui);
292 }
293 }
Amith Yamasani515d4062015-09-28 11:30:06 -0700294 final int partialsSize = partials.size();
295 for (int i = 0; i < partialsSize; i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700296 UserInfo ui = partials.get(i);
Amith Yamasania7892482015-08-07 11:09:05 -0700297 Slog.w(LOG_TAG, "Removing partially created user " + ui.id
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700298 + " (name=" + ui.name + ")");
299 removeUserStateLocked(ui.id);
300 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700301 }
Dianne Hackborn4428e172012-08-24 17:43:05 -0700302 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700303 onUserForeground(UserHandle.USER_SYSTEM);
Jason Monk62062992014-05-06 09:55:28 -0400304 mAppOpsService = IAppOpsService.Stub.asInterface(
305 ServiceManager.getService(Context.APP_OPS_SERVICE));
306 for (int i = 0; i < mUserIds.length; ++i) {
Makoto Onuki068c54a2015-10-13 14:34:03 -0700307 final int userId = mUserIds[i];
Jason Monk62062992014-05-06 09:55:28 -0400308 try {
Makoto Onuki068c54a2015-10-13 14:34:03 -0700309 mAppOpsService.setUserRestrictions(getEffectiveUserRestrictions(userId), userId);
Jason Monk62062992014-05-06 09:55:28 -0400310 } catch (RemoteException e) {
311 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
312 }
313 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700314 }
315
316 @Override
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700317 public UserInfo getPrimaryUser() {
318 checkManageUsersPermission("query users");
319 synchronized (mPackagesLock) {
Amith Yamasani515d4062015-09-28 11:30:06 -0700320 final int userSize = mUsers.size();
321 for (int i = 0; i < userSize; i++) {
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700322 UserInfo ui = mUsers.valueAt(i);
323 if (ui.isPrimary()) {
324 return ui;
325 }
326 }
327 }
328 return null;
329 }
330
331 @Override
Xiaohui Chen594f2082015-08-18 11:04:20 -0700332 public @NonNull List<UserInfo> getUsers(boolean excludeDying) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700333 checkManageUsersPermission("query users");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700334 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700335 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasani515d4062015-09-28 11:30:06 -0700336 final int userSize = mUsers.size();
337 for (int i = 0; i < userSize; i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700338 UserInfo ui = mUsers.valueAt(i);
339 if (ui.partial) {
340 continue;
341 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800342 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700343 users.add(ui);
Amith Yamasani920ace02012-09-20 22:15:37 -0700344 }
Amith Yamasani13593602012-03-22 16:16:17 -0700345 }
346 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700347 }
Amith Yamasani13593602012-03-22 16:16:17 -0700348 }
349
Amith Yamasani258848d2012-08-10 17:06:33 -0700350 @Override
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100351 public List<UserInfo> getProfiles(int userId, boolean enabledOnly) {
Amith Yamasani4f582632014-02-19 14:31:52 -0800352 if (userId != UserHandle.getCallingUserId()) {
353 checkManageUsersPermission("getting profiles related to user " + userId);
354 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700355 final long ident = Binder.clearCallingIdentity();
356 try {
357 synchronized (mPackagesLock) {
358 return getProfilesLocked(userId, enabledOnly);
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100359 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700360 } finally {
361 Binder.restoreCallingIdentity(ident);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000362 }
363 }
364
Amith Yamasanibe465322014-04-24 13:45:17 -0700365 /** Assume permissions already checked and caller's identity cleared */
366 private List<UserInfo> getProfilesLocked(int userId, boolean enabledOnly) {
Amith Yamasanibe465322014-04-24 13:45:17 -0700367 UserInfo user = getUserInfoLocked(userId);
368 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasanidda003f2014-08-28 18:06:51 -0700369 if (user == null) {
370 // Probably a dying user
371 return users;
372 }
Amith Yamasani515d4062015-09-28 11:30:06 -0700373 final int userSize = mUsers.size();
374 for (int i = 0; i < userSize; i++) {
Amith Yamasanibe465322014-04-24 13:45:17 -0700375 UserInfo profile = mUsers.valueAt(i);
376 if (!isProfileOf(user, profile)) {
377 continue;
378 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100379 if (enabledOnly && !profile.isEnabled()) {
380 continue;
Amith Yamasanibe465322014-04-24 13:45:17 -0700381 }
Amith Yamasani70fcf0c2014-07-11 08:40:19 -0700382 if (mRemovingUserIds.get(profile.id)) {
383 continue;
384 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700385 users.add(profile);
386 }
387 return users;
388 }
389
Jessica Hummelbe81c802014-04-22 15:49:22 +0100390 @Override
Andres Moralesc5548c02015-08-05 10:23:12 -0700391 public int getCredentialOwnerProfile(int userHandle) {
392 checkManageUsersPermission("get the credential owner");
393 if (CONFIG_PROFILES_SHARE_CREDENTIAL) {
394 synchronized (mPackagesLock) {
395 UserInfo profileParent = getProfileParentLocked(userHandle);
396 if (profileParent != null) {
397 return profileParent.id;
398 }
399 }
400 }
401
402 return userHandle;
403 }
404
405 @Override
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700406 public boolean isSameProfileGroup(int userId, int otherUserId) {
407 if (userId == otherUserId) return true;
408 checkManageUsersPermission("check if in the same profile group");
409 synchronized (mPackagesLock) {
410 return isSameProfileGroupLocked(userId, otherUserId);
411 }
412 }
413
414 private boolean isSameProfileGroupLocked(int userId, int otherUserId) {
415 UserInfo userInfo = getUserInfoLocked(userId);
416 if (userInfo == null || userInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
417 return false;
418 }
419 UserInfo otherUserInfo = getUserInfoLocked(otherUserId);
420 if (otherUserInfo == null || otherUserInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
421 return false;
422 }
423 return userInfo.profileGroupId == otherUserInfo.profileGroupId;
424 }
425
426 @Override
Jessica Hummelbe81c802014-04-22 15:49:22 +0100427 public UserInfo getProfileParent(int userHandle) {
428 checkManageUsersPermission("get the profile parent");
429 synchronized (mPackagesLock) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700430 return getProfileParentLocked(userHandle);
431 }
432 }
433
434 private UserInfo getProfileParentLocked(int userHandle) {
435 UserInfo profile = getUserInfoLocked(userHandle);
436 if (profile == null) {
437 return null;
438 }
439 int parentUserId = profile.profileGroupId;
440 if (parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
441 return null;
442 } else {
443 return getUserInfoLocked(parentUserId);
Jessica Hummelbe81c802014-04-22 15:49:22 +0100444 }
445 }
446
Kenny Guy2a764942014-04-02 13:29:20 +0100447 private boolean isProfileOf(UserInfo user, UserInfo profile) {
448 return user.id == profile.id ||
449 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
450 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000451 }
452
453 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100454 public void setUserEnabled(int userId) {
455 checkManageUsersPermission("enable user");
456 synchronized (mPackagesLock) {
457 UserInfo info = getUserInfoLocked(userId);
458 if (info != null && !info.isEnabled()) {
459 info.flags ^= UserInfo.FLAG_DISABLED;
460 writeUserLocked(info);
461 }
462 }
463 }
464
465 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700466 public UserInfo getUserInfo(int userId) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700467 checkManageUsersPermission("query user");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700468 synchronized (mPackagesLock) {
Amith Yamasani195263742012-08-21 15:40:12 -0700469 return getUserInfoLocked(userId);
Amith Yamasani13593602012-03-22 16:16:17 -0700470 }
471 }
472
Amith Yamasani71e6c692013-03-24 17:39:28 -0700473 @Override
474 public boolean isRestricted() {
475 synchronized (mPackagesLock) {
476 return getUserInfoLocked(UserHandle.getCallingUserId()).isRestricted();
477 }
478 }
479
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700480 @Override
481 public boolean canHaveRestrictedProfile(int userId) {
482 checkManageUsersPermission("canHaveRestrictedProfile");
483 synchronized (mPackagesLock) {
484 final UserInfo userInfo = getUserInfoLocked(userId);
485 if (userInfo == null || !userInfo.canHaveProfile()) {
486 return false;
487 }
488 if (!userInfo.isAdmin()) {
489 return false;
490 }
491 }
492 DevicePolicyManager dpm = (DevicePolicyManager) mContext.getSystemService(
493 Context.DEVICE_POLICY_SERVICE);
494 // restricted profile can be created if there is no DO set and the admin user has no PO
495 return dpm.getDeviceOwner() == null && dpm.getProfileOwnerAsUser(userId) == null;
496 }
497
Amith Yamasani195263742012-08-21 15:40:12 -0700498 /*
499 * Should be locked on mUsers before calling this.
500 */
501 private UserInfo getUserInfoLocked(int userId) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700502 UserInfo ui = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -0700503 // If it is partial and not in the process of being removed, return as unknown user.
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800504 if (ui != null && ui.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700505 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
506 return null;
507 }
508 return ui;
Amith Yamasani195263742012-08-21 15:40:12 -0700509 }
510
Amith Yamasani236b2b52015-08-18 14:32:14 -0700511 /** Called by PackageManagerService */
Amith Yamasani13593602012-03-22 16:16:17 -0700512 public boolean exists(int userId) {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700513 synchronized (mPackagesLock) {
Amith Yamasani236b2b52015-08-18 14:32:14 -0700514 return mUsers.get(userId) != null;
Amith Yamasani13593602012-03-22 16:16:17 -0700515 }
516 }
517
Amith Yamasani258848d2012-08-10 17:06:33 -0700518 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700519 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700520 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700521 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700522 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700523 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700524 if (info == null || info.partial) {
525 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
526 return;
527 }
Amith Yamasani13593602012-03-22 16:16:17 -0700528 if (name != null && !name.equals(info.name)) {
529 info.name = name;
530 writeUserLocked(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700531 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -0700532 }
533 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700534 if (changed) {
535 sendUserInfoChangedBroadcast(userId);
536 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700537 }
538
Amith Yamasani258848d2012-08-10 17:06:33 -0700539 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700540 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700541 checkManageUsersPermission("update users");
Jason Monk9a944532014-07-08 09:31:21 -0400542 long ident = Binder.clearCallingIdentity();
543 try {
544 synchronized (mPackagesLock) {
545 UserInfo info = mUsers.get(userId);
546 if (info == null || info.partial) {
547 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
548 return;
549 }
550 writeBitmapLocked(info, bitmap);
551 writeUserLocked(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700552 }
Jason Monk9a944532014-07-08 09:31:21 -0400553 sendUserInfoChangedBroadcast(userId);
554 } finally {
555 Binder.restoreCallingIdentity(ident);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700556 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700557 }
558
559 private void sendUserInfoChangedBroadcast(int userId) {
560 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
561 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
562 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -0700563 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700564 }
565
Amith Yamasani258848d2012-08-10 17:06:33 -0700566 @Override
Adrian Roos1bdff912015-02-17 15:51:35 +0100567 public ParcelFileDescriptor getUserIcon(int userId) {
568 String iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700569 synchronized (mPackagesLock) {
570 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700571 if (info == null || info.partial) {
572 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + userId);
573 return null;
574 }
Nicolas Prevot88cc3462014-05-14 14:51:48 +0100575 int callingGroupId = mUsers.get(UserHandle.getCallingUserId()).profileGroupId;
576 if (callingGroupId == UserInfo.NO_PROFILE_GROUP_ID
577 || callingGroupId != info.profileGroupId) {
578 checkManageUsersPermission("get the icon of a user who is not related");
579 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700580 if (info.iconPath == null) {
581 return null;
582 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100583 iconPath = info.iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700584 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100585
586 try {
587 return ParcelFileDescriptor.open(
588 new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
589 } catch (FileNotFoundException e) {
590 Log.e(LOG_TAG, "Couldn't find icon file", e);
591 }
592 return null;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700593 }
594
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700595 public void makeInitialized(int userId) {
596 checkManageUsersPermission("makeInitialized");
597 synchronized (mPackagesLock) {
598 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700599 if (info == null || info.partial) {
600 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
601 }
602 if ((info.flags&UserInfo.FLAG_INITIALIZED) == 0) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700603 info.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800604 scheduleWriteUserLocked(info);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700605 }
606 }
607 }
608
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700609 /**
610 * If default guest restrictions haven't been initialized yet, add the basic
611 * restrictions.
612 */
613 private void initDefaultGuestRestrictions() {
614 if (mGuestRestrictions.isEmpty()) {
615 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
Amith Yamasanida0b1682014-11-21 12:58:17 -0800616 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700617 }
618 }
619
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800620 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530621 public Bundle getDefaultGuestRestrictions() {
622 checkManageUsersPermission("getDefaultGuestRestrictions");
623 synchronized (mPackagesLock) {
624 return new Bundle(mGuestRestrictions);
625 }
626 }
627
628 @Override
629 public void setDefaultGuestRestrictions(Bundle restrictions) {
630 checkManageUsersPermission("setDefaultGuestRestrictions");
631 synchronized (mPackagesLock) {
632 mGuestRestrictions.clear();
633 mGuestRestrictions.putAll(restrictions);
634 writeUserListLocked();
635 }
636 }
637
Makoto Onuki068c54a2015-10-13 14:34:03 -0700638 @GuardedBy("mRestrictionsLock")
639 private Bundle computeEffectiveUserRestrictionsRL(int userId) {
640 final DevicePolicyManagerInternal dpmi =
641 LocalServices.getService(DevicePolicyManagerInternal.class);
642 final Bundle systemRestrictions = mBaseUserRestrictions.get(userId);
643
644 final Bundle effective;
645 if (dpmi == null) {
646 // TODO Make sure it's because DPMS is disabled and not because we called it too early.
647 effective = systemRestrictions;
648 } else {
649 effective = dpmi.getComposedUserRestrictions(userId, systemRestrictions);
650 }
651 return effective;
652 }
653
654 @GuardedBy("mRestrictionsLock")
655 private void invalidateEffectiveUserRestrictionsRL(int userId) {
656 if (DBG) {
657 Log.d(LOG_TAG, "invalidateEffectiveUserRestrictions userId=" + userId);
658 }
659 mCachedEffectiveUserRestrictions.remove(userId);
660 }
661
662 private Bundle getEffectiveUserRestrictions(int userId) {
663 synchronized (mRestrictionsLock) {
664 Bundle restrictions = mCachedEffectiveUserRestrictions.get(userId);
665 if (restrictions == null) {
666 restrictions = computeEffectiveUserRestrictionsRL(userId);
667 mCachedEffectiveUserRestrictions.put(userId, restrictions);
668 }
669 return restrictions;
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700670 }
671 }
672
Makoto Onuki068c54a2015-10-13 14:34:03 -0700673 /** @return a specific user restriction that's in effect currently. */
674 @Override
675 public boolean hasUserRestriction(String restrictionKey, int userId) {
676 Bundle restrictions = getEffectiveUserRestrictions(userId);
677 return restrictions != null && restrictions.getBoolean(restrictionKey);
678 }
679
680 /**
681 * @return UserRestrictions that are in effect currently. This always returns a new
682 * {@link Bundle}.
683 */
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700684 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800685 public Bundle getUserRestrictions(int userId) {
Makoto Onuki068c54a2015-10-13 14:34:03 -0700686 Bundle restrictions = getEffectiveUserRestrictions(userId);
687 return restrictions != null ? new Bundle(restrictions) : new Bundle();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800688 }
689
690 @Override
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700691 public void setUserRestriction(String key, boolean value, int userId) {
Fyodor Kupolovd4b26042015-07-27 14:30:59 -0700692 checkManageUsersPermission("setUserRestriction");
Makoto Onuki068c54a2015-10-13 14:34:03 -0700693 if (!UserRestrictionsUtils.SYSTEM_CONTROLLED_USER_RESTRICTIONS.contains(key)) {
694 setUserRestrictionNoCheck(key, value, userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700695 }
696 }
697
698 @Override
699 public void setSystemControlledUserRestriction(String key, boolean value, int userId) {
700 checkSystemOrRoot("setSystemControlledUserRestriction");
Makoto Onuki068c54a2015-10-13 14:34:03 -0700701 setUserRestrictionNoCheck(key, value, userId);
702 }
703
704 private void setUserRestrictionNoCheck(String key, boolean value, int userId) {
705 synchronized (mRestrictionsLock) {
706 // Note we can't modify Bundles stored in mBaseUserRestrictions directly, so create
707 // a copy.
708 final Bundle newRestrictions = new Bundle();
709 UserRestrictionsUtils.merge(newRestrictions, mBaseUserRestrictions.get(userId));
710 newRestrictions.putBoolean(key, value);
711
712 updateUserRestrictionsInternalRL(newRestrictions, userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700713 }
714 }
715
Makoto Onuki068c54a2015-10-13 14:34:03 -0700716 /**
717 * Optionally updating user restrictions, calculate the effective user restrictions by
718 * consulting {@link com.android.server.devicepolicy.DevicePolicyManagerService} and also
719 * apply it to {@link com.android.server.AppOpsService}.
720 * TODO applyUserRestrictionsLocked() should also apply to system settings.
721 *
722 * @param newRestrictions User restrictions to set. If null, only the effective restrictions
723 * will be updated. Note don't pass an existing Bundle in {@link #mBaseUserRestrictions}
724 * or {@link #mCachedEffectiveUserRestrictions}; that'll most likely cause a sub
725 * @param userId target user ID.
726 */
727 @GuardedBy("mRestrictionsLock")
728 private void updateUserRestrictionsInternalRL(
729 @Nullable Bundle newRestrictions, int userId) {
730 if (DBG) {
731 Log.d(LOG_TAG, "updateUserRestrictionsInternalLocked userId=" + userId
732 + " bundle=" + newRestrictions);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800733 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700734 final Bundle prevRestrictions = getEffectiveUserRestrictions(userId);
735
736 // Update system restrictions.
737 if (newRestrictions != null) {
738 // If newRestrictions == the current one, it's probably a bug.
739 Preconditions.checkState(mBaseUserRestrictions.get(userId) != newRestrictions);
740 Preconditions.checkState(mCachedEffectiveUserRestrictions.get(userId)
741 != newRestrictions);
742 mBaseUserRestrictions.put(userId, newRestrictions);
743 }
744
Makoto Onuki759a7632015-10-28 16:43:10 -0700745 final Bundle effective = computeEffectiveUserRestrictionsRL(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700746
Makoto Onuki759a7632015-10-28 16:43:10 -0700747 mCachedEffectiveUserRestrictions.put(userId, effective);
748
749 applyUserRestrictionsRL(userId, effective, prevRestrictions);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800750 }
751
Makoto Onuki068c54a2015-10-13 14:34:03 -0700752 @GuardedBy("mRestrictionsLock")
753 private void applyUserRestrictionsRL(int userId,
754 Bundle newRestrictions, Bundle prevRestrictions) {
755 final long token = Binder.clearCallingIdentity();
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700756 try {
Makoto Onuki068c54a2015-10-13 14:34:03 -0700757 mAppOpsService.setUserRestrictions(newRestrictions, userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700758 } catch (RemoteException e) {
759 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
760 } finally {
761 Binder.restoreCallingIdentity(token);
762 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700763
764 // TODO Move the code from DPMS.setUserRestriction().
765 }
766
767 @GuardedBy("mRestrictionsLock")
768 private void updateEffectiveUserRestrictionsRL(int userId) {
769 updateUserRestrictionsInternalRL(null, userId);
770 }
771
772 @GuardedBy("mRestrictionsLock")
773 private void updateEffectiveUserRestrictionsForAllUsersRL() {
774 // First, invalidate all cached values.
775 synchronized (mRestrictionsLock) {
776 mCachedEffectiveUserRestrictions.clear();
777 }
778 // We don't want to call into ActivityManagerNative while taking a lock, so we'll call
779 // it on a handler.
780 final Runnable r = new Runnable() {
781 @Override
782 public void run() {
783 // Then get the list of running users.
784 final int[] runningUsers;
785 try {
786 runningUsers = ActivityManagerNative.getDefault().getRunningUserIds();
787 } catch (RemoteException e) {
788 Log.w(LOG_TAG, "Unable to access ActivityManagerNative");
789 return;
790 }
791 // Then re-calculate the effective restrictions and apply, only for running users.
792 // It's okay if a new user has started after the getRunningUserIds() call,
793 // because we'll do the same thing (re-calculate the restrictions and apply)
794 // when we start a user.
795 // TODO: "Apply restrictions upon user start hasn't been implemented. Implement it.
796 synchronized (mRestrictionsLock) {
797 for (int i = 0; i < runningUsers.length; i++) {
798 updateUserRestrictionsInternalRL(null, runningUsers[i]);
799 }
800 }
801 }
802 };
803 mHandler.post(r);
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700804 }
805
Amith Yamasani258848d2012-08-10 17:06:33 -0700806 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700807 * Check if we've hit the limit of how many users can be created.
808 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700809 private boolean isUserLimitReachedLocked() {
Nicolas Prevot12678a92015-05-13 12:15:03 -0700810 return getAliveUsersExcludingGuestsCountLocked() >= UserManager.getMaxSupportedUsers();
811 }
812
813 @Override
Nicolas Prevotb8186812015-08-06 15:00:03 +0100814 public boolean canAddMoreManagedProfiles(int userId) {
Nicolas Prevot12678a92015-05-13 12:15:03 -0700815 checkManageUsersPermission("check if more managed profiles can be added.");
816 if (ActivityManager.isLowRamDeviceStatic()) {
817 return false;
818 }
Fyodor Kupolovb6157992015-06-05 15:32:28 -0700819 if (!mContext.getPackageManager().hasSystemFeature(
820 PackageManager.FEATURE_MANAGED_USERS)) {
821 return false;
822 }
Nicolas Prevotb8186812015-08-06 15:00:03 +0100823 // Limit number of managed profiles that can be created
824 int managedProfilesCount = getProfiles(userId, true).size() - 1;
825 if (managedProfilesCount >= MAX_MANAGED_PROFILES) {
826 return false;
827 }
Nicolas Prevot12678a92015-05-13 12:15:03 -0700828 synchronized(mPackagesLock) {
Nicolas Prevotb8186812015-08-06 15:00:03 +0100829 UserInfo userInfo = getUserInfoLocked(userId);
830 if (!userInfo.canHaveProfile()) {
Nicolas Prevot12678a92015-05-13 12:15:03 -0700831 return false;
832 }
833 int usersCount = getAliveUsersExcludingGuestsCountLocked();
834 // We allow creating a managed profile in the special case where there is only one user.
835 return usersCount == 1 || usersCount < UserManager.getMaxSupportedUsers();
836 }
837 }
838
839 private int getAliveUsersExcludingGuestsCountLocked() {
Amith Yamasanif584f012014-05-19 17:57:25 -0700840 int aliveUserCount = 0;
841 final int totalUserCount = mUsers.size();
842 // Skip over users being removed
843 for (int i = 0; i < totalUserCount; i++) {
844 UserInfo user = mUsers.valueAt(i);
Amith Yamasani95ab7842014-08-11 17:09:26 -0700845 if (!mRemovingUserIds.get(user.id)
Amith Yamasani1df14732014-08-29 21:37:27 -0700846 && !user.isGuest() && !user.partial) {
Amith Yamasanif584f012014-05-19 17:57:25 -0700847 aliveUserCount++;
848 }
849 }
Nicolas Prevot12678a92015-05-13 12:15:03 -0700850 return aliveUserCount;
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700851 }
852
853 /**
Amith Yamasani195263742012-08-21 15:40:12 -0700854 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -0700855 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -0700856 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -0700857 *
858 * @param message used as message if SecurityException is thrown
859 * @throws SecurityException if the caller is not system or root
860 */
Amith Yamasanibe465322014-04-24 13:45:17 -0700861 private static final void checkManageUsersPermission(String message) {
Amith Yamasani258848d2012-08-10 17:06:33 -0700862 final int uid = Binder.getCallingUid();
Amith Yamasanibe465322014-04-24 13:45:17 -0700863 if (uid != Process.SYSTEM_UID && uid != 0
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400864 && ActivityManager.checkComponentPermission(
865 android.Manifest.permission.MANAGE_USERS,
Amith Yamasanibe465322014-04-24 13:45:17 -0700866 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
867 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
868 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400869 }
870
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700871 private static void checkSystemOrRoot(String message) {
872 final int uid = Binder.getCallingUid();
873 if (uid != Process.SYSTEM_UID && uid != 0) {
874 throw new SecurityException("Only system may call: " + message);
875 }
876 }
877
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700878 private void writeBitmapLocked(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700879 try {
880 File dir = new File(mUsersDir, Integer.toString(info.id));
881 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +0100882 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700883 if (!dir.exists()) {
884 dir.mkdir();
885 FileUtils.setPermissions(
886 dir.getPath(),
887 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
888 -1, -1);
889 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700890 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +0100891 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
892 && tmp.renameTo(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -0700893 info.iconPath = file.getAbsolutePath();
894 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700895 try {
896 os.close();
897 } catch (IOException ioe) {
898 // What the ... !
899 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100900 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700901 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700902 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700903 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700904 }
905
Amith Yamasani0b285492011-04-14 17:35:23 -0700906 /**
907 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
908 * cache it elsewhere.
909 * @return the array of user ids.
910 */
Dianne Hackborn1676c852012-09-10 14:52:30 -0700911 public int[] getUserIds() {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700912 synchronized (mPackagesLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700913 return mUserIds;
914 }
Amith Yamasani0b285492011-04-14 17:35:23 -0700915 }
916
Dianne Hackborn4428e172012-08-24 17:43:05 -0700917 int[] getUserIdsLPr() {
918 return mUserIds;
919 }
920
Amith Yamasani13593602012-03-22 16:16:17 -0700921 private void readUserListLocked() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700922 if (!mUserListFile.exists()) {
Amith Yamasani13593602012-03-22 16:16:17 -0700923 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700924 return;
925 }
926 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700927 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700928 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700929 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700930 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100931 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700932 int type;
933 while ((type = parser.next()) != XmlPullParser.START_TAG
934 && type != XmlPullParser.END_DOCUMENT) {
935 ;
936 }
937
938 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700939 Slog.e(LOG_TAG, "Unable to read user list");
Amith Yamasani13593602012-03-22 16:16:17 -0700940 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700941 return;
942 }
943
Amith Yamasani2a003292012-08-14 18:25:45 -0700944 mNextSerialNumber = -1;
945 if (parser.getName().equals(TAG_USERS)) {
946 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
947 if (lastSerialNumber != null) {
948 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
949 }
Amith Yamasani6f34b412012-10-22 18:19:27 -0700950 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
951 if (versionNumber != null) {
952 mUserVersion = Integer.parseInt(versionNumber);
953 }
Amith Yamasani2a003292012-08-14 18:25:45 -0700954 }
955
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700956 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530957 if (type == XmlPullParser.START_TAG) {
958 final String name = parser.getName();
959 if (name.equals(TAG_USER)) {
960 String id = parser.getAttributeValue(null, ATTR_ID);
961 UserInfo user = readUserLocked(Integer.parseInt(id));
Amith Yamasani6f34b412012-10-22 18:19:27 -0700962
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530963 if (user != null) {
964 mUsers.put(user.id, user);
965 if (mNextSerialNumber < 0 || mNextSerialNumber <= user.id) {
966 mNextSerialNumber = user.id + 1;
967 }
Amith Yamasani2a003292012-08-14 18:25:45 -0700968 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530969 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -0800970 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
971 && type != XmlPullParser.END_TAG) {
972 if (type == XmlPullParser.START_TAG) {
973 if (parser.getName().equals(TAG_RESTRICTIONS)) {
Makoto Onukia4f11972015-10-01 13:19:58 -0700974 UserRestrictionsUtils
975 .readRestrictions(parser, mGuestRestrictions);
Amith Yamasanida0b1682014-11-21 12:58:17 -0800976 }
977 break;
978 }
979 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700980 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700981 }
982 }
Amith Yamasani13593602012-03-22 16:16:17 -0700983 updateUserIdsLocked();
Amith Yamasani350962c2013-08-06 11:18:53 -0700984 upgradeIfNecessaryLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700985 } catch (IOException ioe) {
Amith Yamasani13593602012-03-22 16:16:17 -0700986 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700987 } catch (XmlPullParserException pe) {
Amith Yamasani13593602012-03-22 16:16:17 -0700988 fallbackToSingleUserLocked();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -0800989 } finally {
990 if (fis != null) {
991 try {
992 fis.close();
993 } catch (IOException e) {
994 }
995 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700996 }
997 }
998
Amith Yamasani6f34b412012-10-22 18:19:27 -0700999 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -08001000 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -07001001 */
Amith Yamasani350962c2013-08-06 11:18:53 -07001002 private void upgradeIfNecessaryLocked() {
Amith Yamasani6f34b412012-10-22 18:19:27 -07001003 int userVersion = mUserVersion;
1004 if (userVersion < 1) {
1005 // Assign a proper name for the owner, if not initialized correctly before
Xiaohui Chen47f07952015-10-02 14:40:27 -07001006 UserInfo user = mUsers.get(UserHandle.USER_SYSTEM);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001007 if ("Primary".equals(user.name)) {
1008 user.name = mContext.getResources().getString(com.android.internal.R.string.owner_name);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001009 scheduleWriteUserLocked(user);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001010 }
1011 userVersion = 1;
1012 }
1013
Amith Yamasanibc9625052012-11-15 14:39:18 -08001014 if (userVersion < 2) {
1015 // Owner should be marked as initialized
Xiaohui Chen47f07952015-10-02 14:40:27 -07001016 UserInfo user = mUsers.get(UserHandle.USER_SYSTEM);
Amith Yamasanibc9625052012-11-15 14:39:18 -08001017 if ((user.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1018 user.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001019 scheduleWriteUserLocked(user);
Amith Yamasanibc9625052012-11-15 14:39:18 -08001020 }
1021 userVersion = 2;
1022 }
1023
Amith Yamasani350962c2013-08-06 11:18:53 -07001024
Amith Yamasani5e486f52013-08-07 11:06:44 -07001025 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -07001026 userVersion = 4;
1027 }
1028
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001029 if (userVersion < 5) {
1030 initDefaultGuestRestrictions();
1031 userVersion = 5;
1032 }
1033
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001034 if (userVersion < 6) {
1035 final boolean splitSystemUser = UserManager.isSplitSystemUser();
1036 for (int i = 0; i < mUsers.size(); i++) {
1037 UserInfo user = mUsers.valueAt(i);
1038 // In non-split mode, only user 0 can have restricted profiles
1039 if (!splitSystemUser && user.isRestricted()
1040 && (user.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID)) {
1041 user.restrictedProfileParentId = UserHandle.USER_SYSTEM;
1042 scheduleWriteUserLocked(user);
1043 }
1044 }
1045 userVersion = 6;
1046 }
1047
Amith Yamasani6f34b412012-10-22 18:19:27 -07001048 if (userVersion < USER_VERSION) {
1049 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
1050 + USER_VERSION);
1051 } else {
1052 mUserVersion = userVersion;
1053 writeUserListLocked();
1054 }
1055 }
1056
Amith Yamasani13593602012-03-22 16:16:17 -07001057 private void fallbackToSingleUserLocked() {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001058 int flags = UserInfo.FLAG_INITIALIZED;
1059 // In split system user mode, the admin and primary flags are assigned to the first human
1060 // user.
1061 if (!UserManager.isSplitSystemUser()) {
1062 flags |= UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY;
1063 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001064 // Create the system user
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001065 UserInfo system = new UserInfo(UserHandle.USER_SYSTEM,
Amith Yamasani6f34b412012-10-22 18:19:27 -07001066 mContext.getResources().getString(com.android.internal.R.string.owner_name), null,
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001067 flags);
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001068 mUsers.put(system.id, system);
Amith Yamasani634cf312012-10-04 17:34:21 -07001069 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -04001070 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -08001071
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001072 Bundle restrictions = new Bundle();
Makoto Onuki068c54a2015-10-13 14:34:03 -07001073 synchronized (mRestrictionsLock) {
1074 mBaseUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions);
1075 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001076
Amith Yamasani13593602012-03-22 16:16:17 -07001077 updateUserIdsLocked();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001078 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001079
Amith Yamasani13593602012-03-22 16:16:17 -07001080 writeUserListLocked();
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001081 writeUserLocked(system);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001082 }
1083
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001084 private void scheduleWriteUserLocked(UserInfo userInfo) {
1085 if (!mHandler.hasMessages(WRITE_USER_MSG, userInfo)) {
1086 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, userInfo);
1087 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
1088 }
1089 }
1090
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001091 /*
1092 * Writes the user file in this format:
1093 *
1094 * <user flags="20039023" id="0">
1095 * <name>Primary</name>
1096 * </user>
1097 */
Amith Yamasani13593602012-03-22 16:16:17 -07001098 private void writeUserLocked(UserInfo userInfo) {
Amith Yamasani742a6712011-05-04 14:49:28 -07001099 FileOutputStream fos = null;
Amith Yamasanifc95e702013-09-26 13:20:17 -07001100 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userInfo.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001101 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001102 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001103 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1104
1105 // XmlSerializer serializer = XmlUtils.serializerInstance();
1106 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001107 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001108 serializer.startDocument(null, true);
1109 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1110
1111 serializer.startTag(null, TAG_USER);
1112 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
Amith Yamasani2a003292012-08-14 18:25:45 -07001113 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001114 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Amith Yamasani920ace02012-09-20 22:15:37 -07001115 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
1116 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
1117 Long.toString(userInfo.lastLoggedInTime));
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001118 if (userInfo.iconPath != null) {
1119 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
1120 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001121 if (userInfo.partial) {
1122 serializer.attribute(null, ATTR_PARTIAL, "true");
1123 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001124 if (userInfo.guestToRemove) {
1125 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
1126 }
Kenny Guy2a764942014-04-02 13:29:20 +01001127 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
1128 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
1129 Integer.toString(userInfo.profileGroupId));
Kenny Guya52dc3e2014-02-11 15:33:14 +00001130 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001131 if (userInfo.restrictedProfileParentId != UserInfo.NO_PROFILE_GROUP_ID) {
1132 serializer.attribute(null, ATTR_RESTRICTED_PROFILE_PARENT_ID,
1133 Integer.toString(userInfo.restrictedProfileParentId));
1134 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001135 serializer.startTag(null, TAG_NAME);
1136 serializer.text(userInfo.name);
1137 serializer.endTag(null, TAG_NAME);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001138 Bundle restrictions;
1139 synchronized (mRestrictionsLock) {
1140 restrictions = mBaseUserRestrictions.get(userInfo.id);
1141 }
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001142 if (restrictions != null) {
Makoto Onuki068c54a2015-10-13 14:34:03 -07001143 UserRestrictionsUtils
1144 .writeRestrictions(serializer, restrictions, TAG_RESTRICTIONS);
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001145 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001146 serializer.endTag(null, TAG_USER);
1147
1148 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001149 userFile.finishWrite(fos);
1150 } catch (Exception ioe) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001151 Slog.e(LOG_TAG, "Error writing user info " + userInfo.id + "\n" + ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -07001152 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001153 }
1154 }
1155
1156 /*
1157 * Writes the user list file in this format:
1158 *
Amith Yamasani2a003292012-08-14 18:25:45 -07001159 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001160 * <user id="0"></user>
1161 * <user id="2"></user>
1162 * </users>
1163 */
Amith Yamasani13593602012-03-22 16:16:17 -07001164 private void writeUserListLocked() {
Amith Yamasani742a6712011-05-04 14:49:28 -07001165 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001166 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001167 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001168 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001169 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1170
1171 // XmlSerializer serializer = XmlUtils.serializerInstance();
1172 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001173 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001174 serializer.startDocument(null, true);
1175 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1176
1177 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -07001178 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -07001179 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001180
Adam Lesinskieddeb492014-09-08 17:50:03 -07001181 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Makoto Onukia4f11972015-10-01 13:19:58 -07001182 UserRestrictionsUtils
1183 .writeRestrictions(serializer, mGuestRestrictions, TAG_RESTRICTIONS);
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301184 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Amith Yamasani515d4062015-09-28 11:30:06 -07001185 final int userSize = mUsers.size();
1186 for (int i = 0; i < userSize; i++) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001187 UserInfo user = mUsers.valueAt(i);
1188 serializer.startTag(null, TAG_USER);
1189 serializer.attribute(null, ATTR_ID, Integer.toString(user.id));
1190 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001191 }
1192
1193 serializer.endTag(null, TAG_USERS);
1194
1195 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001196 userListFile.finishWrite(fos);
1197 } catch (Exception e) {
1198 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -07001199 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001200 }
1201 }
1202
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001203 private UserInfo readUserLocked(int id) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001204 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -07001205 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001206 String name = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001207 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -07001208 long creationTime = 0L;
1209 long lastLoggedInTime = 0L;
Kenny Guy2a764942014-04-02 13:29:20 +01001210 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001211 int restrictedProfileParentId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001212 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001213 boolean guestToRemove = false;
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001214 Bundle restrictions = new Bundle();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001215
1216 FileInputStream fis = null;
1217 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001218 AtomicFile userFile =
Amith Yamasanifc95e702013-09-26 13:20:17 -07001219 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
Amith Yamasani2a003292012-08-14 18:25:45 -07001220 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001221 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001222 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001223 int type;
1224 while ((type = parser.next()) != XmlPullParser.START_TAG
1225 && type != XmlPullParser.END_DOCUMENT) {
1226 ;
1227 }
1228
1229 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001230 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001231 return null;
1232 }
1233
1234 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001235 int storedId = readIntAttribute(parser, ATTR_ID, -1);
1236 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001237 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001238 return null;
1239 }
Amith Yamasani920ace02012-09-20 22:15:37 -07001240 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
1241 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001242 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -07001243 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
1244 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Kenny Guy2a764942014-04-02 13:29:20 +01001245 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
1246 UserInfo.NO_PROFILE_GROUP_ID);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001247 restrictedProfileParentId = readIntAttribute(parser,
1248 ATTR_RESTRICTED_PROFILE_PARENT_ID, UserInfo.NO_PROFILE_GROUP_ID);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001249 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
1250 if ("true".equals(valueString)) {
1251 partial = true;
1252 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001253 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
1254 if ("true".equals(valueString)) {
1255 guestToRemove = true;
1256 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001257
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001258 int outerDepth = parser.getDepth();
1259 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1260 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1261 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1262 continue;
1263 }
1264 String tag = parser.getName();
1265 if (TAG_NAME.equals(tag)) {
1266 type = parser.next();
1267 if (type == XmlPullParser.TEXT) {
1268 name = parser.getText();
1269 }
1270 } else if (TAG_RESTRICTIONS.equals(tag)) {
Makoto Onukia4f11972015-10-01 13:19:58 -07001271 UserRestrictionsUtils.readRestrictions(parser, restrictions);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001272 }
1273 }
1274 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001275
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001276 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -07001277 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -07001278 userInfo.creationTime = creationTime;
1279 userInfo.lastLoggedInTime = lastLoggedInTime;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001280 userInfo.partial = partial;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001281 userInfo.guestToRemove = guestToRemove;
Kenny Guy2a764942014-04-02 13:29:20 +01001282 userInfo.profileGroupId = profileGroupId;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001283 userInfo.restrictedProfileParentId = restrictedProfileParentId;
Makoto Onuki068c54a2015-10-13 14:34:03 -07001284 synchronized (mRestrictionsLock) {
1285 mBaseUserRestrictions.append(id, restrictions);
1286 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001287 return userInfo;
1288
1289 } catch (IOException ioe) {
1290 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001291 } finally {
1292 if (fis != null) {
1293 try {
1294 fis.close();
1295 } catch (IOException e) {
1296 }
1297 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001298 }
1299 return null;
1300 }
1301
Amith Yamasani920ace02012-09-20 22:15:37 -07001302 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
1303 String valueString = parser.getAttributeValue(null, attr);
1304 if (valueString == null) return defaultValue;
1305 try {
1306 return Integer.parseInt(valueString);
1307 } catch (NumberFormatException nfe) {
1308 return defaultValue;
1309 }
1310 }
1311
1312 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
1313 String valueString = parser.getAttributeValue(null, attr);
1314 if (valueString == null) return defaultValue;
1315 try {
1316 return Long.parseLong(valueString);
1317 } catch (NumberFormatException nfe) {
1318 return defaultValue;
1319 }
1320 }
1321
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001322 private boolean isPackageInstalled(String pkg, int userId) {
1323 final ApplicationInfo info = mPm.getApplicationInfo(pkg,
1324 PackageManager.GET_UNINSTALLED_PACKAGES,
1325 userId);
1326 if (info == null || (info.flags&ApplicationInfo.FLAG_INSTALLED) == 0) {
1327 return false;
1328 }
1329 return true;
1330 }
1331
Amith Yamasanib82add22013-07-09 11:24:44 -07001332 /**
Kenny Guyd21b2182014-07-17 16:38:55 +01001333 * Removes all the restrictions files (res_<packagename>) for a given user.
Amith Yamasanib82add22013-07-09 11:24:44 -07001334 * Does not do any permissions checking.
1335 */
Kenny Guyd21b2182014-07-17 16:38:55 +01001336 private void cleanAppRestrictions(int userId) {
Amith Yamasanib82add22013-07-09 11:24:44 -07001337 synchronized (mPackagesLock) {
1338 File dir = Environment.getUserSystemDirectory(userId);
1339 String[] files = dir.list();
1340 if (files == null) return;
1341 for (String fileName : files) {
1342 if (fileName.startsWith(RESTRICTIONS_FILE_PREFIX)) {
1343 File resFile = new File(dir, fileName);
1344 if (resFile.exists()) {
Kenny Guyd21b2182014-07-17 16:38:55 +01001345 resFile.delete();
Amith Yamasanib82add22013-07-09 11:24:44 -07001346 }
1347 }
1348 }
1349 }
1350 }
1351
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001352 /**
1353 * Removes the app restrictions file for a specific package and user id, if it exists.
1354 */
1355 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
1356 synchronized (mPackagesLock) {
1357 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07001358 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001359 if (resFile.exists()) {
1360 resFile.delete();
1361 }
1362 }
1363 }
1364
Kenny Guya52dc3e2014-02-11 15:33:14 +00001365 @Override
Kenny Guy2a764942014-04-02 13:29:20 +01001366 public UserInfo createProfileForUser(String name, int flags, int userId) {
Kenny Guya52dc3e2014-02-11 15:33:14 +00001367 checkManageUsersPermission("Only the system can create users");
Kenny Guy2a764942014-04-02 13:29:20 +01001368 return createUserInternal(name, flags, userId);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001369 }
1370
Amith Yamasani258848d2012-08-10 17:06:33 -07001371 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07001372 public UserInfo createUser(String name, int flags) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001373 checkManageUsersPermission("Only the system can create users");
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001374 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001375 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001376
Jessica Hummelbe81c802014-04-22 15:49:22 +01001377 private UserInfo createUserInternal(String name, int flags, int parentId) {
Julia Reynolds75175022014-06-26 16:35:00 -04001378 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1379 UserManager.DISALLOW_ADD_USER, false)) {
1380 Log.w(LOG_TAG, "Cannot add user. DISALLOW_ADD_USER is enabled.");
1381 return null;
1382 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001383 if (ActivityManager.isLowRamDeviceStatic()) {
1384 return null;
1385 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07001386 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001387 final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001388 final boolean isRestricted = (flags & UserInfo.FLAG_RESTRICTED) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001389 final long ident = Binder.clearCallingIdentity();
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001390 UserInfo userInfo = null;
Amith Yamasanibb054c92015-07-09 14:16:27 -07001391 final int userId;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001392 try {
1393 synchronized (mInstallLock) {
1394 synchronized (mPackagesLock) {
Jessica Hummelbe81c802014-04-22 15:49:22 +01001395 UserInfo parent = null;
1396 if (parentId != UserHandle.USER_NULL) {
1397 parent = getUserInfoLocked(parentId);
1398 if (parent == null) return null;
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001399 }
Nicolas Prevotb8186812015-08-06 15:00:03 +01001400 if (isManagedProfile && !canAddMoreManagedProfiles(parentId)) {
1401 Log.e(LOG_TAG, "Cannot add more managed profiles for user " + parentId);
Nicolas Prevot12678a92015-05-13 12:15:03 -07001402 return null;
1403 }
1404 if (!isGuest && !isManagedProfile && isUserLimitReachedLocked()) {
1405 // If we're not adding a guest user or a managed profile and the limit has
1406 // been reached, cannot add a user.
Amith Yamasani95ab7842014-08-11 17:09:26 -07001407 return null;
1408 }
1409 // If we're adding a guest and there already exists one, bail.
Adam Lesinskieddeb492014-09-08 17:50:03 -07001410 if (isGuest && findCurrentGuestUserLocked() != null) {
Amith Yamasani95ab7842014-08-11 17:09:26 -07001411 return null;
1412 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001413 // In legacy mode, restricted profile's parent can only be the owner user
1414 if (isRestricted && !UserManager.isSplitSystemUser()
1415 && (parentId != UserHandle.USER_SYSTEM)) {
1416 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
1417 return null;
1418 }
1419 if (isRestricted && UserManager.isSplitSystemUser()) {
1420 if (parent == null) {
1421 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be "
1422 + "specified");
1423 return null;
1424 }
1425 if (!parent.canHaveProfile()) {
1426 Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be "
1427 + "created for the specified parent user id " + parentId);
1428 return null;
1429 }
1430 }
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001431 // In split system user mode, we assign the first human user the primary flag.
Xiaohui Chen203243a2015-07-16 11:55:47 -07001432 // And if there is no device owner, we also assign the admin flag to primary
1433 // user.
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001434 if (UserManager.isSplitSystemUser()
Xiaohui Chen203243a2015-07-16 11:55:47 -07001435 && !isGuest && !isManagedProfile && getPrimaryUser() == null) {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001436 flags |= UserInfo.FLAG_PRIMARY;
Xiaohui Chen203243a2015-07-16 11:55:47 -07001437 DevicePolicyManager devicePolicyManager = (DevicePolicyManager)
1438 mContext.getSystemService(Context.DEVICE_POLICY_SERVICE);
1439 if (devicePolicyManager == null
1440 || devicePolicyManager.getDeviceOwner() == null) {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001441 flags |= UserInfo.FLAG_ADMIN;
1442 }
1443 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07001444 userId = getNextAvailableIdLocked();
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001445 userInfo = new UserInfo(userId, name, null, flags);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001446 userInfo.serialNumber = mNextSerialNumber++;
Amith Yamasani920ace02012-09-20 22:15:37 -07001447 long now = System.currentTimeMillis();
1448 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001449 userInfo.partial = true;
Amith Yamasani16389312012-10-17 21:20:14 -07001450 Environment.getUserSystemDirectory(userInfo.id).mkdirs();
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001451 mUsers.put(userId, userInfo);
1452 writeUserListLocked();
Jessica Hummelbe81c802014-04-22 15:49:22 +01001453 if (parent != null) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001454 if (isManagedProfile) {
1455 if (parent.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
1456 parent.profileGroupId = parent.id;
1457 scheduleWriteUserLocked(parent);
1458 }
1459 userInfo.profileGroupId = parent.profileGroupId;
1460 } else if (isRestricted) {
1461 if (!parent.canHaveProfile()) {
1462 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
1463 }
1464 if (parent.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) {
1465 parent.restrictedProfileParentId = parent.id;
1466 scheduleWriteUserLocked(parent);
1467 }
1468 userInfo.restrictedProfileParentId = parent.restrictedProfileParentId;
Kenny Guya52dc3e2014-02-11 15:33:14 +00001469 }
Kenny Guya52dc3e2014-02-11 15:33:14 +00001470 }
Jeff Sharkey6dce4962015-07-03 18:08:41 -07001471 final StorageManager storage = mContext.getSystemService(StorageManager.class);
1472 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
1473 final String volumeUuid = vol.getFsUuid();
1474 try {
1475 final File userDir = Environment.getDataUserDirectory(volumeUuid,
1476 userId);
Jeff Sharkey3bb8c852015-07-06 16:44:23 -07001477 prepareUserDirectory(mContext, volumeUuid, userId);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07001478 enforceSerialNumber(userDir, userInfo.serialNumber);
1479 } catch (IOException e) {
1480 Log.wtf(LOG_TAG, "Failed to create user directory on " + volumeUuid, e);
1481 }
1482 }
1483 mPm.createNewUserLILPw(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001484 userInfo.partial = false;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001485 scheduleWriteUserLocked(userInfo);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001486 updateUserIdsLocked();
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001487 Bundle restrictions = new Bundle();
Makoto Onuki068c54a2015-10-13 14:34:03 -07001488 synchronized (mRestrictionsLock) {
1489 mBaseUserRestrictions.append(userId, restrictions);
1490 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001491 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07001492 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07001493 mPm.newUserCreated(userId);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001494 if (userInfo != null) {
1495 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
1496 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userInfo.id);
1497 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
1498 android.Manifest.permission.MANAGE_USERS);
1499 }
1500 } finally {
1501 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07001502 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001503 return userInfo;
1504 }
1505
Amith Yamasani0b285492011-04-14 17:35:23 -07001506 /**
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07001507 * @hide
1508 */
1509 public UserInfo createRestrictedProfile(String name, int parentUserId) {
1510 checkManageUsersPermission("setupRestrictedProfile");
1511 final UserInfo user = createProfileForUser(name, UserInfo.FLAG_RESTRICTED, parentUserId);
1512 if (user == null) {
1513 return null;
1514 }
1515 setUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, true, user.id);
1516 // Change the setting before applying the DISALLOW_SHARE_LOCATION restriction, otherwise
1517 // the putIntForUser() will fail.
1518 android.provider.Settings.Secure.putIntForUser(mContext.getContentResolver(),
1519 android.provider.Settings.Secure.LOCATION_MODE,
1520 android.provider.Settings.Secure.LOCATION_MODE_OFF, user.id);
1521 setUserRestriction(UserManager.DISALLOW_SHARE_LOCATION, true, user.id);
1522 return user;
1523 }
1524
1525 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07001526 * Find the current guest user. If the Guest user is partial,
1527 * then do not include it in the results as it is about to die.
Adam Lesinskieddeb492014-09-08 17:50:03 -07001528 */
1529 private UserInfo findCurrentGuestUserLocked() {
1530 final int size = mUsers.size();
1531 for (int i = 0; i < size; i++) {
1532 final UserInfo user = mUsers.valueAt(i);
1533 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
1534 return user;
1535 }
1536 }
1537 return null;
1538 }
1539
1540 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07001541 * Mark this guest user for deletion to allow us to create another guest
1542 * and switch to that user before actually removing this guest.
1543 * @param userHandle the userid of the current guest
1544 * @return whether the user could be marked for deletion
1545 */
1546 public boolean markGuestForDeletion(int userHandle) {
1547 checkManageUsersPermission("Only the system can remove users");
1548 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1549 UserManager.DISALLOW_REMOVE_USER, false)) {
1550 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1551 return false;
1552 }
1553
1554 long ident = Binder.clearCallingIdentity();
1555 try {
1556 final UserInfo user;
1557 synchronized (mPackagesLock) {
1558 user = mUsers.get(userHandle);
1559 if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
1560 return false;
1561 }
1562 if (!user.isGuest()) {
1563 return false;
1564 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001565 // We set this to a guest user that is to be removed. This is a temporary state
1566 // where we are allowed to add new Guest users, even if this one is still not
1567 // removed. This user will still show up in getUserInfo() calls.
1568 // If we don't get around to removing this Guest user, it will be purged on next
1569 // startup.
1570 user.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07001571 // Mark it as disabled, so that it isn't returned any more when
1572 // profiles are queried.
1573 user.flags |= UserInfo.FLAG_DISABLED;
Amith Yamasani1df14732014-08-29 21:37:27 -07001574 writeUserLocked(user);
1575 }
1576 } finally {
1577 Binder.restoreCallingIdentity(ident);
1578 }
1579 return true;
1580 }
1581
1582 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07001583 * Removes a user and all data directories created for that user. This method should be called
1584 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001585 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07001586 */
Amith Yamasani258848d2012-08-10 17:06:33 -07001587 public boolean removeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001588 checkManageUsersPermission("Only the system can remove users");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04001589 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1590 UserManager.DISALLOW_REMOVE_USER, false)) {
1591 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1592 return false;
1593 }
1594
Kenny Guyee58b4f2014-05-23 15:19:53 +01001595 long ident = Binder.clearCallingIdentity();
1596 try {
1597 final UserInfo user;
Fyodor Kupolov0df68cd2015-10-01 13:54:22 -07001598 int currentUser = ActivityManager.getCurrentUser();
1599 if (currentUser == userHandle) {
1600 Log.w(LOG_TAG, "Current user cannot be removed");
1601 return false;
1602 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01001603 synchronized (mPackagesLock) {
1604 user = mUsers.get(userHandle);
Kenny Guy17c9d692014-06-13 13:51:42 +01001605 if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01001606 return false;
1607 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08001608
1609 // We remember deleted user IDs to prevent them from being
1610 // reused during the current boot; they can still be reused
1611 // after a reboot.
Kenny Guyee58b4f2014-05-23 15:19:53 +01001612 mRemovingUserIds.put(userHandle, true);
Jeff Sharkey6eb09392014-11-14 15:57:59 -08001613
Kenny Guyee58b4f2014-05-23 15:19:53 +01001614 try {
1615 mAppOpsService.removeUser(userHandle);
1616 } catch (RemoteException e) {
1617 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
1618 }
1619 // Set this to a partially created user, so that the user will be purged
1620 // on next startup, in case the runtime stops now before stopping and
1621 // removing the user completely.
1622 user.partial = true;
1623 // Mark it as disabled, so that it isn't returned any more when
1624 // profiles are queried.
1625 user.flags |= UserInfo.FLAG_DISABLED;
1626 writeUserLocked(user);
1627 }
1628
1629 if (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
1630 && user.isManagedProfile()) {
1631 // Send broadcast to notify system that the user removed was a
1632 // managed user.
1633 sendProfileRemovedBroadcast(user.profileGroupId, user.id);
1634 }
1635
1636 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
1637 int res;
1638 try {
1639 res = ActivityManagerNative.getDefault().stopUser(userHandle,
1640 new IStopUserCallback.Stub() {
1641 @Override
1642 public void userStopped(int userId) {
1643 finishRemoveUser(userId);
1644 }
1645 @Override
1646 public void userStopAborted(int userId) {
1647 }
1648 });
1649 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001650 return false;
1651 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01001652 return res == ActivityManager.USER_OP_SUCCESS;
1653 } finally {
1654 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001655 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001656 }
1657
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001658 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07001659 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001660 // Let other services shutdown any activity and clean up their state before completely
1661 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001662 long ident = Binder.clearCallingIdentity();
1663 try {
1664 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
1665 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001666 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
1667 android.Manifest.permission.MANAGE_USERS,
1668
1669 new BroadcastReceiver() {
1670 @Override
1671 public void onReceive(Context context, Intent intent) {
1672 if (DBG) {
1673 Slog.i(LOG_TAG,
1674 "USER_REMOVED broadcast sent, cleaning up user data "
1675 + userHandle);
1676 }
1677 new Thread() {
1678 public void run() {
Amith Yamasani515d4062015-09-28 11:30:06 -07001679 // Clean up any ActivityManager state
1680 LocalServices.getService(ActivityManagerInternal.class)
1681 .onUserRemoved(userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001682 synchronized (mInstallLock) {
1683 synchronized (mPackagesLock) {
1684 removeUserStateLocked(userHandle);
1685 }
1686 }
1687 }
1688 }.start();
1689 }
1690 },
1691
1692 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001693 } finally {
1694 Binder.restoreCallingIdentity(ident);
1695 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001696 }
1697
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001698 private void removeUserStateLocked(final int userHandle) {
Paul Crowley85e4e812015-05-19 12:42:00 +01001699 mContext.getSystemService(StorageManager.class)
1700 .deleteUserKey(userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001701 // Cleanup package manager settings
Amith Yamasanidda003f2014-08-28 18:06:51 -07001702 mPm.cleanUpUserLILPw(this, userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001703
1704 // Remove this user from the list
1705 mUsers.remove(userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001706 // Remove user file
Amith Yamasanifc95e702013-09-26 13:20:17 -07001707 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001708 userFile.delete();
1709 // Update the user list
1710 writeUserListLocked();
1711 updateUserIdsLocked();
1712 removeDirectoryRecursive(Environment.getUserSystemDirectory(userHandle));
1713 }
1714
Amith Yamasani61f57372012-08-31 12:12:28 -07001715 private void removeDirectoryRecursive(File parent) {
1716 if (parent.isDirectory()) {
1717 String[] files = parent.list();
1718 for (String filename : files) {
1719 File child = new File(parent, filename);
1720 removeDirectoryRecursive(child);
1721 }
1722 }
1723 parent.delete();
1724 }
1725
Kenny Guyf8d3a232014-05-15 16:09:52 +01001726 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01001727 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01001728 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
1729 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01001730 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
1731 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01001732 }
1733
Amith Yamasani2a003292012-08-14 18:25:45 -07001734 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001735 public Bundle getApplicationRestrictions(String packageName) {
1736 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
1737 }
1738
1739 @Override
1740 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001741 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07001742 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Esteban Talavera2a5d6c62015-10-21 10:55:56 +01001743 checkManageUsersPermission("get application restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001744 }
1745 synchronized (mPackagesLock) {
1746 // Read the restrictions from XML
1747 return readApplicationRestrictionsLocked(packageName, userId);
1748 }
1749 }
1750
1751 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001752 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001753 int userId) {
Esteban Talavera2a5d6c62015-10-21 10:55:56 +01001754 checkManageUsersPermission("set application restrictions");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001755 synchronized (mPackagesLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01001756 if (restrictions == null || restrictions.isEmpty()) {
1757 cleanAppRestrictionsForPackage(packageName, userId);
1758 } else {
1759 // Write the restrictions to XML
1760 writeApplicationRestrictionsLocked(packageName, restrictions, userId);
1761 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001762 }
Robin Lee66e5d962014-04-09 16:44:21 +01001763
Kenny Guyd21b2182014-07-17 16:38:55 +01001764 if (isPackageInstalled(packageName, userId)) {
1765 // Notify package of changes via an intent - only sent to explicitly registered receivers.
1766 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
1767 changeIntent.setPackage(packageName);
1768 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
1769 mContext.sendBroadcastAsUser(changeIntent, new UserHandle(userId));
1770 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001771 }
1772
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001773 private void unhideAllInstalledAppsForUser(final int userHandle) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001774 mHandler.post(new Runnable() {
1775 @Override
1776 public void run() {
1777 List<ApplicationInfo> apps =
1778 mPm.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES,
1779 userHandle).getList();
1780 final long ident = Binder.clearCallingIdentity();
1781 try {
1782 for (ApplicationInfo appInfo : apps) {
1783 if ((appInfo.flags & ApplicationInfo.FLAG_INSTALLED) != 0
Alex Klyubinb9f8a522015-02-03 11:12:59 -08001784 && (appInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HIDDEN)
1785 != 0) {
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001786 mPm.setApplicationHiddenSettingAsUser(appInfo.packageName, false,
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001787 userHandle);
1788 }
1789 }
1790 } finally {
1791 Binder.restoreCallingIdentity(ident);
1792 }
1793 }
1794 });
1795 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001796 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07001797 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001798 try {
1799 return mContext.getPackageManager().getApplicationInfo(packageName,
1800 PackageManager.GET_UNINSTALLED_PACKAGES).uid;
1801 } catch (NameNotFoundException nnfe) {
1802 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07001803 } finally {
1804 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001805 }
1806 }
1807
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001808 private Bundle readApplicationRestrictionsLocked(String packageName,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001809 int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001810 AtomicFile restrictionsFile =
1811 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
1812 packageToRestrictionsFileName(packageName)));
1813 return readApplicationRestrictionsLocked(restrictionsFile);
1814 }
1815
1816 @VisibleForTesting
1817 static Bundle readApplicationRestrictionsLocked(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001818 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001819 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07001820 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07001821 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07001822 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001823
1824 FileInputStream fis = null;
1825 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001826 fis = restrictionsFile.openRead();
1827 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001828 parser.setInput(fis, StandardCharsets.UTF_8.name());
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001829 XmlUtils.nextElement(parser);
1830 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001831 Slog.e(LOG_TAG, "Unable to read restrictions file "
1832 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001833 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001834 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001835 while (parser.next() != XmlPullParser.END_DOCUMENT) {
1836 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001837 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001838 } catch (IOException|XmlPullParserException e) {
1839 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001840 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001841 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001842 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001843 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001844 }
1845
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001846 private static void readEntry(Bundle restrictions, ArrayList<String> values,
1847 XmlPullParser parser) throws XmlPullParserException, IOException {
1848 int type = parser.getEventType();
1849 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
1850 String key = parser.getAttributeValue(null, ATTR_KEY);
1851 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
1852 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
1853 if (multiple != null) {
1854 values.clear();
1855 int count = Integer.parseInt(multiple);
1856 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1857 if (type == XmlPullParser.START_TAG
1858 && parser.getName().equals(TAG_VALUE)) {
1859 values.add(parser.nextText().trim());
1860 count--;
1861 }
1862 }
1863 String [] valueStrings = new String[values.size()];
1864 values.toArray(valueStrings);
1865 restrictions.putStringArray(key, valueStrings);
1866 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
1867 restrictions.putBundle(key, readBundleEntry(parser, values));
1868 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
1869 final int outerDepth = parser.getDepth();
1870 ArrayList<Bundle> bundleList = new ArrayList<>();
1871 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
1872 Bundle childBundle = readBundleEntry(parser, values);
1873 bundleList.add(childBundle);
1874 }
1875 restrictions.putParcelableArray(key,
1876 bundleList.toArray(new Bundle[bundleList.size()]));
1877 } else {
1878 String value = parser.nextText().trim();
1879 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
1880 restrictions.putBoolean(key, Boolean.parseBoolean(value));
1881 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
1882 restrictions.putInt(key, Integer.parseInt(value));
1883 } else {
1884 restrictions.putString(key, value);
1885 }
1886 }
1887 }
1888 }
1889
1890 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
1891 throws IOException, XmlPullParserException {
1892 Bundle childBundle = new Bundle();
1893 final int outerDepth = parser.getDepth();
1894 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
1895 readEntry(childBundle, values, parser);
1896 }
1897 return childBundle;
1898 }
1899
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001900 private void writeApplicationRestrictionsLocked(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001901 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001902 AtomicFile restrictionsFile = new AtomicFile(
1903 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07001904 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001905 writeApplicationRestrictionsLocked(restrictions, restrictionsFile);
1906 }
1907
1908 @VisibleForTesting
1909 static void writeApplicationRestrictionsLocked(Bundle restrictions,
1910 AtomicFile restrictionsFile) {
1911 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001912 try {
1913 fos = restrictionsFile.startWrite();
1914 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1915
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001916 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001917 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001918 serializer.startDocument(null, true);
1919 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1920
1921 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001922 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001923 serializer.endTag(null, TAG_RESTRICTIONS);
1924
1925 serializer.endDocument();
1926 restrictionsFile.finishWrite(fos);
1927 } catch (Exception e) {
1928 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001929 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
1930 }
1931 }
1932
1933 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
1934 throws IOException {
1935 for (String key : restrictions.keySet()) {
1936 Object value = restrictions.get(key);
1937 serializer.startTag(null, TAG_ENTRY);
1938 serializer.attribute(null, ATTR_KEY, key);
1939
1940 if (value instanceof Boolean) {
1941 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
1942 serializer.text(value.toString());
1943 } else if (value instanceof Integer) {
1944 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
1945 serializer.text(value.toString());
1946 } else if (value == null || value instanceof String) {
1947 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
1948 serializer.text(value != null ? (String) value : "");
1949 } else if (value instanceof Bundle) {
1950 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
1951 writeBundle((Bundle) value, serializer);
1952 } else if (value instanceof Parcelable[]) {
1953 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
1954 Parcelable[] array = (Parcelable[]) value;
1955 for (Parcelable parcelable : array) {
1956 if (!(parcelable instanceof Bundle)) {
1957 throw new IllegalArgumentException("bundle-array can only hold Bundles");
1958 }
1959 serializer.startTag(null, TAG_ENTRY);
1960 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
1961 writeBundle((Bundle) parcelable, serializer);
1962 serializer.endTag(null, TAG_ENTRY);
1963 }
1964 } else {
1965 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
1966 String[] values = (String[]) value;
1967 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
1968 for (String choice : values) {
1969 serializer.startTag(null, TAG_VALUE);
1970 serializer.text(choice != null ? choice : "");
1971 serializer.endTag(null, TAG_VALUE);
1972 }
1973 }
1974 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001975 }
1976 }
1977
1978 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07001979 public int getUserSerialNumber(int userHandle) {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001980 synchronized (mPackagesLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001981 if (!exists(userHandle)) return -1;
Amith Yamasani195263742012-08-21 15:40:12 -07001982 return getUserInfoLocked(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07001983 }
1984 }
1985
1986 @Override
1987 public int getUserHandle(int userSerialNumber) {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001988 synchronized (mPackagesLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001989 for (int userId : mUserIds) {
Kenny Guy945f8832015-02-10 15:17:26 +00001990 UserInfo info = getUserInfoLocked(userId);
1991 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07001992 }
1993 // Not found
1994 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07001995 }
1996 }
1997
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07001998 @Override
1999 public long getUserCreationTime(int userHandle) {
2000 int callingUserId = UserHandle.getCallingUserId();
2001 UserInfo userInfo = null;
2002 synchronized (mPackagesLock) {
2003 if (callingUserId == userHandle) {
2004 userInfo = getUserInfoLocked(userHandle);
2005 } else {
2006 UserInfo parent = getProfileParentLocked(userHandle);
2007 if (parent != null && parent.id == callingUserId) {
2008 userInfo = getUserInfoLocked(userHandle);
2009 }
2010 }
2011 }
2012 if (userInfo == null) {
2013 throw new SecurityException("userHandle can only be the calling user or a managed "
2014 + "profile associated with this user");
2015 }
2016 return userInfo.creationTime;
2017 }
2018
Amith Yamasani0b285492011-04-14 17:35:23 -07002019 /**
2020 * Caches the list of user ids in an array, adjusting the array size when necessary.
2021 */
Amith Yamasani13593602012-03-22 16:16:17 -07002022 private void updateUserIdsLocked() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002023 int num = 0;
Amith Yamasani515d4062015-09-28 11:30:06 -07002024 final int userSize = mUsers.size();
2025 for (int i = 0; i < userSize; i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002026 if (!mUsers.valueAt(i).partial) {
2027 num++;
2028 }
2029 }
Amith Yamasani16389312012-10-17 21:20:14 -07002030 final int[] newUsers = new int[num];
2031 int n = 0;
Amith Yamasani515d4062015-09-28 11:30:06 -07002032 for (int i = 0; i < userSize; i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002033 if (!mUsers.valueAt(i).partial) {
Amith Yamasani16389312012-10-17 21:20:14 -07002034 newUsers[n++] = mUsers.keyAt(i);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002035 }
Amith Yamasani0b285492011-04-14 17:35:23 -07002036 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07002037 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07002038 }
2039
2040 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002041 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasani920ace02012-09-20 22:15:37 -07002042 * @param userId the user that was just foregrounded
2043 */
Amith Yamasani06bf8242015-05-08 16:36:21 -07002044 public void onUserForeground(int userId) {
Amith Yamasani920ace02012-09-20 22:15:37 -07002045 synchronized (mPackagesLock) {
2046 UserInfo user = mUsers.get(userId);
2047 long now = System.currentTimeMillis();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002048 if (user == null || user.partial) {
2049 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
2050 return;
2051 }
2052 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani920ace02012-09-20 22:15:37 -07002053 user.lastLoggedInTime = now;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002054 scheduleWriteUserLocked(user);
Amith Yamasani920ace02012-09-20 22:15:37 -07002055 }
2056 }
2057 }
2058
2059 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002060 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani742a6712011-05-04 14:49:28 -07002061 * TODO: May not be a good idea to recycle ids, in case it results in confusion
2062 * for data and battery stats collection, or unexpected cross-talk.
Amith Yamasani0b285492011-04-14 17:35:23 -07002063 * @return
2064 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002065 private int getNextAvailableIdLocked() {
Dianne Hackborn4428e172012-08-24 17:43:05 -07002066 synchronized (mPackagesLock) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002067 int i = MIN_USER_ID;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002068 while (i < MAX_USER_ID) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002069 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002070 return i;
Amith Yamasani195263742012-08-21 15:40:12 -07002071 }
2072 i++;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002073 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002074 }
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002075 throw new IllegalStateException("No user id available!");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002076 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002077
Amith Yamasanifc95e702013-09-26 13:20:17 -07002078 private String packageToRestrictionsFileName(String packageName) {
2079 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
2080 }
2081
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002082 /**
2083 * Create new {@code /data/user/[id]} directory and sets default
2084 * permissions.
2085 */
Jeff Sharkey3bb8c852015-07-06 16:44:23 -07002086 public static void prepareUserDirectory(Context context, String volumeUuid, int userId) {
2087 final StorageManager storage = context.getSystemService(StorageManager.class);
2088 final File userDir = Environment.getDataUserDirectory(volumeUuid, userId);
2089 storage.createNewUserDir(userId, userDir);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002090 }
2091
2092 /**
2093 * Enforce that serial number stored in user directory inode matches the
2094 * given expected value. Gracefully sets the serial number if currently
2095 * undefined.
2096 *
2097 * @throws IOException when problem extracting serial number, or serial
2098 * number is mismatched.
2099 */
2100 public static void enforceSerialNumber(File file, int serialNumber) throws IOException {
2101 final int foundSerial = getSerialNumber(file);
2102 Slog.v(LOG_TAG, "Found " + file + " with serial number " + foundSerial);
2103
2104 if (foundSerial == -1) {
2105 Slog.d(LOG_TAG, "Serial number missing on " + file + "; assuming current is valid");
2106 try {
2107 setSerialNumber(file, serialNumber);
2108 } catch (IOException e) {
2109 Slog.w(LOG_TAG, "Failed to set serial number on " + file, e);
2110 }
2111
2112 } else if (foundSerial != serialNumber) {
2113 throw new IOException("Found serial number " + foundSerial
2114 + " doesn't match expected " + serialNumber);
2115 }
2116 }
2117
2118 /**
2119 * Set serial number stored in user directory inode.
2120 *
2121 * @throws IOException if serial number was already set
2122 */
2123 private static void setSerialNumber(File file, int serialNumber)
2124 throws IOException {
2125 try {
2126 final byte[] buf = Integer.toString(serialNumber).getBytes(StandardCharsets.UTF_8);
2127 Os.setxattr(file.getAbsolutePath(), XATTR_SERIAL, buf, OsConstants.XATTR_CREATE);
2128 } catch (ErrnoException e) {
2129 throw e.rethrowAsIOException();
2130 }
2131 }
2132
2133 /**
2134 * Return serial number stored in user directory inode.
2135 *
2136 * @return parsed serial number, or -1 if not set
2137 */
2138 private static int getSerialNumber(File file) throws IOException {
2139 try {
2140 final byte[] buf = new byte[256];
2141 final int len = Os.getxattr(file.getAbsolutePath(), XATTR_SERIAL, buf);
2142 final String serial = new String(buf, 0, len);
2143 try {
2144 return Integer.parseInt(serial);
2145 } catch (NumberFormatException e) {
2146 throw new IOException("Bad serial number: " + serial);
2147 }
2148 } catch (ErrnoException e) {
2149 if (e.errno == OsConstants.ENODATA) {
2150 return -1;
2151 } else {
2152 throw e.rethrowAsIOException();
2153 }
2154 }
2155 }
2156
Amith Yamasani920ace02012-09-20 22:15:37 -07002157 @Override
2158 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2159 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2160 != PackageManager.PERMISSION_GRANTED) {
2161 pw.println("Permission Denial: can't dump UserManager from from pid="
2162 + Binder.getCallingPid()
2163 + ", uid=" + Binder.getCallingUid()
2164 + " without permission "
2165 + android.Manifest.permission.DUMP);
2166 return;
2167 }
2168
2169 long now = System.currentTimeMillis();
2170 StringBuilder sb = new StringBuilder();
2171 synchronized (mPackagesLock) {
2172 pw.println("Users:");
2173 for (int i = 0; i < mUsers.size(); i++) {
2174 UserInfo user = mUsers.valueAt(i);
2175 if (user == null) continue;
Amith Yamasani634cf312012-10-04 17:34:21 -07002176 pw.print(" "); pw.print(user); pw.print(" serialNo="); pw.print(user.serialNumber);
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002177 if (mRemovingUserIds.get(mUsers.keyAt(i))) pw.print(" <removing> ");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002178 if (user.partial) pw.print(" <partial>");
2179 pw.println();
Amith Yamasani920ace02012-09-20 22:15:37 -07002180 pw.print(" Created: ");
2181 if (user.creationTime == 0) {
2182 pw.println("<unknown>");
2183 } else {
2184 sb.setLength(0);
2185 TimeUtils.formatDuration(now - user.creationTime, sb);
2186 sb.append(" ago");
2187 pw.println(sb);
2188 }
2189 pw.print(" Last logged in: ");
2190 if (user.lastLoggedInTime == 0) {
2191 pw.println("<unknown>");
2192 } else {
2193 sb.setLength(0);
2194 TimeUtils.formatDuration(now - user.lastLoggedInTime, sb);
2195 sb.append(" ago");
2196 pw.println(sb);
2197 }
Makoto Onukia4f11972015-10-01 13:19:58 -07002198 pw.println(" Restrictions:");
2199 UserRestrictionsUtils.dumpRestrictions(
Makoto Onuki068c54a2015-10-13 14:34:03 -07002200 pw, " ", mBaseUserRestrictions.get(user.id));
2201 pw.println(" Effective restrictions:");
2202 UserRestrictionsUtils.dumpRestrictions(
2203 pw, " ", mCachedEffectiveUserRestrictions.get(user.id));
Amith Yamasani920ace02012-09-20 22:15:37 -07002204 }
Makoto Onukia4f11972015-10-01 13:19:58 -07002205 pw.println();
2206 pw.println("Guest restrictions:");
2207 UserRestrictionsUtils.dumpRestrictions(pw, " ", mGuestRestrictions);
Amith Yamasani920ace02012-09-20 22:15:37 -07002208 }
2209 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002210
2211 final class MainHandler extends Handler {
2212
2213 @Override
2214 public void handleMessage(Message msg) {
2215 switch (msg.what) {
2216 case WRITE_USER_MSG:
2217 removeMessages(WRITE_USER_MSG, msg.obj);
2218 synchronized (mPackagesLock) {
2219 int userId = ((UserInfo) msg.obj).id;
2220 UserInfo userInfo = mUsers.get(userId);
2221 if (userInfo != null) {
2222 writeUserLocked(userInfo);
2223 }
2224 }
2225 }
2226 }
2227 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07002228
2229 /**
2230 * @param userId
2231 * @return whether the user has been initialized yet
2232 */
2233 boolean isInitialized(int userId) {
2234 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
2235 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07002236
2237 private class LocalService extends UserManagerInternal {
2238
2239 @Override
2240 public Object getUserRestrictionsLock() {
2241 return mRestrictionsLock;
2242 }
2243
2244 @Override
2245 @GuardedBy("mRestrictionsLock")
2246 public void updateEffectiveUserRestrictionsRL(int userId) {
2247 UserManagerService.this.updateEffectiveUserRestrictionsRL(userId);
2248 }
2249
2250 @Override
2251 @GuardedBy("mRestrictionsLock")
2252 public void updateEffectiveUserRestrictionsForAllUsersRL() {
2253 UserManagerService.this.updateEffectiveUserRestrictionsForAllUsersRL();
2254 }
2255
2256 @Override
2257 public Bundle getBaseUserRestrictions(int userId) {
2258 synchronized (mRestrictionsLock) {
2259 return mBaseUserRestrictions.get(userId);
2260 }
2261 }
2262
2263 @Override
2264 public void setBaseUserRestrictionsByDpmsForMigration(
2265 int userId, Bundle baseRestrictions) {
2266 synchronized (mRestrictionsLock) {
2267 mBaseUserRestrictions.put(userId, new Bundle(baseRestrictions));
2268 invalidateEffectiveUserRestrictionsRL(userId);
2269 }
2270
2271 synchronized (mPackagesLock) {
2272 final UserInfo userInfo = mUsers.get(userId);
2273 if (userInfo != null) {
2274 writeUserLocked(userInfo);
2275 } else {
2276 Slog.w(LOG_TAG, "UserInfo not found for " + userId);
2277 }
2278 }
2279 }
2280 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002281}