blob: d128252e8063156c7aefc9c069b14021c8682911 [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
Benjamin Franzf02420c2016-04-04 18:52:21 +010019import static android.content.Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS;
20import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
21
Xiaohui Chenb3b92582015-12-07 11:22:13 -080022import android.Manifest;
Xiaohui Chen594f2082015-08-18 11:04:20 -070023import android.annotation.NonNull;
Makoto Onuki068c54a2015-10-13 14:34:03 -070024import android.annotation.Nullable;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -060025import android.annotation.UserIdInt;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070026import android.app.Activity;
Amith Yamasani2a003292012-08-14 18:25:45 -070027import android.app.ActivityManager;
Amith Yamasani515d4062015-09-28 11:30:06 -070028import android.app.ActivityManagerInternal;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070029import android.app.ActivityManagerNative;
Amith Yamasanieb437d42016-04-29 09:31:25 -070030import android.app.AppGlobals;
Todd Kennedy60459ab2015-10-30 11:32:16 -070031import android.app.IActivityManager;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070032import android.app.IStopUserCallback;
Benjamin Franzf02420c2016-04-04 18:52:21 +010033import android.app.KeyguardManager;
Ricky Waib1dd80b2016-06-07 18:00:55 +010034import android.app.PendingIntent;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070035import android.content.BroadcastReceiver;
Bart Searsc51e7252016-05-27 04:12:51 +000036import android.content.ComponentName;
Amith Yamasani258848d2012-08-10 17:06:33 -070037import android.content.Context;
38import android.content.Intent;
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +010039import android.content.IntentFilter;
Benjamin Franzf02420c2016-04-04 18:52:21 +010040import android.content.IntentSender;
Amith Yamasani0b285492011-04-14 17:35:23 -070041import android.content.pm.PackageManager;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -080042import android.content.pm.PackageManager.NameNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070043import android.content.pm.UserInfo;
Lenka Trochtova02fee152015-12-22 14:26:18 +010044import android.content.res.Resources;
Amith Yamasanie928d7d2012-09-17 21:46:51 -070045import android.graphics.Bitmap;
Amith Yamasani258848d2012-08-10 17:06:33 -070046import android.os.Binder;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -060047import android.os.Build;
Amith Yamasanie4cf7342012-12-17 11:12:09 -080048import android.os.Bundle;
Makoto Onuki1a2cd742015-11-16 13:51:27 -080049import android.os.Debug;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070050import android.os.Environment;
51import android.os.FileUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080052import android.os.Handler;
Svet Ganov9cea80cd2016-02-16 11:47:00 -080053import android.os.IBinder;
Amith Yamasani258848d2012-08-10 17:06:33 -070054import android.os.IUserManager;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -080055import android.os.Message;
Adrian Roos1bdff912015-02-17 15:51:35 +010056import android.os.ParcelFileDescriptor;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070057import android.os.Parcelable;
Amith Yamasani12747872015-12-07 14:19:49 -080058import android.os.PersistableBundle;
Amith Yamasani258848d2012-08-10 17:06:33 -070059import android.os.Process;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070060import android.os.RemoteException;
Todd Kennedy60459ab2015-10-30 11:32:16 -070061import android.os.ResultReceiver;
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +010062import android.os.SELinux;
Jason Monk62062992014-05-06 09:55:28 -040063import android.os.ServiceManager;
Todd Kennedy60459ab2015-10-30 11:32:16 -070064import android.os.ShellCommand;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070065import android.os.UserHandle;
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070066import android.os.UserManager;
Makoto Onuki068c54a2015-10-13 14:34:03 -070067import android.os.UserManagerInternal;
Makoto Onukid45a4a22015-11-02 17:17:38 -080068import android.os.UserManagerInternal.UserRestrictionsListener;
Paul Crowley85e4e812015-05-19 12:42:00 +010069import android.os.storage.StorageManager;
Amith Yamasanid04aaa32016-06-13 12:09:36 -070070import android.security.GateKeeper;
71import android.service.gatekeeper.IGateKeeperService;
Jeff Sharkey6dce4962015-07-03 18:08:41 -070072import android.system.ErrnoException;
73import android.system.Os;
74import android.system.OsConstants;
Amith Yamasanieb437d42016-04-29 09:31:25 -070075import android.text.TextUtils;
Amith Yamasani2a003292012-08-14 18:25:45 -070076import android.util.AtomicFile;
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -070077import android.util.IntArray;
Amith Yamasani655d0e22013-06-12 14:19:10 -070078import android.util.Log;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070079import android.util.Slog;
80import android.util.SparseArray;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080081import android.util.SparseBooleanArray;
Amith Yamasaniea1b9d72016-05-27 15:57:38 +000082import android.util.SparseIntArray;
Amith Yamasani920ace02012-09-20 22:15:37 -070083import android.util.TimeUtils;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070084import android.util.Xml;
85
Makoto Onuki068c54a2015-10-13 14:34:03 -070086import com.android.internal.annotations.GuardedBy;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070087import com.android.internal.annotations.VisibleForTesting;
Jason Monk62062992014-05-06 09:55:28 -040088import com.android.internal.app.IAppOpsService;
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -080089import com.android.internal.logging.MetricsLogger;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080090import com.android.internal.util.FastXmlSerializer;
Makoto Onuki068c54a2015-10-13 14:34:03 -070091import com.android.internal.util.Preconditions;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070092import com.android.internal.util.XmlUtils;
Clara Bayarri10ad84a2015-12-01 17:38:05 +000093import com.android.internal.widget.LockPatternUtils;
Amith Yamasani515d4062015-09-28 11:30:06 -070094import com.android.server.LocalServices;
Amith Yamasanid04aaa32016-06-13 12:09:36 -070095import com.android.server.SystemService;
Amith Yamasaniea1b9d72016-05-27 15:57:38 +000096import com.android.server.am.UserState;
Jeff Sharkey47f71082016-02-01 17:03:54 -070097
98import libcore.io.IoUtils;
99import libcore.util.Objects;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800100
101import org.xmlpull.v1.XmlPullParser;
102import org.xmlpull.v1.XmlPullParserException;
103import org.xmlpull.v1.XmlSerializer;
104
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700105import java.io.BufferedOutputStream;
106import java.io.File;
Amith Yamasani920ace02012-09-20 22:15:37 -0700107import java.io.FileDescriptor;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700108import java.io.FileInputStream;
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700109import java.io.FileNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700110import java.io.FileOutputStream;
111import java.io.IOException;
Amith Yamasani920ace02012-09-20 22:15:37 -0700112import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100113import java.nio.charset.StandardCharsets;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700114import java.util.ArrayList;
115import java.util.List;
116
Makoto Onuki068c54a2015-10-13 14:34:03 -0700117/**
118 * Service for {@link UserManager}.
119 *
120 * Method naming convention:
Fyodor Kupolov82402752015-10-28 14:54:51 -0700121 * <ul>
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800122 * <li> Methods suffixed with "LP" should be called within the {@link #mPackagesLock} lock.
Fyodor Kupolov82402752015-10-28 14:54:51 -0700123 * <li> Methods suffixed with "LR" should be called within the {@link #mRestrictionsLock} lock.
124 * <li> Methods suffixed with "LU" should be called within the {@link #mUsersLock} lock.
125 * </ul>
Makoto Onuki068c54a2015-10-13 14:34:03 -0700126 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700127public class UserManagerService extends IUserManager.Stub {
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700128
Amith Yamasani2a003292012-08-14 18:25:45 -0700129 private static final String LOG_TAG = "UserManagerService";
Makoto Onuki81c61ea2016-01-22 11:22:26 -0800130 static final boolean DBG = false; // DO NOT SUBMIT WITH TRUE
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800131 private static final boolean DBG_WITH_STACKTRACE = false; // DO NOT SUBMIT WITH TRUE
Amith Yamasani16389312012-10-17 21:20:14 -0700132
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700133 private static final String TAG_NAME = "name";
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800134 private static final String TAG_ACCOUNT = "account";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700135 private static final String ATTR_FLAGS = "flags";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700136 private static final String ATTR_ICON_PATH = "icon";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700137 private static final String ATTR_ID = "id";
Amith Yamasani920ace02012-09-20 22:15:37 -0700138 private static final String ATTR_CREATION_TIME = "created";
139 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -0600140 private static final String ATTR_LAST_LOGGED_IN_FINGERPRINT = "lastLoggedInFingerprint";
Amith Yamasani2a003292012-08-14 18:25:45 -0700141 private static final String ATTR_SERIAL_NO = "serialNumber";
142 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700143 private static final String ATTR_PARTIAL = "partial";
Adam Lesinskieddeb492014-09-08 17:50:03 -0700144 private static final String ATTR_GUEST_TO_REMOVE = "guestToRemove";
Amith Yamasani6f34b412012-10-22 18:19:27 -0700145 private static final String ATTR_USER_VERSION = "version";
Kenny Guy2a764942014-04-02 13:29:20 +0100146 private static final String ATTR_PROFILE_GROUP_ID = "profileGroupId";
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700147 private static final String ATTR_RESTRICTED_PROFILE_PARENT_ID = "restrictedProfileParentId";
Amith Yamasani12747872015-12-07 14:19:49 -0800148 private static final String ATTR_SEED_ACCOUNT_NAME = "seedAccountName";
149 private static final String ATTR_SEED_ACCOUNT_TYPE = "seedAccountType";
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530150 private static final String TAG_GUEST_RESTRICTIONS = "guestRestrictions";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700151 private static final String TAG_USERS = "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700152 private static final String TAG_USER = "user";
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800153 private static final String TAG_RESTRICTIONS = "restrictions";
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800154 private static final String TAG_DEVICE_POLICY_RESTRICTIONS = "device_policy_restrictions";
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +0100155 private static final String TAG_GLOBAL_RESTRICTION_OWNER_ID = "globalRestrictionOwnerUserId";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800156 private static final String TAG_ENTRY = "entry";
157 private static final String TAG_VALUE = "value";
Amith Yamasani12747872015-12-07 14:19:49 -0800158 private static final String TAG_SEED_ACCOUNT_OPTIONS = "seedAccountOptions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800159 private static final String ATTR_KEY = "key";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700160 private static final String ATTR_VALUE_TYPE = "type";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800161 private static final String ATTR_MULTIPLE = "m";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700162
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700163 private static final String ATTR_TYPE_STRING_ARRAY = "sa";
164 private static final String ATTR_TYPE_STRING = "s";
165 private static final String ATTR_TYPE_BOOLEAN = "b";
Amith Yamasani5b5aa402014-06-01 20:10:14 -0700166 private static final String ATTR_TYPE_INTEGER = "i";
Fyodor Kupolov262f9952015-03-23 18:55:11 -0700167 private static final String ATTR_TYPE_BUNDLE = "B";
168 private static final String ATTR_TYPE_BUNDLE_ARRAY = "BA";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700169
Amith Yamasani0b285492011-04-14 17:35:23 -0700170 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700171 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700172 private static final String USER_PHOTO_FILENAME = "photo.png";
Adrian Roos1bdff912015-02-17 15:51:35 +0100173 private static final String USER_PHOTO_FILENAME_TMP = USER_PHOTO_FILENAME + ".tmp";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700174
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800175 private static final String RESTRICTIONS_FILE_PREFIX = "res_";
Amith Yamasanifc95e702013-09-26 13:20:17 -0700176 private static final String XML_SUFFIX = ".xml";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800177
Sudheer Shankaf5cea032016-06-08 17:13:24 -0700178 private static final int ALLOWED_FLAGS_FOR_CREATE_USERS_PERMISSION =
179 UserInfo.FLAG_MANAGED_PROFILE
180 | UserInfo.FLAG_EPHEMERAL
181 | UserInfo.FLAG_RESTRICTED
182 | UserInfo.FLAG_GUEST;
183
Amith Yamasani634cf312012-10-04 17:34:21 -0700184 private static final int MIN_USER_ID = 10;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700185 // We need to keep process uid within Integer.MAX_VALUE.
186 private static final int MAX_USER_ID = Integer.MAX_VALUE / UserHandle.PER_USER_RANGE;
Amith Yamasani634cf312012-10-04 17:34:21 -0700187
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700188 private static final int USER_VERSION = 6;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700189
Amith Yamasani920ace02012-09-20 22:15:37 -0700190 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
191
Nicolas Prevotb8186812015-08-06 15:00:03 +0100192 // Maximum number of managed profiles permitted per user is 1. This cannot be increased
Amith Yamasani95ab7842014-08-11 17:09:26 -0700193 // without first making sure that the rest of the framework is prepared for it.
194 private static final int MAX_MANAGED_PROFILES = 1;
195
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800196 static final int WRITE_USER_MSG = 1;
197 static final int WRITE_USER_DELAY = 2*1000; // 2 seconds
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530198
Jeff Sharkey6dce4962015-07-03 18:08:41 -0700199 private static final String XATTR_SERIAL = "user.serial";
200
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -0800201 // Tron counters
202 private static final String TRON_GUEST_CREATED = "users_guest_created";
203 private static final String TRON_USER_CREATED = "users_user_created";
204
Dianne Hackborn4428e172012-08-24 17:43:05 -0700205 private final Context mContext;
206 private final PackageManagerService mPm;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700207 private final Object mPackagesLock;
Fyodor Kupolov82402752015-10-28 14:54:51 -0700208 // Short-term lock for internal state, when interaction/sync with PM is not required
209 private final Object mUsersLock = new Object();
210 private final Object mRestrictionsLock = new Object();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700211
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800212 private final Handler mHandler;
213
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700214 private final File mUsersDir;
215 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700216
Svet Ganov9cea80cd2016-02-16 11:47:00 -0800217 private static final IBinder mUserRestriconToken = new Binder();
218
Makoto Onuki068c54a2015-10-13 14:34:03 -0700219 /**
Amith Yamasani12747872015-12-07 14:19:49 -0800220 * User-related information that is used for persisting to flash. Only UserInfo is
221 * directly exposed to other system apps.
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800222 */
Amith Yamasani12747872015-12-07 14:19:49 -0800223 private static class UserData {
224 // Basic user information and properties
225 UserInfo info;
226 // Account name used when there is a strong association between a user and an account
227 String account;
228 // Account information for seeding into a newly created user. This could also be
229 // used for login validation for an existing user, for updating their credentials.
230 // In the latter case, data may not need to be persisted as it is only valid for the
231 // current login session.
232 String seedAccountName;
233 String seedAccountType;
234 PersistableBundle seedAccountOptions;
235 // Whether to perist the seed account information to be available after a boot
236 boolean persistSeedData;
237
238 void clearSeedAccountData() {
239 seedAccountName = null;
240 seedAccountType = null;
241 seedAccountOptions = null;
242 persistSeedData = false;
243 }
244 }
245
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800246 @GuardedBy("mUsersLock")
Amith Yamasani12747872015-12-07 14:19:49 -0800247 private final SparseArray<UserData> mUsers = new SparseArray<>();
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800248
249 /**
Makoto Onuki068c54a2015-10-13 14:34:03 -0700250 * User restrictions set via UserManager. This doesn't include restrictions set by
251 * device owner / profile owners.
252 *
253 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
254 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
255 * maybe shared between {@link #mBaseUserRestrictions} and
256 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
257 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700258 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700259 */
260 @GuardedBy("mRestrictionsLock")
261 private final SparseArray<Bundle> mBaseUserRestrictions = new SparseArray<>();
262
263 /**
264 * Cached user restrictions that are in effect -- i.e. {@link #mBaseUserRestrictions} combined
265 * with device / profile owner restrictions. We'll initialize it lazily; use
266 * {@link #getEffectiveUserRestrictions} to access it.
267 *
268 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
269 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
270 * maybe shared between {@link #mBaseUserRestrictions} and
271 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
272 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700273 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700274 */
275 @GuardedBy("mRestrictionsLock")
276 private final SparseArray<Bundle> mCachedEffectiveUserRestrictions = new SparseArray<>();
277
Makoto Onuki4f160732015-10-27 17:15:38 -0700278 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800279 * User restrictions that have already been applied in
280 * {@link #updateUserRestrictionsInternalLR(Bundle, int)}. We use it to detect restrictions
281 * that have changed since the last
282 * {@link #updateUserRestrictionsInternalLR(Bundle, int)} call.
Makoto Onuki4f160732015-10-27 17:15:38 -0700283 */
284 @GuardedBy("mRestrictionsLock")
285 private final SparseArray<Bundle> mAppliedUserRestrictions = new SparseArray<>();
286
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800287 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800288 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
289 * that should be applied to all users, including guests.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800290 */
291 @GuardedBy("mRestrictionsLock")
292 private Bundle mDevicePolicyGlobalUserRestrictions;
293
294 /**
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +0100295 * Id of the user that set global restrictions.
296 */
297 @GuardedBy("mRestrictionsLock")
298 private int mGlobalRestrictionOwnerUserId = UserHandle.USER_NULL;
299
300 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800301 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
302 * for each user.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800303 */
304 @GuardedBy("mRestrictionsLock")
305 private final SparseArray<Bundle> mDevicePolicyLocalUserRestrictions = new SparseArray<>();
306
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800307 @GuardedBy("mGuestRestrictions")
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530308 private final Bundle mGuestRestrictions = new Bundle();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800309
310 /**
311 * Set of user IDs being actively removed. Removed IDs linger in this set
312 * for several seconds to work around a VFS caching issue.
313 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700314 @GuardedBy("mUsersLock")
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800315 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700316
Fyodor Kupolov82402752015-10-28 14:54:51 -0700317 @GuardedBy("mUsersLock")
Amith Yamasani0b285492011-04-14 17:35:23 -0700318 private int[] mUserIds;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800319 @GuardedBy("mPackagesLock")
Amith Yamasani2a003292012-08-14 18:25:45 -0700320 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700321 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700322
Jason Monk62062992014-05-06 09:55:28 -0400323 private IAppOpsService mAppOpsService;
324
Makoto Onuki068c54a2015-10-13 14:34:03 -0700325 private final LocalService mLocalService;
326
Makoto Onukie7927da2015-11-25 10:05:17 -0800327 @GuardedBy("mUsersLock")
328 private boolean mIsDeviceManaged;
329
330 @GuardedBy("mUsersLock")
331 private final SparseBooleanArray mIsUserManaged = new SparseBooleanArray();
332
Makoto Onukid45a4a22015-11-02 17:17:38 -0800333 @GuardedBy("mUserRestrictionsListeners")
334 private final ArrayList<UserRestrictionsListener> mUserRestrictionsListeners =
335 new ArrayList<>();
336
Clara Bayarria1771112015-12-18 16:29:18 +0000337 private final LockPatternUtils mLockPatternUtils;
338
Ricky Waib1dd80b2016-06-07 18:00:55 +0100339 private final String ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK =
340 "com.android.server.pm.DISABLE_QUIET_MODE_AFTER_UNLOCK";
341
342 private final BroadcastReceiver mDisableQuietModeCallback = new BroadcastReceiver() {
343 @Override
344 public void onReceive(Context context, Intent intent) {
345 if (ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK.equals(intent.getAction())) {
346 final IntentSender target = intent.getParcelableExtra(Intent.EXTRA_INTENT);
347 final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_ID, 0);
348 setQuietModeEnabled(userHandle, false);
349 if (target != null) {
350 try {
351 mContext.startIntentSender(target, null, 0, 0, 0);
352 } catch (IntentSender.SendIntentException e) {
353 /* ignore */
354 }
355 }
356 }
357 }
358 };
359
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +0100360 /**
361 * Whether all users should be created ephemeral.
362 */
363 @GuardedBy("mUsersLock")
364 private boolean mForceEphemeralUsers;
365
Amith Yamasaniea1b9d72016-05-27 15:57:38 +0000366 @GuardedBy("mUserStates")
367 private final SparseIntArray mUserStates = new SparseIntArray();
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -0700368
Amith Yamasani258848d2012-08-10 17:06:33 -0700369 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700370
Dianne Hackborn4428e172012-08-24 17:43:05 -0700371 public static UserManagerService getInstance() {
372 synchronized (UserManagerService.class) {
373 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700374 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700375 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700376
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700377 public static class LifeCycle extends SystemService {
378
379 private UserManagerService mUms;
380
381 /**
382 * @param context
383 */
384 public LifeCycle(Context context) {
385 super(context);
386 }
387
388 @Override
389 public void onStart() {
390 mUms = UserManagerService.getInstance();
391 publishBinderService(Context.USER_SERVICE, mUms);
392 }
393
394 @Override
395 public void onBootPhase(int phase) {
396 if (phase == SystemService.PHASE_ACTIVITY_MANAGER_READY) {
397 mUms.cleanupPartialUsers();
398 }
399 }
400 }
401
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800402 @VisibleForTesting
403 UserManagerService(File dataDir) {
404 this(null, null, new Object(), dataDir);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700405 }
406
Dianne Hackborn4428e172012-08-24 17:43:05 -0700407 /**
408 * Called by package manager to create the service. This is closely
409 * associated with the package manager, and the given lock is the
410 * package manager's own lock.
411 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800412 UserManagerService(Context context, PackageManagerService pm, Object packagesLock) {
413 this(context, pm, packagesLock, Environment.getDataDirectory());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700414 }
415
Dianne Hackborn4428e172012-08-24 17:43:05 -0700416 private UserManagerService(Context context, PackageManagerService pm,
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800417 Object packagesLock, File dataDir) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700418 mContext = context;
419 mPm = pm;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700420 mPackagesLock = packagesLock;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800421 mHandler = new MainHandler();
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800422 synchronized (mPackagesLock) {
423 mUsersDir = new File(dataDir, USER_INFO_DIR);
424 mUsersDir.mkdirs();
425 // Make zeroth user directory, for services to migrate their files to that location
426 File userZeroDir = new File(mUsersDir, String.valueOf(UserHandle.USER_SYSTEM));
427 userZeroDir.mkdirs();
428 FileUtils.setPermissions(mUsersDir.toString(),
429 FileUtils.S_IRWXU | FileUtils.S_IRWXG | FileUtils.S_IROTH | FileUtils.S_IXOTH,
430 -1, -1);
431 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
432 initDefaultGuestRestrictions();
433 readUserListLP();
434 sInstance = this;
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700435 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700436 mLocalService = new LocalService();
437 LocalServices.addService(UserManagerInternal.class, mLocalService);
Clara Bayarria1771112015-12-18 16:29:18 +0000438 mLockPatternUtils = new LockPatternUtils(mContext);
Amith Yamasaniea1b9d72016-05-27 15:57:38 +0000439 mUserStates.put(UserHandle.USER_SYSTEM, UserState.STATE_BOOTING);
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700440 }
441
442 void systemReady() {
Jason Monk62062992014-05-06 09:55:28 -0400443 mAppOpsService = IAppOpsService.Stub.asInterface(
444 ServiceManager.getService(Context.APP_OPS_SERVICE));
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800445
446 synchronized (mRestrictionsLock) {
447 applyUserRestrictionsLR(UserHandle.USER_SYSTEM);
Jason Monk62062992014-05-06 09:55:28 -0400448 }
Samuel Tand9453b82016-03-14 15:57:02 -0700449
450 UserInfo currentGuestUser = findCurrentGuestUser();
451 if (currentGuestUser != null && !hasUserRestriction(
452 UserManager.DISALLOW_CONFIG_WIFI, currentGuestUser.id)) {
453 // If a guest user currently exists, apply the DISALLOW_CONFIG_WIFI option
454 // to it, in case this guest was created in a previous version where this
455 // user restriction was not a default guest restriction.
456 setUserRestriction(UserManager.DISALLOW_CONFIG_WIFI, true, currentGuestUser.id);
457 }
Amith Yamasanieb437d42016-04-29 09:31:25 -0700458
459 maybeInitializeDemoMode(UserHandle.USER_SYSTEM);
Ricky Waib1dd80b2016-06-07 18:00:55 +0100460 mContext.registerReceiver(mDisableQuietModeCallback,
461 new IntentFilter(ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK),
462 null, mHandler);
Amith Yamasani258848d2012-08-10 17:06:33 -0700463 }
464
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700465 void cleanupPartialUsers() {
466 // Prune out any partially created, partially removed and ephemeral users.
467 ArrayList<UserInfo> partials = new ArrayList<>();
468 synchronized (mUsersLock) {
469 final int userSize = mUsers.size();
470 for (int i = 0; i < userSize; i++) {
471 UserInfo ui = mUsers.valueAt(i).info;
472 if ((ui.partial || ui.guestToRemove || ui.isEphemeral()) && i != 0) {
473 partials.add(ui);
Amith Yamasaniae261892016-06-27 10:40:09 -0700474 mRemovingUserIds.append(ui.id, true);
475 ui.partial = true;
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700476 }
477 }
478 }
479 final int partialsSize = partials.size();
480 for (int i = 0; i < partialsSize; i++) {
481 UserInfo ui = partials.get(i);
482 Slog.w(LOG_TAG, "Removing partially created user " + ui.id
483 + " (name=" + ui.name + ")");
484 removeUserState(ui.id);
485 }
486 }
487
Amith Yamasani258848d2012-08-10 17:06:33 -0700488 @Override
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800489 public String getUserAccount(int userId) {
490 checkManageUserAndAcrossUsersFullPermission("get user account");
491 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800492 return mUsers.get(userId).account;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800493 }
494 }
495
496 @Override
497 public void setUserAccount(int userId, String accountName) {
498 checkManageUserAndAcrossUsersFullPermission("set user account");
Amith Yamasani12747872015-12-07 14:19:49 -0800499 UserData userToUpdate = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800500 synchronized (mPackagesLock) {
501 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800502 final UserData userData = mUsers.get(userId);
503 if (userData == null) {
504 Slog.e(LOG_TAG, "User not found for setting user account: u" + userId);
505 return;
506 }
507 String currentAccount = userData.account;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800508 if (!Objects.equal(currentAccount, accountName)) {
Amith Yamasani12747872015-12-07 14:19:49 -0800509 userData.account = accountName;
510 userToUpdate = userData;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800511 }
512 }
513
514 if (userToUpdate != null) {
515 writeUserLP(userToUpdate);
516 }
517 }
518 }
519
520 @Override
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700521 public UserInfo getPrimaryUser() {
522 checkManageUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700523 synchronized (mUsersLock) {
Amith Yamasani515d4062015-09-28 11:30:06 -0700524 final int userSize = mUsers.size();
525 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800526 UserInfo ui = mUsers.valueAt(i).info;
Xiaohui Chend3e9e182015-11-18 13:37:32 -0800527 if (ui.isPrimary() && !mRemovingUserIds.get(ui.id)) {
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700528 return ui;
529 }
530 }
531 }
532 return null;
533 }
534
535 @Override
Xiaohui Chen594f2082015-08-18 11:04:20 -0700536 public @NonNull List<UserInfo> getUsers(boolean excludeDying) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -0700537 checkManageOrCreateUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700538 synchronized (mUsersLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700539 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasani515d4062015-09-28 11:30:06 -0700540 final int userSize = mUsers.size();
541 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800542 UserInfo ui = mUsers.valueAt(i).info;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700543 if (ui.partial) {
544 continue;
545 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800546 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Amith Yamasani6f48d6e2016-03-23 14:28:25 -0700547 users.add(userWithName(ui));
Amith Yamasani920ace02012-09-20 22:15:37 -0700548 }
Amith Yamasani13593602012-03-22 16:16:17 -0700549 }
550 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700551 }
Amith Yamasani13593602012-03-22 16:16:17 -0700552 }
553
Amith Yamasani258848d2012-08-10 17:06:33 -0700554 @Override
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100555 public List<UserInfo> getProfiles(int userId, boolean enabledOnly) {
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700556 boolean returnFullInfo = true;
Amith Yamasani4f582632014-02-19 14:31:52 -0800557 if (userId != UserHandle.getCallingUserId()) {
558 checkManageUsersPermission("getting profiles related to user " + userId);
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700559 } else {
560 returnFullInfo = hasManageUsersPermission();
Amith Yamasani4f582632014-02-19 14:31:52 -0800561 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700562 final long ident = Binder.clearCallingIdentity();
563 try {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700564 synchronized (mUsersLock) {
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700565 return getProfilesLU(userId, enabledOnly, returnFullInfo);
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100566 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700567 } finally {
568 Binder.restoreCallingIdentity(ident);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000569 }
570 }
571
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700572 @Override
573 public int[] getProfileIds(int userId, boolean enabledOnly) {
574 if (userId != UserHandle.getCallingUserId()) {
575 checkManageUsersPermission("getting profiles related to user " + userId);
576 }
577 final long ident = Binder.clearCallingIdentity();
578 try {
579 synchronized (mUsersLock) {
580 return getProfileIdsLU(userId, enabledOnly).toArray();
581 }
582 } finally {
583 Binder.restoreCallingIdentity(ident);
584 }
585 }
586
Amith Yamasanibe465322014-04-24 13:45:17 -0700587 /** Assume permissions already checked and caller's identity cleared */
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700588 private List<UserInfo> getProfilesLU(int userId, boolean enabledOnly, boolean fullInfo) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700589 IntArray profileIds = getProfileIdsLU(userId, enabledOnly);
590 ArrayList<UserInfo> users = new ArrayList<>(profileIds.size());
591 for (int i = 0; i < profileIds.size(); i++) {
592 int profileId = profileIds.get(i);
593 UserInfo userInfo = mUsers.get(profileId).info;
594 // If full info is not required - clear PII data to prevent 3P apps from reading it
595 if (!fullInfo) {
596 userInfo = new UserInfo(userInfo);
597 userInfo.name = null;
598 userInfo.iconPath = null;
599 } else {
600 userInfo = userWithName(userInfo);
601 }
602 users.add(userInfo);
603 }
604 return users;
605 }
606
607 /**
608 * Assume permissions already checked and caller's identity cleared
609 */
610 private IntArray getProfileIdsLU(int userId, boolean enabledOnly) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700611 UserInfo user = getUserInfoLU(userId);
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700612 IntArray result = new IntArray(mUsers.size());
Amith Yamasanidda003f2014-08-28 18:06:51 -0700613 if (user == null) {
614 // Probably a dying user
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700615 return result;
Amith Yamasanidda003f2014-08-28 18:06:51 -0700616 }
Amith Yamasani515d4062015-09-28 11:30:06 -0700617 final int userSize = mUsers.size();
618 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800619 UserInfo profile = mUsers.valueAt(i).info;
Amith Yamasanibe465322014-04-24 13:45:17 -0700620 if (!isProfileOf(user, profile)) {
621 continue;
622 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100623 if (enabledOnly && !profile.isEnabled()) {
624 continue;
Amith Yamasanibe465322014-04-24 13:45:17 -0700625 }
Amith Yamasani70fcf0c2014-07-11 08:40:19 -0700626 if (mRemovingUserIds.get(profile.id)) {
627 continue;
628 }
Tony Mak80189cd2016-04-05 17:21:42 +0100629 if (profile.partial) {
630 continue;
631 }
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700632 result.add(profile.id);
Amith Yamasanibe465322014-04-24 13:45:17 -0700633 }
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700634 return result;
Amith Yamasanibe465322014-04-24 13:45:17 -0700635 }
636
Jessica Hummelbe81c802014-04-22 15:49:22 +0100637 @Override
Andres Moralesc5548c02015-08-05 10:23:12 -0700638 public int getCredentialOwnerProfile(int userHandle) {
639 checkManageUsersPermission("get the credential owner");
Clara Bayarria1771112015-12-18 16:29:18 +0000640 if (!mLockPatternUtils.isSeparateProfileChallengeEnabled(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700641 synchronized (mUsersLock) {
642 UserInfo profileParent = getProfileParentLU(userHandle);
Andres Moralesc5548c02015-08-05 10:23:12 -0700643 if (profileParent != null) {
644 return profileParent.id;
645 }
646 }
647 }
648
649 return userHandle;
650 }
651
652 @Override
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700653 public boolean isSameProfileGroup(int userId, int otherUserId) {
654 if (userId == otherUserId) return true;
655 checkManageUsersPermission("check if in the same profile group");
656 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700657 return isSameProfileGroupLP(userId, otherUserId);
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700658 }
659 }
660
Fyodor Kupolov82402752015-10-28 14:54:51 -0700661 private boolean isSameProfileGroupLP(int userId, int otherUserId) {
662 synchronized (mUsersLock) {
663 UserInfo userInfo = getUserInfoLU(userId);
664 if (userInfo == null || userInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
665 return false;
666 }
667 UserInfo otherUserInfo = getUserInfoLU(otherUserId);
668 if (otherUserInfo == null
669 || otherUserInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
670 return false;
671 }
672 return userInfo.profileGroupId == otherUserInfo.profileGroupId;
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700673 }
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700674 }
675
676 @Override
Jessica Hummelbe81c802014-04-22 15:49:22 +0100677 public UserInfo getProfileParent(int userHandle) {
678 checkManageUsersPermission("get the profile parent");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700679 synchronized (mUsersLock) {
680 return getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700681 }
682 }
683
Fyodor Kupolov82402752015-10-28 14:54:51 -0700684 private UserInfo getProfileParentLU(int userHandle) {
685 UserInfo profile = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700686 if (profile == null) {
687 return null;
688 }
689 int parentUserId = profile.profileGroupId;
690 if (parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
691 return null;
692 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700693 return getUserInfoLU(parentUserId);
Jessica Hummelbe81c802014-04-22 15:49:22 +0100694 }
695 }
696
Fyodor Kupolov82402752015-10-28 14:54:51 -0700697 private static boolean isProfileOf(UserInfo user, UserInfo profile) {
Kenny Guy2a764942014-04-02 13:29:20 +0100698 return user.id == profile.id ||
699 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
700 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000701 }
702
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000703 private void broadcastProfileAvailabilityChanges(UserHandle profileHandle,
Rubin Xuf13c9802016-01-21 18:06:00 +0000704 UserHandle parentHandle, boolean inQuietMode) {
Rubin Xue95057a2016-04-01 16:49:25 +0100705 Intent intent = new Intent();
706 if (inQuietMode) {
707 intent.setAction(Intent.ACTION_MANAGED_PROFILE_UNAVAILABLE);
708 } else {
709 intent.setAction(Intent.ACTION_MANAGED_PROFILE_AVAILABLE);
710 }
Rubin Xuf13c9802016-01-21 18:06:00 +0000711 intent.putExtra(Intent.EXTRA_QUIET_MODE, inQuietMode);
712 intent.putExtra(Intent.EXTRA_USER, profileHandle);
713 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileHandle.getIdentifier());
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000714 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Rubin Xuf13c9802016-01-21 18:06:00 +0000715 mContext.sendBroadcastAsUser(intent, parentHandle);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000716 }
717
718 @Override
719 public void setQuietModeEnabled(int userHandle, boolean enableQuietMode) {
720 checkManageUsersPermission("silence profile");
721 boolean changed = false;
722 UserInfo profile, parent;
723 synchronized (mPackagesLock) {
724 synchronized (mUsersLock) {
725 profile = getUserInfoLU(userHandle);
726 parent = getProfileParentLU(userHandle);
727
728 }
729 if (profile == null || !profile.isManagedProfile()) {
730 throw new IllegalArgumentException("User " + userHandle + " is not a profile");
731 }
732 if (profile.isQuietModeEnabled() != enableQuietMode) {
733 profile.flags ^= UserInfo.FLAG_QUIET_MODE;
Amith Yamasani12747872015-12-07 14:19:49 -0800734 writeUserLP(getUserDataLU(profile.id));
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000735 changed = true;
736 }
737 }
738 if (changed) {
Rubin Xuf13c9802016-01-21 18:06:00 +0000739 long identity = Binder.clearCallingIdentity();
740 try {
741 if (enableQuietMode) {
Nicolas Prevot1219c922016-06-20 17:25:12 +0100742 ActivityManagerNative.getDefault().stopUser(userHandle, /* force */true, null);
Rubin Xuf8451b92016-04-01 15:50:58 +0100743 LocalServices.getService(ActivityManagerInternal.class)
744 .killForegroundAppsForUser(userHandle);
Rubin Xuf13c9802016-01-21 18:06:00 +0000745 } else {
746 ActivityManagerNative.getDefault().startUserInBackground(userHandle);
747 }
748 } catch (RemoteException e) {
749 Slog.e(LOG_TAG, "fail to start/stop user for quiet mode", e);
750 } finally {
751 Binder.restoreCallingIdentity(identity);
752 }
753
754 broadcastProfileAvailabilityChanges(profile.getUserHandle(), parent.getUserHandle(),
755 enableQuietMode);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000756 }
757 }
758
759 @Override
760 public boolean isQuietModeEnabled(int userHandle) {
761 synchronized (mPackagesLock) {
762 UserInfo info;
763 synchronized (mUsersLock) {
764 info = getUserInfoLU(userHandle);
765 }
766 if (info == null || !info.isManagedProfile()) {
Rubin Xuf13c9802016-01-21 18:06:00 +0000767 return false;
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000768 }
769 return info.isQuietModeEnabled();
770 }
771 }
772
Kenny Guya52dc3e2014-02-11 15:33:14 +0000773 @Override
Benjamin Franzf02420c2016-04-04 18:52:21 +0100774 public boolean trySetQuietModeDisabled(int userHandle, IntentSender target) {
Ricky Waib1dd80b2016-06-07 18:00:55 +0100775 checkManageUsersPermission("silence profile");
Jeff Sharkeyce18c812016-04-27 16:00:41 -0600776 if (StorageManager.isUserKeyUnlocked(userHandle)
Ricky Wai9cc7ad62016-05-11 18:00:20 +0100777 || !mLockPatternUtils.isSecure(userHandle)) {
Benjamin Franzf02420c2016-04-04 18:52:21 +0100778 // if the user is already unlocked, no need to show a profile challenge
779 setQuietModeEnabled(userHandle, false);
780 return true;
781 }
782
783 long identity = Binder.clearCallingIdentity();
784 try {
785 // otherwise, we show a profile challenge to trigger decryption of the user
786 final KeyguardManager km = (KeyguardManager) mContext.getSystemService(
787 Context.KEYGUARD_SERVICE);
Ricky Wai7881cf82016-04-15 17:20:12 +0100788 // We should use userHandle not credentialOwnerUserId here, as even if it is unified
789 // lock, confirm screenlock page will know and show personal challenge, and unlock
790 // work profile when personal challenge is correct
Benjamin Franzf02420c2016-04-04 18:52:21 +0100791 final Intent unlockIntent = km.createConfirmDeviceCredentialIntent(null, null,
792 userHandle);
793 if (unlockIntent == null) {
794 return false;
795 }
Ricky Waib1dd80b2016-06-07 18:00:55 +0100796 final Intent callBackIntent = new Intent(
797 ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK);
Benjamin Franzf02420c2016-04-04 18:52:21 +0100798 if (target != null) {
Ricky Waib1dd80b2016-06-07 18:00:55 +0100799 callBackIntent.putExtra(Intent.EXTRA_INTENT, target);
Benjamin Franzf02420c2016-04-04 18:52:21 +0100800 }
Ricky Waib1dd80b2016-06-07 18:00:55 +0100801 callBackIntent.putExtra(Intent.EXTRA_USER_ID, userHandle);
802 callBackIntent.setPackage(mContext.getPackageName());
803 callBackIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
804 final PendingIntent pendingIntent = PendingIntent.getBroadcast(
805 mContext,
806 0,
807 callBackIntent,
808 PendingIntent.FLAG_CANCEL_CURRENT |
809 PendingIntent.FLAG_ONE_SHOT |
810 PendingIntent.FLAG_IMMUTABLE);
811 // After unlocking the challenge, it will disable quiet mode and run the original
812 // intentSender
813 unlockIntent.putExtra(Intent.EXTRA_INTENT, pendingIntent.getIntentSender());
Benjamin Franzf02420c2016-04-04 18:52:21 +0100814 unlockIntent.setFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
815 mContext.startActivity(unlockIntent);
816 } finally {
817 Binder.restoreCallingIdentity(identity);
818 }
819 return false;
820 }
821
822 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100823 public void setUserEnabled(int userId) {
824 checkManageUsersPermission("enable user");
825 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700826 UserInfo info;
827 synchronized (mUsersLock) {
828 info = getUserInfoLU(userId);
829 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100830 if (info != null && !info.isEnabled()) {
831 info.flags ^= UserInfo.FLAG_DISABLED;
Amith Yamasani12747872015-12-07 14:19:49 -0800832 writeUserLP(getUserDataLU(info.id));
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100833 }
834 }
835 }
836
837 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700838 public UserInfo getUserInfo(int userId) {
Sudheer Shankaaccaa082016-06-14 16:22:57 -0700839 checkManageOrCreateUsersPermission("query user");
Tony Mak8673b282016-03-21 21:10:59 +0000840 synchronized (mUsersLock) {
Amith Yamasani6f48d6e2016-03-23 14:28:25 -0700841 return userWithName(getUserInfoLU(userId));
842 }
843 }
844
845 /**
846 * Returns a UserInfo object with the name filled in, for Owner, or the original
847 * if the name is already set.
848 */
849 private UserInfo userWithName(UserInfo orig) {
850 if (orig != null && orig.name == null && orig.id == UserHandle.USER_SYSTEM) {
851 UserInfo withName = new UserInfo(orig);
852 withName.name = getOwnerName();
853 return withName;
854 } else {
855 return orig;
Tony Mak8673b282016-03-21 21:10:59 +0000856 }
857 }
858
859 @Override
860 public boolean isManagedProfile(int userId) {
Tony Makb531d082016-03-16 14:49:52 +0000861 int callingUserId = UserHandle.getCallingUserId();
862 if (callingUserId != userId && !hasManageUsersPermission()) {
863 synchronized (mPackagesLock) {
864 if (!isSameProfileGroupLP(callingUserId, userId)) {
865 throw new SecurityException(
Tony Mak8673b282016-03-21 21:10:59 +0000866 "You need MANAGE_USERS permission to: check if specified user a " +
867 "managed profile outside your profile group");
Tony Makb531d082016-03-16 14:49:52 +0000868 }
869 }
Tony Mak4dc008c2016-03-16 10:46:49 +0000870 }
Fyodor Kupolov82402752015-10-28 14:54:51 -0700871 synchronized (mUsersLock) {
Tony Mak8673b282016-03-21 21:10:59 +0000872 UserInfo userInfo = getUserInfoLU(userId);
873 return userInfo != null && userInfo.isManagedProfile();
Amith Yamasani13593602012-03-22 16:16:17 -0700874 }
875 }
876
Amith Yamasani71e6c692013-03-24 17:39:28 -0700877 @Override
878 public boolean isRestricted() {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700879 synchronized (mUsersLock) {
880 return getUserInfoLU(UserHandle.getCallingUserId()).isRestricted();
Amith Yamasani71e6c692013-03-24 17:39:28 -0700881 }
882 }
883
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700884 @Override
885 public boolean canHaveRestrictedProfile(int userId) {
886 checkManageUsersPermission("canHaveRestrictedProfile");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700887 synchronized (mUsersLock) {
888 final UserInfo userInfo = getUserInfoLU(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700889 if (userInfo == null || !userInfo.canHaveProfile()) {
890 return false;
891 }
892 if (!userInfo.isAdmin()) {
893 return false;
894 }
Makoto Onukie7927da2015-11-25 10:05:17 -0800895 // restricted profile can be created if there is no DO set and the admin user has no PO;
896 return !mIsDeviceManaged && !mIsUserManaged.get(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700897 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700898 }
899
Amith Yamasani195263742012-08-21 15:40:12 -0700900 /*
901 * Should be locked on mUsers before calling this.
902 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700903 private UserInfo getUserInfoLU(int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -0800904 final UserData userData = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -0700905 // If it is partial and not in the process of being removed, return as unknown user.
Amith Yamasani12747872015-12-07 14:19:49 -0800906 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700907 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
908 return null;
909 }
Amith Yamasani12747872015-12-07 14:19:49 -0800910 return userData != null ? userData.info : null;
911 }
912
913 private UserData getUserDataLU(int userId) {
914 final UserData userData = mUsers.get(userId);
915 // If it is partial and not in the process of being removed, return as unknown user.
916 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
917 return null;
918 }
919 return userData;
Amith Yamasani195263742012-08-21 15:40:12 -0700920 }
921
Fyodor Kupolov82402752015-10-28 14:54:51 -0700922 /**
923 * Obtains {@link #mUsersLock} and return UserInfo from mUsers.
924 * <p>No permissions checking or any addition checks are made</p>
925 */
926 private UserInfo getUserInfoNoChecks(int userId) {
927 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800928 final UserData userData = mUsers.get(userId);
929 return userData != null ? userData.info : null;
930 }
931 }
932
933 /**
934 * Obtains {@link #mUsersLock} and return UserData from mUsers.
935 * <p>No permissions checking or any addition checks are made</p>
936 */
937 private UserData getUserDataNoChecks(int userId) {
938 synchronized (mUsersLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700939 return mUsers.get(userId);
940 }
941 }
942
Amith Yamasani236b2b52015-08-18 14:32:14 -0700943 /** Called by PackageManagerService */
Amith Yamasani13593602012-03-22 16:16:17 -0700944 public boolean exists(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700945 return getUserInfoNoChecks(userId) != null;
Amith Yamasani13593602012-03-22 16:16:17 -0700946 }
947
Amith Yamasani258848d2012-08-10 17:06:33 -0700948 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700949 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700950 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700951 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700952 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800953 UserData userData = getUserDataNoChecks(userId);
954 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700955 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
956 return;
957 }
Amith Yamasani12747872015-12-07 14:19:49 -0800958 if (name != null && !name.equals(userData.info.name)) {
959 userData.info.name = name;
960 writeUserLP(userData);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700961 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -0700962 }
963 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700964 if (changed) {
965 sendUserInfoChangedBroadcast(userId);
966 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700967 }
968
Amith Yamasani258848d2012-08-10 17:06:33 -0700969 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700970 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700971 checkManageUsersPermission("update users");
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +0100972 if (hasUserRestriction(UserManager.DISALLOW_SET_USER_ICON, userId)) {
973 Log.w(LOG_TAG, "Cannot set user icon. DISALLOW_SET_USER_ICON is enabled.");
974 return;
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700975 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +0100976 mLocalService.setUserIcon(userId, bitmap);
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700977 }
978
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +0100979
980
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700981 private void sendUserInfoChangedBroadcast(int userId) {
982 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
983 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
984 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -0700985 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700986 }
987
Amith Yamasani258848d2012-08-10 17:06:33 -0700988 @Override
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +0100989 public ParcelFileDescriptor getUserIcon(int targetUserId) {
Adrian Roos1bdff912015-02-17 15:51:35 +0100990 String iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700991 synchronized (mPackagesLock) {
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +0100992 UserInfo targetUserInfo = getUserInfoNoChecks(targetUserId);
993 if (targetUserInfo == null || targetUserInfo.partial) {
994 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + targetUserId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700995 return null;
996 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +0100997
998 final int callingUserId = UserHandle.getCallingUserId();
999 final int callingGroupId = getUserInfoNoChecks(callingUserId).profileGroupId;
1000 final int targetGroupId = targetUserInfo.profileGroupId;
1001 final boolean sameGroup = (callingGroupId != UserInfo.NO_PROFILE_GROUP_ID
1002 && callingGroupId == targetGroupId);
1003 if ((callingUserId != targetUserId) && !sameGroup) {
Nicolas Prevot88cc3462014-05-14 14:51:48 +01001004 checkManageUsersPermission("get the icon of a user who is not related");
1005 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001006
1007 if (targetUserInfo.iconPath == null) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001008 return null;
1009 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001010 iconPath = targetUserInfo.iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001011 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001012
1013 try {
1014 return ParcelFileDescriptor.open(
1015 new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
1016 } catch (FileNotFoundException e) {
1017 Log.e(LOG_TAG, "Couldn't find icon file", e);
1018 }
1019 return null;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001020 }
1021
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001022 public void makeInitialized(int userId) {
1023 checkManageUsersPermission("makeInitialized");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001024 boolean scheduleWriteUser = false;
Amith Yamasani12747872015-12-07 14:19:49 -08001025 UserData userData;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001026 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001027 userData = mUsers.get(userId);
1028 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001029 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001030 return;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001031 }
Amith Yamasani12747872015-12-07 14:19:49 -08001032 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1033 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001034 scheduleWriteUser = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001035 }
1036 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001037 if (scheduleWriteUser) {
Amith Yamasani12747872015-12-07 14:19:49 -08001038 scheduleWriteUser(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001039 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001040 }
1041
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001042 /**
1043 * If default guest restrictions haven't been initialized yet, add the basic
1044 * restrictions.
1045 */
1046 private void initDefaultGuestRestrictions() {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001047 synchronized (mGuestRestrictions) {
1048 if (mGuestRestrictions.isEmpty()) {
Samuel Tand9453b82016-03-14 15:57:02 -07001049 mGuestRestrictions.putBoolean(UserManager.DISALLOW_CONFIG_WIFI, true);
Fyodor Kupolove04462c2015-11-30 15:02:53 -08001050 mGuestRestrictions.putBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, true);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001051 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
1052 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
1053 }
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001054 }
1055 }
1056
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001057 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301058 public Bundle getDefaultGuestRestrictions() {
1059 checkManageUsersPermission("getDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001060 synchronized (mGuestRestrictions) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301061 return new Bundle(mGuestRestrictions);
1062 }
1063 }
1064
1065 @Override
1066 public void setDefaultGuestRestrictions(Bundle restrictions) {
1067 checkManageUsersPermission("setDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001068 synchronized (mGuestRestrictions) {
1069 mGuestRestrictions.clear();
1070 mGuestRestrictions.putAll(restrictions);
1071 }
1072 synchronized (mPackagesLock) {
1073 writeUserListLP();
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301074 }
1075 }
1076
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001077 /**
1078 * See {@link UserManagerInternal#setDevicePolicyUserRestrictions(int, Bundle, Bundle)}
1079 */
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08001080 void setDevicePolicyUserRestrictionsInner(int userId, @NonNull Bundle local,
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001081 @Nullable Bundle global) {
1082 Preconditions.checkNotNull(local);
1083 boolean globalChanged = false;
1084 boolean localChanged;
1085 synchronized (mRestrictionsLock) {
1086 if (global != null) {
1087 // Update global.
1088 globalChanged = !UserRestrictionsUtils.areEqual(
1089 mDevicePolicyGlobalUserRestrictions, global);
1090 if (globalChanged) {
1091 mDevicePolicyGlobalUserRestrictions = global;
1092 }
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001093 // Remember the global restriction owner userId to be able to make a distinction
1094 // in getUserRestrictionSource on who set local policies.
1095 mGlobalRestrictionOwnerUserId = userId;
1096 } else {
Zoltan Szatmary-Ban8a5536d2016-05-27 17:56:44 +01001097 if (mGlobalRestrictionOwnerUserId == userId) {
1098 // When profile owner sets restrictions it passes null global bundle and we
1099 // reset global restriction owner userId.
1100 // This means this user used to have DO, but now the DO is gone and the user
1101 // instead has PO.
1102 mGlobalRestrictionOwnerUserId = UserHandle.USER_NULL;
1103 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001104 }
1105 {
1106 // Update local.
1107 final Bundle prev = mDevicePolicyLocalUserRestrictions.get(userId);
1108 localChanged = !UserRestrictionsUtils.areEqual(prev, local);
1109 if (localChanged) {
1110 mDevicePolicyLocalUserRestrictions.put(userId, local);
1111 }
1112 }
1113 }
1114 if (DBG) {
1115 Log.d(LOG_TAG, "setDevicePolicyUserRestrictions: userId=" + userId
1116 + " global=" + global + (globalChanged ? " (changed)" : "")
1117 + " local=" + local + (localChanged ? " (changed)" : "")
1118 );
1119 }
1120 // Don't call them within the mRestrictionsLock.
1121 synchronized (mPackagesLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001122 if (localChanged) {
Amith Yamasani12747872015-12-07 14:19:49 -08001123 writeUserLP(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001124 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06001125 if (globalChanged) {
1126 writeUserListLP();
1127 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001128 }
1129
1130 synchronized (mRestrictionsLock) {
1131 if (globalChanged) {
1132 applyUserRestrictionsForAllUsersLR();
1133 } else if (localChanged) {
1134 applyUserRestrictionsLR(userId);
1135 }
1136 }
1137 }
1138
Makoto Onuki068c54a2015-10-13 14:34:03 -07001139 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001140 private Bundle computeEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001141 final Bundle baseRestrictions =
1142 UserRestrictionsUtils.nonNull(mBaseUserRestrictions.get(userId));
1143 final Bundle global = mDevicePolicyGlobalUserRestrictions;
1144 final Bundle local = mDevicePolicyLocalUserRestrictions.get(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001145
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001146 if (UserRestrictionsUtils.isEmpty(global) && UserRestrictionsUtils.isEmpty(local)) {
1147 // Common case first.
1148 return baseRestrictions;
Makoto Onuki068c54a2015-10-13 14:34:03 -07001149 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001150 final Bundle effective = UserRestrictionsUtils.clone(baseRestrictions);
1151 UserRestrictionsUtils.merge(effective, global);
1152 UserRestrictionsUtils.merge(effective, local);
1153
Makoto Onuki068c54a2015-10-13 14:34:03 -07001154 return effective;
1155 }
1156
1157 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001158 private void invalidateEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki068c54a2015-10-13 14:34:03 -07001159 if (DBG) {
1160 Log.d(LOG_TAG, "invalidateEffectiveUserRestrictions userId=" + userId);
1161 }
1162 mCachedEffectiveUserRestrictions.remove(userId);
1163 }
1164
1165 private Bundle getEffectiveUserRestrictions(int userId) {
1166 synchronized (mRestrictionsLock) {
1167 Bundle restrictions = mCachedEffectiveUserRestrictions.get(userId);
1168 if (restrictions == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001169 restrictions = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001170 mCachedEffectiveUserRestrictions.put(userId, restrictions);
1171 }
1172 return restrictions;
Amith Yamasani8cd28b52014-06-08 17:54:27 -07001173 }
1174 }
1175
Makoto Onuki068c54a2015-10-13 14:34:03 -07001176 /** @return a specific user restriction that's in effect currently. */
1177 @Override
1178 public boolean hasUserRestriction(String restrictionKey, int userId) {
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001179 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1180 return false;
1181 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001182 Bundle restrictions = getEffectiveUserRestrictions(userId);
1183 return restrictions != null && restrictions.getBoolean(restrictionKey);
1184 }
1185
1186 /**
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001187 * @hide
1188 *
1189 * Returns who set a user restriction on a user.
1190 * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
1191 * @param restrictionKey the string key representing the restriction
1192 * @param userId the id of the user for whom to retrieve the restrictions.
1193 * @return The source of user restriction. Any combination of
1194 * {@link UserManager#RESTRICTION_NOT_SET},
1195 * {@link UserManager#RESTRICTION_SOURCE_SYSTEM},
1196 * {@link UserManager#RESTRICTION_SOURCE_DEVICE_OWNER}
1197 * and {@link UserManager#RESTRICTION_SOURCE_PROFILE_OWNER}
1198 */
1199 @Override
1200 public int getUserRestrictionSource(String restrictionKey, int userId) {
1201 checkManageUsersPermission("getUserRestrictionSource");
1202 int result = UserManager.RESTRICTION_NOT_SET;
1203
1204 // Shortcut for the most common case
1205 if (!hasUserRestriction(restrictionKey, userId)) {
1206 return result;
1207 }
1208
1209 if (hasBaseUserRestriction(restrictionKey, userId)) {
1210 result |= UserManager.RESTRICTION_SOURCE_SYSTEM;
1211 }
1212
1213 synchronized(mRestrictionsLock) {
1214 Bundle localRestrictions = mDevicePolicyLocalUserRestrictions.get(userId);
1215 if (!UserRestrictionsUtils.isEmpty(localRestrictions)
1216 && localRestrictions.getBoolean(restrictionKey)) {
1217 // Local restrictions may have been set by device owner the userId of which is
1218 // stored in mGlobalRestrictionOwnerUserId.
1219 if (mGlobalRestrictionOwnerUserId == userId) {
1220 result |= UserManager.RESTRICTION_SOURCE_DEVICE_OWNER;
1221 } else {
1222 result |= UserManager.RESTRICTION_SOURCE_PROFILE_OWNER;
1223 }
1224 }
1225 if (!UserRestrictionsUtils.isEmpty(mDevicePolicyGlobalUserRestrictions)
1226 && mDevicePolicyGlobalUserRestrictions.getBoolean(restrictionKey)) {
1227 result |= UserManager.RESTRICTION_SOURCE_DEVICE_OWNER;
1228 }
1229 }
1230
1231 return result;
1232 }
1233
1234 /**
Makoto Onuki068c54a2015-10-13 14:34:03 -07001235 * @return UserRestrictions that are in effect currently. This always returns a new
1236 * {@link Bundle}.
1237 */
Amith Yamasani8cd28b52014-06-08 17:54:27 -07001238 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001239 public Bundle getUserRestrictions(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001240 return UserRestrictionsUtils.clone(getEffectiveUserRestrictions(userId));
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001241 }
1242
1243 @Override
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +00001244 public boolean hasBaseUserRestriction(String restrictionKey, int userId) {
1245 checkManageUsersPermission("hasBaseUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001246 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1247 return false;
1248 }
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +00001249 synchronized (mRestrictionsLock) {
1250 Bundle bundle = mBaseUserRestrictions.get(userId);
1251 return (bundle != null && bundle.getBoolean(restrictionKey, false));
1252 }
1253 }
1254
1255 @Override
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001256 public void setUserRestriction(String key, boolean value, int userId) {
Fyodor Kupolovd4b26042015-07-27 14:30:59 -07001257 checkManageUsersPermission("setUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001258 if (!UserRestrictionsUtils.isValidRestriction(key)) {
1259 return;
1260 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001261 synchronized (mRestrictionsLock) {
1262 // Note we can't modify Bundles stored in mBaseUserRestrictions directly, so create
1263 // a copy.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001264 final Bundle newRestrictions = UserRestrictionsUtils.clone(
1265 mBaseUserRestrictions.get(userId));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001266 newRestrictions.putBoolean(key, value);
1267
Fyodor Kupolov82402752015-10-28 14:54:51 -07001268 updateUserRestrictionsInternalLR(newRestrictions, userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001269 }
1270 }
1271
Makoto Onuki068c54a2015-10-13 14:34:03 -07001272 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001273 * Optionally updating user restrictions, calculate the effective user restrictions and also
1274 * propagate to other services and system settings.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001275 *
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001276 * @param newRestrictions User restrictions to set.
1277 * If null, will not update user restrictions and only does the propagation.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001278 * @param userId target user ID.
1279 */
1280 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001281 private void updateUserRestrictionsInternalLR(
Makoto Onuki068c54a2015-10-13 14:34:03 -07001282 @Nullable Bundle newRestrictions, int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001283
1284 final Bundle prevAppliedRestrictions = UserRestrictionsUtils.nonNull(
1285 mAppliedUserRestrictions.get(userId));
1286
1287 // Update base restrictions.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001288 if (newRestrictions != null) {
1289 // If newRestrictions == the current one, it's probably a bug.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001290 final Bundle prevBaseRestrictions = mBaseUserRestrictions.get(userId);
1291
1292 Preconditions.checkState(prevBaseRestrictions != newRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001293 Preconditions.checkState(mCachedEffectiveUserRestrictions.get(userId)
1294 != newRestrictions);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001295
1296 if (!UserRestrictionsUtils.areEqual(prevBaseRestrictions, newRestrictions)) {
1297 mBaseUserRestrictions.put(userId, newRestrictions);
Amith Yamasani12747872015-12-07 14:19:49 -08001298 scheduleWriteUser(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001299 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001300 }
1301
Fyodor Kupolov82402752015-10-28 14:54:51 -07001302 final Bundle effective = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001303
Makoto Onuki759a7632015-10-28 16:43:10 -07001304 mCachedEffectiveUserRestrictions.put(userId, effective);
1305
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001306 // Apply the new restrictions.
Makoto Onuki4f160732015-10-27 17:15:38 -07001307 if (DBG) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001308 debug("Applying user restrictions: userId=" + userId
1309 + " new=" + effective + " prev=" + prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001310 }
1311
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001312 if (mAppOpsService != null) { // We skip it until system-ready.
Fyodor Kupolovec30ca32016-06-16 15:09:29 -07001313 mHandler.post(new Runnable() {
1314 @Override
1315 public void run() {
1316 try {
1317 mAppOpsService.setUserRestrictions(effective, mUserRestriconToken, userId);
1318 } catch (RemoteException e) {
1319 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
1320 }
1321 }
1322 });
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001323 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001324
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001325 propagateUserRestrictionsLR(userId, effective, prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001326
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001327 mAppliedUserRestrictions.put(userId, new Bundle(effective));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001328 }
1329
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001330 private void propagateUserRestrictionsLR(final int userId,
Makoto Onukid45a4a22015-11-02 17:17:38 -08001331 Bundle newRestrictions, Bundle prevRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001332 // Note this method doesn't touch any state, meaning it doesn't require mRestrictionsLock
1333 // actually, but we still need some kind of synchronization otherwise we might end up
1334 // calling listeners out-of-order, thus "LR".
1335
1336 if (UserRestrictionsUtils.areEqual(newRestrictions, prevRestrictions)) {
1337 return;
1338 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08001339
1340 final Bundle newRestrictionsFinal = new Bundle(newRestrictions);
1341 final Bundle prevRestrictionsFinal = new Bundle(prevRestrictions);
1342
1343 mHandler.post(new Runnable() {
1344 @Override
1345 public void run() {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07001346 UserRestrictionsUtils.applyUserRestrictions(
1347 mContext, userId, newRestrictionsFinal, prevRestrictionsFinal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001348
Makoto Onukid45a4a22015-11-02 17:17:38 -08001349 final UserRestrictionsListener[] listeners;
1350 synchronized (mUserRestrictionsListeners) {
1351 listeners = new UserRestrictionsListener[mUserRestrictionsListeners.size()];
1352 mUserRestrictionsListeners.toArray(listeners);
1353 }
1354 for (int i = 0; i < listeners.length; i++) {
1355 listeners[i].onUserRestrictionsChanged(userId,
1356 newRestrictionsFinal, prevRestrictionsFinal);
1357 }
1358 }
1359 });
1360 }
1361
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001362 // Package private for the inner class.
1363 void applyUserRestrictionsLR(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001364 updateUserRestrictionsInternalLR(null, userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001365 }
1366
1367 @GuardedBy("mRestrictionsLock")
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001368 // Package private for the inner class.
1369 void applyUserRestrictionsForAllUsersLR() {
1370 if (DBG) {
1371 debug("applyUserRestrictionsForAllUsersLR");
1372 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001373 // First, invalidate all cached values.
Makoto Onuki4f160732015-10-27 17:15:38 -07001374 mCachedEffectiveUserRestrictions.clear();
1375
Makoto Onuki068c54a2015-10-13 14:34:03 -07001376 // We don't want to call into ActivityManagerNative while taking a lock, so we'll call
1377 // it on a handler.
1378 final Runnable r = new Runnable() {
1379 @Override
1380 public void run() {
1381 // Then get the list of running users.
1382 final int[] runningUsers;
1383 try {
1384 runningUsers = ActivityManagerNative.getDefault().getRunningUserIds();
1385 } catch (RemoteException e) {
1386 Log.w(LOG_TAG, "Unable to access ActivityManagerNative");
1387 return;
1388 }
1389 // Then re-calculate the effective restrictions and apply, only for running users.
1390 // It's okay if a new user has started after the getRunningUserIds() call,
1391 // because we'll do the same thing (re-calculate the restrictions and apply)
1392 // when we start a user.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001393 synchronized (mRestrictionsLock) {
1394 for (int i = 0; i < runningUsers.length; i++) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001395 applyUserRestrictionsLR(runningUsers[i]);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001396 }
1397 }
1398 }
1399 };
1400 mHandler.post(r);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001401 }
1402
Amith Yamasani258848d2012-08-10 17:06:33 -07001403 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001404 * Check if we've hit the limit of how many users can be created.
1405 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001406 private boolean isUserLimitReached() {
1407 int count;
1408 synchronized (mUsersLock) {
1409 count = getAliveUsersExcludingGuestsCountLU();
1410 }
1411 return count >= UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001412 }
1413
1414 @Override
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001415 public boolean canAddMoreManagedProfiles(int userId, boolean allowedToRemoveOne) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001416 checkManageUsersPermission("check if more managed profiles can be added.");
1417 if (ActivityManager.isLowRamDeviceStatic()) {
1418 return false;
1419 }
Fyodor Kupolovb6157992015-06-05 15:32:28 -07001420 if (!mContext.getPackageManager().hasSystemFeature(
1421 PackageManager.FEATURE_MANAGED_USERS)) {
1422 return false;
1423 }
Nicolas Prevotb8186812015-08-06 15:00:03 +01001424 // Limit number of managed profiles that can be created
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001425 final int managedProfilesCount = getProfiles(userId, true).size() - 1;
1426 final int profilesRemovedCount = managedProfilesCount > 0 && allowedToRemoveOne ? 1 : 0;
1427 if (managedProfilesCount - profilesRemovedCount >= MAX_MANAGED_PROFILES) {
Nicolas Prevotb8186812015-08-06 15:00:03 +01001428 return false;
1429 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001430 synchronized(mUsersLock) {
1431 UserInfo userInfo = getUserInfoLU(userId);
Nicolas Prevotb8186812015-08-06 15:00:03 +01001432 if (!userInfo.canHaveProfile()) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001433 return false;
1434 }
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001435 int usersCountAfterRemoving = getAliveUsersExcludingGuestsCountLU()
1436 - profilesRemovedCount;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001437 // We allow creating a managed profile in the special case where there is only one user.
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001438 return usersCountAfterRemoving == 1
1439 || usersCountAfterRemoving < UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001440 }
1441 }
1442
Fyodor Kupolov82402752015-10-28 14:54:51 -07001443 private int getAliveUsersExcludingGuestsCountLU() {
Amith Yamasanif584f012014-05-19 17:57:25 -07001444 int aliveUserCount = 0;
1445 final int totalUserCount = mUsers.size();
1446 // Skip over users being removed
1447 for (int i = 0; i < totalUserCount; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001448 UserInfo user = mUsers.valueAt(i).info;
Amith Yamasani95ab7842014-08-11 17:09:26 -07001449 if (!mRemovingUserIds.get(user.id)
Amith Yamasani1df14732014-08-29 21:37:27 -07001450 && !user.isGuest() && !user.partial) {
Amith Yamasanif584f012014-05-19 17:57:25 -07001451 aliveUserCount++;
1452 }
1453 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001454 return aliveUserCount;
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001455 }
1456
1457 /**
Amith Yamasani195263742012-08-21 15:40:12 -07001458 * Enforces that only the system UID or root's UID or apps that have the
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001459 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} and
1460 * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL INTERACT_ACROSS_USERS_FULL}
1461 * permissions can make certain calls to the UserManager.
1462 *
1463 * @param message used as message if SecurityException is thrown
1464 * @throws SecurityException if the caller does not have enough privilege.
1465 */
1466 private static final void checkManageUserAndAcrossUsersFullPermission(String message) {
1467 final int uid = Binder.getCallingUid();
1468 if (uid != Process.SYSTEM_UID && uid != 0
1469 && ActivityManager.checkComponentPermission(
1470 Manifest.permission.MANAGE_USERS,
1471 uid, -1, true) != PackageManager.PERMISSION_GRANTED
1472 && ActivityManager.checkComponentPermission(
1473 Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1474 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
1475 throw new SecurityException(
1476 "You need MANAGE_USERS and INTERACT_ACROSS_USERS_FULL permission to: "
1477 + message);
1478 }
1479 }
1480
1481 /**
1482 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001483 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -07001484 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -07001485 *
1486 * @param message used as message if SecurityException is thrown
1487 * @throws SecurityException if the caller is not system or root
Tony Mak4dc008c2016-03-16 10:46:49 +00001488 * @see #hasManageUsersPermission()
Amith Yamasani258848d2012-08-10 17:06:33 -07001489 */
Amith Yamasanibe465322014-04-24 13:45:17 -07001490 private static final void checkManageUsersPermission(String message) {
Tony Mak4dc008c2016-03-16 10:46:49 +00001491 if (!hasManageUsersPermission()) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001492 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
1493 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -04001494 }
1495
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001496 /**
Sudheer Shankaf5cea032016-06-08 17:13:24 -07001497 * Enforces that only the system UID or root's UID or apps that have the
1498 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or
1499 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS}
1500 * can make certain calls to the UserManager.
1501 *
1502 * @param message used as message if SecurityException is thrown
1503 * @throws SecurityException if the caller is not system or root
1504 * @see #hasManageOrCreateUsersPermission()
1505 */
1506 private static final void checkManageOrCreateUsersPermission(String message) {
1507 if (!hasManageOrCreateUsersPermission()) {
1508 throw new SecurityException(
1509 "You either need MANAGE_USERS or CREATE_USERS permission to: " + message);
1510 }
1511 }
1512
1513 /**
1514 * Similar to {@link #checkManageOrCreateUsersPermission(String)} but when the caller is tries
1515 * to create user/profiles other than what is allowed for
1516 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS} permission, then it will only
1517 * allow callers with {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} permission.
1518 */
1519 private static final void checkManageOrCreateUsersPermission(int creationFlags) {
1520 if ((creationFlags & ~ALLOWED_FLAGS_FOR_CREATE_USERS_PERMISSION) == 0) {
1521 if (!hasManageOrCreateUsersPermission()) {
1522 throw new SecurityException("You either need MANAGE_USERS or CREATE_USERS "
1523 + "permission to create an user with flags: " + creationFlags);
1524 }
1525 } else if (!hasManageUsersPermission()) {
1526 throw new SecurityException("You need MANAGE_USERS permission to create an user "
1527 + " with flags: " + creationFlags);
1528 }
1529 }
1530
1531 /**
Tony Mak4dc008c2016-03-16 10:46:49 +00001532 * @return whether the calling UID is system UID or root's UID or the calling app has the
1533 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}.
1534 */
1535 private static final boolean hasManageUsersPermission() {
1536 final int callingUid = Binder.getCallingUid();
1537 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
1538 || callingUid == Process.ROOT_UID
1539 || ActivityManager.checkComponentPermission(
1540 android.Manifest.permission.MANAGE_USERS,
1541 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED;
1542 }
1543
1544 /**
Sudheer Shankaf5cea032016-06-08 17:13:24 -07001545 * @return whether the calling UID is system UID or root's UID or the calling app has the
1546 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or
1547 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS}.
1548 */
1549 private static final boolean hasManageOrCreateUsersPermission() {
1550 final int callingUid = Binder.getCallingUid();
1551 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
1552 || callingUid == Process.ROOT_UID
1553 || ActivityManager.checkComponentPermission(
1554 android.Manifest.permission.MANAGE_USERS,
1555 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED
1556 || ActivityManager.checkComponentPermission(
1557 android.Manifest.permission.CREATE_USERS,
1558 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED;
1559 }
1560
1561 /**
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001562 * Enforces that only the system UID or root's UID (on any user) can make certain calls to the
1563 * UserManager.
1564 *
1565 * @param message used as message if SecurityException is thrown
1566 * @throws SecurityException if the caller is not system or root
1567 */
1568 private static void checkSystemOrRoot(String message) {
1569 final int uid = Binder.getCallingUid();
1570 if (!UserHandle.isSameApp(uid, Process.SYSTEM_UID) && uid != Process.ROOT_UID) {
1571 throw new SecurityException("Only system may: " + message);
1572 }
1573 }
1574
Fyodor Kupolov82402752015-10-28 14:54:51 -07001575 private void writeBitmapLP(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001576 try {
1577 File dir = new File(mUsersDir, Integer.toString(info.id));
1578 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +01001579 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001580 if (!dir.exists()) {
1581 dir.mkdir();
1582 FileUtils.setPermissions(
1583 dir.getPath(),
1584 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
1585 -1, -1);
1586 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001587 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +01001588 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001589 && tmp.renameTo(file) && SELinux.restorecon(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -07001590 info.iconPath = file.getAbsolutePath();
1591 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001592 try {
1593 os.close();
1594 } catch (IOException ioe) {
1595 // What the ... !
1596 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001597 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001598 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001599 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001600 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001601 }
1602
Amith Yamasani0b285492011-04-14 17:35:23 -07001603 /**
1604 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
1605 * cache it elsewhere.
1606 * @return the array of user ids.
1607 */
Dianne Hackborn1676c852012-09-10 14:52:30 -07001608 public int[] getUserIds() {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001609 synchronized (mUsersLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001610 return mUserIds;
1611 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001612 }
1613
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001614 private void readUserListLP() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001615 if (!mUserListFile.exists()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001616 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001617 return;
1618 }
1619 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001620 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001621 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001622 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001623 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001624 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001625 int type;
1626 while ((type = parser.next()) != XmlPullParser.START_TAG
1627 && type != XmlPullParser.END_DOCUMENT) {
Amith Yamasani12747872015-12-07 14:19:49 -08001628 // Skip
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001629 }
1630
1631 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001632 Slog.e(LOG_TAG, "Unable to read user list");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001633 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001634 return;
1635 }
1636
Amith Yamasani2a003292012-08-14 18:25:45 -07001637 mNextSerialNumber = -1;
1638 if (parser.getName().equals(TAG_USERS)) {
1639 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
1640 if (lastSerialNumber != null) {
1641 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
1642 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001643 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
1644 if (versionNumber != null) {
1645 mUserVersion = Integer.parseInt(versionNumber);
1646 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001647 }
1648
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001649 final Bundle newDevicePolicyGlobalUserRestrictions = new Bundle();
1650
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001651 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301652 if (type == XmlPullParser.START_TAG) {
1653 final String name = parser.getName();
1654 if (name.equals(TAG_USER)) {
1655 String id = parser.getAttributeValue(null, ATTR_ID);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001656
Amith Yamasani12747872015-12-07 14:19:49 -08001657 UserData userData = readUserLP(Integer.parseInt(id));
1658
1659 if (userData != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001660 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001661 mUsers.put(userData.info.id, userData);
1662 if (mNextSerialNumber < 0
1663 || mNextSerialNumber <= userData.info.id) {
1664 mNextSerialNumber = userData.info.id + 1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001665 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301666 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001667 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301668 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -08001669 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1670 && type != XmlPullParser.END_TAG) {
1671 if (type == XmlPullParser.START_TAG) {
1672 if (parser.getName().equals(TAG_RESTRICTIONS)) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001673 synchronized (mGuestRestrictions) {
1674 UserRestrictionsUtils
1675 .readRestrictions(parser, mGuestRestrictions);
1676 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001677 } else if (parser.getName().equals(TAG_DEVICE_POLICY_RESTRICTIONS)
1678 ) {
1679 UserRestrictionsUtils.readRestrictions(parser,
1680 newDevicePolicyGlobalUserRestrictions);
Amith Yamasanida0b1682014-11-21 12:58:17 -08001681 }
1682 break;
1683 }
1684 }
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001685 } else if (name.equals(TAG_GLOBAL_RESTRICTION_OWNER_ID)) {
1686 String ownerUserId = parser.getAttributeValue(null, ATTR_ID);
1687 if (ownerUserId != null) {
1688 mGlobalRestrictionOwnerUserId = Integer.parseInt(ownerUserId);
1689 }
Amith Yamasani258848d2012-08-10 17:06:33 -07001690 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001691 }
1692 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001693 synchronized (mRestrictionsLock) {
1694 mDevicePolicyGlobalUserRestrictions = newDevicePolicyGlobalUserRestrictions;
1695 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001696 updateUserIds();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001697 upgradeIfNecessaryLP();
1698 } catch (IOException | XmlPullParserException e) {
1699 fallbackToSingleUserLP();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001700 } finally {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001701 IoUtils.closeQuietly(fis);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001702 }
1703 }
1704
Amith Yamasani6f34b412012-10-22 18:19:27 -07001705 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -08001706 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -07001707 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001708 private void upgradeIfNecessaryLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001709 final int originalVersion = mUserVersion;
Amith Yamasani6f34b412012-10-22 18:19:27 -07001710 int userVersion = mUserVersion;
1711 if (userVersion < 1) {
1712 // Assign a proper name for the owner, if not initialized correctly before
Amith Yamasani12747872015-12-07 14:19:49 -08001713 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
1714 if ("Primary".equals(userData.info.name)) {
1715 userData.info.name =
1716 mContext.getResources().getString(com.android.internal.R.string.owner_name);
1717 scheduleWriteUser(userData);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001718 }
1719 userVersion = 1;
1720 }
1721
Amith Yamasanibc9625052012-11-15 14:39:18 -08001722 if (userVersion < 2) {
1723 // Owner should be marked as initialized
Amith Yamasani12747872015-12-07 14:19:49 -08001724 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
1725 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1726 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
1727 scheduleWriteUser(userData);
Amith Yamasanibc9625052012-11-15 14:39:18 -08001728 }
1729 userVersion = 2;
1730 }
1731
Amith Yamasani350962c2013-08-06 11:18:53 -07001732
Amith Yamasani5e486f52013-08-07 11:06:44 -07001733 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -07001734 userVersion = 4;
1735 }
1736
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001737 if (userVersion < 5) {
1738 initDefaultGuestRestrictions();
1739 userVersion = 5;
1740 }
1741
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001742 if (userVersion < 6) {
1743 final boolean splitSystemUser = UserManager.isSplitSystemUser();
Fyodor Kupolov82402752015-10-28 14:54:51 -07001744 synchronized (mUsersLock) {
1745 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001746 UserData userData = mUsers.valueAt(i);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001747 // In non-split mode, only user 0 can have restricted profiles
Amith Yamasani12747872015-12-07 14:19:49 -08001748 if (!splitSystemUser && userData.info.isRestricted()
1749 && (userData.info.restrictedProfileParentId
1750 == UserInfo.NO_PROFILE_GROUP_ID)) {
1751 userData.info.restrictedProfileParentId = UserHandle.USER_SYSTEM;
1752 scheduleWriteUser(userData);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001753 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001754 }
1755 }
1756 userVersion = 6;
1757 }
1758
Amith Yamasani6f34b412012-10-22 18:19:27 -07001759 if (userVersion < USER_VERSION) {
1760 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
1761 + USER_VERSION);
1762 } else {
1763 mUserVersion = userVersion;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001764
1765 if (originalVersion < mUserVersion) {
1766 writeUserListLP();
1767 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001768 }
1769 }
1770
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001771 private void fallbackToSingleUserLP() {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001772 int flags = UserInfo.FLAG_INITIALIZED;
1773 // In split system user mode, the admin and primary flags are assigned to the first human
1774 // user.
1775 if (!UserManager.isSplitSystemUser()) {
1776 flags |= UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY;
1777 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001778 // Create the system user
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001779 UserInfo system = new UserInfo(UserHandle.USER_SYSTEM, null, null, flags);
Amith Yamasani12747872015-12-07 14:19:49 -08001780 UserData userData = new UserData();
1781 userData.info = system;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001782 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001783 mUsers.put(system.id, userData);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001784 }
Amith Yamasani634cf312012-10-04 17:34:21 -07001785 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -04001786 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -08001787
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001788 Bundle restrictions = new Bundle();
Makoto Onuki068c54a2015-10-13 14:34:03 -07001789 synchronized (mRestrictionsLock) {
1790 mBaseUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions);
1791 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001792
Fyodor Kupolov82402752015-10-28 14:54:51 -07001793 updateUserIds();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001794 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001795
Amith Yamasani12747872015-12-07 14:19:49 -08001796 writeUserLP(userData);
Jeff Sharkeycd575992016-03-29 14:12:49 -06001797 writeUserListLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001798 }
1799
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001800 private String getOwnerName() {
1801 return mContext.getResources().getString(com.android.internal.R.string.owner_name);
1802 }
1803
Amith Yamasani12747872015-12-07 14:19:49 -08001804 private void scheduleWriteUser(UserData UserData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001805 if (DBG) {
1806 debug("scheduleWriteUser");
1807 }
Makoto Onuki9e935a32015-11-06 14:24:24 -08001808 // No need to wrap it within a lock -- worst case, we'll just post the same message
1809 // twice.
Amith Yamasani12747872015-12-07 14:19:49 -08001810 if (!mHandler.hasMessages(WRITE_USER_MSG, UserData)) {
1811 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, UserData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001812 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
1813 }
1814 }
1815
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001816 /*
1817 * Writes the user file in this format:
1818 *
1819 * <user flags="20039023" id="0">
1820 * <name>Primary</name>
1821 * </user>
1822 */
Amith Yamasani12747872015-12-07 14:19:49 -08001823 private void writeUserLP(UserData userData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001824 if (DBG) {
Amith Yamasani12747872015-12-07 14:19:49 -08001825 debug("writeUserLP " + userData);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001826 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001827 FileOutputStream fos = null;
Amith Yamasani12747872015-12-07 14:19:49 -08001828 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userData.info.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001829 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001830 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001831 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1832
1833 // XmlSerializer serializer = XmlUtils.serializerInstance();
1834 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001835 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001836 serializer.startDocument(null, true);
1837 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1838
Amith Yamasani12747872015-12-07 14:19:49 -08001839 final UserInfo userInfo = userData.info;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001840 serializer.startTag(null, TAG_USER);
1841 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
Amith Yamasani2a003292012-08-14 18:25:45 -07001842 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001843 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Amith Yamasani920ace02012-09-20 22:15:37 -07001844 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
1845 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
1846 Long.toString(userInfo.lastLoggedInTime));
Jeff Sharkeycd575992016-03-29 14:12:49 -06001847 if (userInfo.lastLoggedInFingerprint != null) {
1848 serializer.attribute(null, ATTR_LAST_LOGGED_IN_FINGERPRINT,
1849 userInfo.lastLoggedInFingerprint);
1850 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001851 if (userInfo.iconPath != null) {
1852 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
1853 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001854 if (userInfo.partial) {
1855 serializer.attribute(null, ATTR_PARTIAL, "true");
1856 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001857 if (userInfo.guestToRemove) {
1858 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
1859 }
Kenny Guy2a764942014-04-02 13:29:20 +01001860 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
1861 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
1862 Integer.toString(userInfo.profileGroupId));
Kenny Guya52dc3e2014-02-11 15:33:14 +00001863 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001864 if (userInfo.restrictedProfileParentId != UserInfo.NO_PROFILE_GROUP_ID) {
1865 serializer.attribute(null, ATTR_RESTRICTED_PROFILE_PARENT_ID,
1866 Integer.toString(userInfo.restrictedProfileParentId));
1867 }
Amith Yamasani12747872015-12-07 14:19:49 -08001868 // Write seed data
1869 if (userData.persistSeedData) {
1870 if (userData.seedAccountName != null) {
1871 serializer.attribute(null, ATTR_SEED_ACCOUNT_NAME, userData.seedAccountName);
1872 }
1873 if (userData.seedAccountType != null) {
1874 serializer.attribute(null, ATTR_SEED_ACCOUNT_TYPE, userData.seedAccountType);
1875 }
1876 }
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001877 if (userInfo.name != null) {
1878 serializer.startTag(null, TAG_NAME);
1879 serializer.text(userInfo.name);
1880 serializer.endTag(null, TAG_NAME);
1881 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001882 synchronized (mRestrictionsLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001883 UserRestrictionsUtils.writeRestrictions(serializer,
1884 mBaseUserRestrictions.get(userInfo.id), TAG_RESTRICTIONS);
1885 UserRestrictionsUtils.writeRestrictions(serializer,
1886 mDevicePolicyLocalUserRestrictions.get(userInfo.id),
1887 TAG_DEVICE_POLICY_RESTRICTIONS);
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001888 }
Amith Yamasani12747872015-12-07 14:19:49 -08001889
1890 if (userData.account != null) {
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001891 serializer.startTag(null, TAG_ACCOUNT);
Amith Yamasani12747872015-12-07 14:19:49 -08001892 serializer.text(userData.account);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001893 serializer.endTag(null, TAG_ACCOUNT);
1894 }
1895
Amith Yamasani12747872015-12-07 14:19:49 -08001896 if (userData.persistSeedData && userData.seedAccountOptions != null) {
1897 serializer.startTag(null, TAG_SEED_ACCOUNT_OPTIONS);
1898 userData.seedAccountOptions.saveToXml(serializer);
1899 serializer.endTag(null, TAG_SEED_ACCOUNT_OPTIONS);
1900 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001901 serializer.endTag(null, TAG_USER);
1902
1903 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001904 userFile.finishWrite(fos);
1905 } catch (Exception ioe) {
Jeff Sharkeycd575992016-03-29 14:12:49 -06001906 Slog.e(LOG_TAG, "Error writing user info " + userData.info.id, ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -07001907 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001908 }
1909 }
1910
1911 /*
1912 * Writes the user list file in this format:
1913 *
Amith Yamasani2a003292012-08-14 18:25:45 -07001914 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001915 * <user id="0"></user>
1916 * <user id="2"></user>
1917 * </users>
1918 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001919 private void writeUserListLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001920 if (DBG) {
1921 debug("writeUserList");
1922 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001923 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001924 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001925 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001926 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001927 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1928
1929 // XmlSerializer serializer = XmlUtils.serializerInstance();
1930 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001931 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001932 serializer.startDocument(null, true);
1933 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1934
1935 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -07001936 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -07001937 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001938
Adam Lesinskieddeb492014-09-08 17:50:03 -07001939 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001940 synchronized (mGuestRestrictions) {
1941 UserRestrictionsUtils
1942 .writeRestrictions(serializer, mGuestRestrictions, TAG_RESTRICTIONS);
1943 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301944 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001945 synchronized (mRestrictionsLock) {
1946 UserRestrictionsUtils.writeRestrictions(serializer,
1947 mDevicePolicyGlobalUserRestrictions, TAG_DEVICE_POLICY_RESTRICTIONS);
1948 }
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001949 serializer.startTag(null, TAG_GLOBAL_RESTRICTION_OWNER_ID);
1950 serializer.attribute(null, ATTR_ID, Integer.toString(mGlobalRestrictionOwnerUserId));
1951 serializer.endTag(null, TAG_GLOBAL_RESTRICTION_OWNER_ID);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001952 int[] userIdsToWrite;
1953 synchronized (mUsersLock) {
1954 userIdsToWrite = new int[mUsers.size()];
1955 for (int i = 0; i < userIdsToWrite.length; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001956 UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001957 userIdsToWrite[i] = user.id;
1958 }
1959 }
1960 for (int id : userIdsToWrite) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001961 serializer.startTag(null, TAG_USER);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001962 serializer.attribute(null, ATTR_ID, Integer.toString(id));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001963 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001964 }
1965
1966 serializer.endTag(null, TAG_USERS);
1967
1968 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001969 userListFile.finishWrite(fos);
1970 } catch (Exception e) {
1971 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -07001972 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001973 }
1974 }
1975
Amith Yamasani12747872015-12-07 14:19:49 -08001976 private UserData readUserLP(int id) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001977 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -07001978 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001979 String name = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001980 String account = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001981 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -07001982 long creationTime = 0L;
1983 long lastLoggedInTime = 0L;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06001984 String lastLoggedInFingerprint = null;
Kenny Guy2a764942014-04-02 13:29:20 +01001985 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001986 int restrictedProfileParentId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001987 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001988 boolean guestToRemove = false;
Amith Yamasani12747872015-12-07 14:19:49 -08001989 boolean persistSeedData = false;
1990 String seedAccountName = null;
1991 String seedAccountType = null;
1992 PersistableBundle seedAccountOptions = null;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001993 Bundle baseRestrictions = new Bundle();
1994 Bundle localRestrictions = new Bundle();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001995
1996 FileInputStream fis = null;
1997 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001998 AtomicFile userFile =
Amith Yamasanifc95e702013-09-26 13:20:17 -07001999 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
Amith Yamasani2a003292012-08-14 18:25:45 -07002000 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002001 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002002 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002003 int type;
2004 while ((type = parser.next()) != XmlPullParser.START_TAG
2005 && type != XmlPullParser.END_DOCUMENT) {
Amith Yamasani12747872015-12-07 14:19:49 -08002006 // Skip
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002007 }
2008
2009 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07002010 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002011 return null;
2012 }
2013
2014 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -07002015 int storedId = readIntAttribute(parser, ATTR_ID, -1);
2016 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -07002017 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002018 return null;
2019 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002020 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
2021 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002022 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -07002023 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
2024 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002025 lastLoggedInFingerprint = parser.getAttributeValue(null,
2026 ATTR_LAST_LOGGED_IN_FINGERPRINT);
Kenny Guy2a764942014-04-02 13:29:20 +01002027 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
2028 UserInfo.NO_PROFILE_GROUP_ID);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002029 restrictedProfileParentId = readIntAttribute(parser,
2030 ATTR_RESTRICTED_PROFILE_PARENT_ID, UserInfo.NO_PROFILE_GROUP_ID);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002031 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
2032 if ("true".equals(valueString)) {
2033 partial = true;
2034 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002035 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
2036 if ("true".equals(valueString)) {
2037 guestToRemove = true;
2038 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002039
Amith Yamasani12747872015-12-07 14:19:49 -08002040 seedAccountName = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_NAME);
2041 seedAccountType = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_TYPE);
2042 if (seedAccountName != null || seedAccountType != null) {
2043 persistSeedData = true;
2044 }
2045
Amith Yamasanie4cf7342012-12-17 11:12:09 -08002046 int outerDepth = parser.getDepth();
2047 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2048 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2049 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2050 continue;
2051 }
2052 String tag = parser.getName();
2053 if (TAG_NAME.equals(tag)) {
2054 type = parser.next();
2055 if (type == XmlPullParser.TEXT) {
2056 name = parser.getText();
2057 }
2058 } else if (TAG_RESTRICTIONS.equals(tag)) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002059 UserRestrictionsUtils.readRestrictions(parser, baseRestrictions);
2060 } else if (TAG_DEVICE_POLICY_RESTRICTIONS.equals(tag)) {
2061 UserRestrictionsUtils.readRestrictions(parser, localRestrictions);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08002062 } else if (TAG_ACCOUNT.equals(tag)) {
2063 type = parser.next();
2064 if (type == XmlPullParser.TEXT) {
2065 account = parser.getText();
2066 }
Amith Yamasani12747872015-12-07 14:19:49 -08002067 } else if (TAG_SEED_ACCOUNT_OPTIONS.equals(tag)) {
2068 seedAccountOptions = PersistableBundle.restoreFromXml(parser);
2069 persistSeedData = true;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002070 }
2071 }
2072 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002073
Amith Yamasani12747872015-12-07 14:19:49 -08002074 // Create the UserInfo object that gets passed around
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002075 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -07002076 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -07002077 userInfo.creationTime = creationTime;
2078 userInfo.lastLoggedInTime = lastLoggedInTime;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002079 userInfo.lastLoggedInFingerprint = lastLoggedInFingerprint;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002080 userInfo.partial = partial;
Adam Lesinskieddeb492014-09-08 17:50:03 -07002081 userInfo.guestToRemove = guestToRemove;
Kenny Guy2a764942014-04-02 13:29:20 +01002082 userInfo.profileGroupId = profileGroupId;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002083 userInfo.restrictedProfileParentId = restrictedProfileParentId;
Amith Yamasani12747872015-12-07 14:19:49 -08002084
2085 // Create the UserData object that's internal to this class
2086 UserData userData = new UserData();
2087 userData.info = userInfo;
2088 userData.account = account;
2089 userData.seedAccountName = seedAccountName;
2090 userData.seedAccountType = seedAccountType;
2091 userData.persistSeedData = persistSeedData;
2092 userData.seedAccountOptions = seedAccountOptions;
2093
Makoto Onuki068c54a2015-10-13 14:34:03 -07002094 synchronized (mRestrictionsLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002095 mBaseUserRestrictions.put(id, baseRestrictions);
2096 mDevicePolicyLocalUserRestrictions.put(id, localRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002097 }
Amith Yamasani12747872015-12-07 14:19:49 -08002098 return userData;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002099 } catch (IOException ioe) {
2100 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08002101 } finally {
2102 if (fis != null) {
2103 try {
2104 fis.close();
2105 } catch (IOException e) {
2106 }
2107 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002108 }
2109 return null;
2110 }
2111
Amith Yamasani920ace02012-09-20 22:15:37 -07002112 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
2113 String valueString = parser.getAttributeValue(null, attr);
2114 if (valueString == null) return defaultValue;
2115 try {
2116 return Integer.parseInt(valueString);
2117 } catch (NumberFormatException nfe) {
2118 return defaultValue;
2119 }
2120 }
2121
2122 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
2123 String valueString = parser.getAttributeValue(null, attr);
2124 if (valueString == null) return defaultValue;
2125 try {
2126 return Long.parseLong(valueString);
2127 } catch (NumberFormatException nfe) {
2128 return defaultValue;
2129 }
2130 }
2131
Amith Yamasanib82add22013-07-09 11:24:44 -07002132 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002133 * Removes the app restrictions file for a specific package and user id, if it exists.
2134 */
2135 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
2136 synchronized (mPackagesLock) {
2137 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07002138 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002139 if (resFile.exists()) {
2140 resFile.delete();
2141 }
2142 }
2143 }
2144
Kenny Guya52dc3e2014-02-11 15:33:14 +00002145 @Override
Kenny Guy2a764942014-04-02 13:29:20 +01002146 public UserInfo createProfileForUser(String name, int flags, int userId) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002147 checkManageOrCreateUsersPermission(flags);
Kenny Guy2a764942014-04-02 13:29:20 +01002148 return createUserInternal(name, flags, userId);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002149 }
2150
Amith Yamasani258848d2012-08-10 17:06:33 -07002151 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07002152 public UserInfo createUser(String name, int flags) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002153 checkManageOrCreateUsersPermission(flags);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00002154 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002155 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07002156
Jessica Hummelbe81c802014-04-22 15:49:22 +01002157 private UserInfo createUserInternal(String name, int flags, int parentId) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002158 if (hasUserRestriction(UserManager.DISALLOW_ADD_USER, UserHandle.getCallingUserId())) {
Julia Reynolds75175022014-06-26 16:35:00 -04002159 Log.w(LOG_TAG, "Cannot add user. DISALLOW_ADD_USER is enabled.");
2160 return null;
2161 }
phweisse9c44062016-02-10 12:57:38 +01002162 return createUserInternalUnchecked(name, flags, parentId);
2163 }
2164
2165 private UserInfo createUserInternalUnchecked(String name, int flags, int parentId) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07002166 if (ActivityManager.isLowRamDeviceStatic()) {
2167 return null;
2168 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07002169 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Nicolas Prevot12678a92015-05-13 12:15:03 -07002170 final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002171 final boolean isRestricted = (flags & UserInfo.FLAG_RESTRICTED) != 0;
Amith Yamasani52c21e32016-05-31 09:12:20 -07002172 final boolean isDemo = (flags & UserInfo.FLAG_DEMO) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002173 final long ident = Binder.clearCallingIdentity();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002174 UserInfo userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08002175 UserData userData;
Amith Yamasanibb054c92015-07-09 14:16:27 -07002176 final int userId;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002177 try {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002178 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002179 UserData parent = null;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002180 if (parentId != UserHandle.USER_NULL) {
2181 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002182 parent = getUserDataLU(parentId);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00002183 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002184 if (parent == null) return null;
2185 }
2186 if (isManagedProfile && !canAddMoreManagedProfiles(parentId, false)) {
2187 Log.e(LOG_TAG, "Cannot add more managed profiles for user " + parentId);
2188 return null;
2189 }
Amith Yamasani52c21e32016-05-31 09:12:20 -07002190 if (!isGuest && !isManagedProfile && !isDemo && isUserLimitReached()) {
2191 // If we're not adding a guest/demo user or a managed profile and the limit has
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002192 // been reached, cannot add a user.
2193 return null;
2194 }
2195 // If we're adding a guest and there already exists one, bail.
2196 if (isGuest && findCurrentGuestUser() != null) {
2197 return null;
2198 }
2199 // In legacy mode, restricted profile's parent can only be the owner user
2200 if (isRestricted && !UserManager.isSplitSystemUser()
2201 && (parentId != UserHandle.USER_SYSTEM)) {
2202 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
2203 return null;
2204 }
2205 if (isRestricted && UserManager.isSplitSystemUser()) {
2206 if (parent == null) {
2207 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be "
2208 + "specified");
Nicolas Prevot12678a92015-05-13 12:15:03 -07002209 return null;
2210 }
Amith Yamasani12747872015-12-07 14:19:49 -08002211 if (!parent.info.canHaveProfile()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002212 Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be "
2213 + "created for the specified parent user id " + parentId);
Amith Yamasani95ab7842014-08-11 17:09:26 -07002214 return null;
2215 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002216 }
Suprabh Shuklacc30b0e72016-05-20 14:41:22 -07002217 if (!UserManager.isSplitSystemUser() && (flags & UserInfo.FLAG_EPHEMERAL) != 0
2218 && (flags & UserInfo.FLAG_DEMO) == 0) {
Lenka Trochtova024f9792016-02-17 13:55:17 +01002219 Log.e(LOG_TAG,
2220 "Ephemeral users are supported on split-system-user systems only.");
2221 return null;
2222 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002223 // In split system user mode, we assign the first human user the primary flag.
2224 // And if there is no device owner, we also assign the admin flag to primary user.
2225 if (UserManager.isSplitSystemUser()
2226 && !isGuest && !isManagedProfile && getPrimaryUser() == null) {
2227 flags |= UserInfo.FLAG_PRIMARY;
Makoto Onukie7927da2015-11-25 10:05:17 -08002228 synchronized (mUsersLock) {
2229 if (!mIsDeviceManaged) {
2230 flags |= UserInfo.FLAG_ADMIN;
2231 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07002232 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002233 }
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002234
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002235 userId = getNextAvailableId();
2236 Environment.getUserSystemDirectory(userId).mkdirs();
Lenka Trochtova02fee152015-12-22 14:26:18 +01002237 boolean ephemeralGuests = Resources.getSystem()
2238 .getBoolean(com.android.internal.R.bool.config_guestUserEphemeral);
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002239
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002240 synchronized (mUsersLock) {
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002241 // Add ephemeral flag to guests/users if required. Also inherit it from parent.
2242 if ((isGuest && ephemeralGuests) || mForceEphemeralUsers
2243 || (parent != null && parent.info.isEphemeral())) {
2244 flags |= UserInfo.FLAG_EPHEMERAL;
2245 }
2246
2247 userInfo = new UserInfo(userId, name, null, flags);
2248 userInfo.serialNumber = mNextSerialNumber++;
2249 long now = System.currentTimeMillis();
2250 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
2251 userInfo.partial = true;
Fyodor Kupolov83c24242016-03-31 13:30:42 -07002252 userInfo.lastLoggedInFingerprint = Build.FINGERPRINT;
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002253 userData = new UserData();
2254 userData.info = userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08002255 mUsers.put(userId, userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002256 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06002257 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002258 writeUserListLP();
2259 if (parent != null) {
2260 if (isManagedProfile) {
Amith Yamasani12747872015-12-07 14:19:49 -08002261 if (parent.info.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
2262 parent.info.profileGroupId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002263 writeUserLP(parent);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002264 }
Amith Yamasani12747872015-12-07 14:19:49 -08002265 userInfo.profileGroupId = parent.info.profileGroupId;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002266 } else if (isRestricted) {
Amith Yamasani12747872015-12-07 14:19:49 -08002267 if (parent.info.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) {
2268 parent.info.restrictedProfileParentId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002269 writeUserLP(parent);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002270 }
Amith Yamasani12747872015-12-07 14:19:49 -08002271 userInfo.restrictedProfileParentId = parent.info.restrictedProfileParentId;
Makoto Onuki068c54a2015-10-13 14:34:03 -07002272 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002273 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07002274 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002275 final StorageManager storage = mContext.getSystemService(StorageManager.class);
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002276 storage.createUserKey(userId, userInfo.serialNumber, userInfo.isEphemeral());
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002277 mPm.prepareUserData(userId, userInfo.serialNumber,
Jeff Sharkey47f71082016-02-01 17:03:54 -07002278 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002279 mPm.createNewUser(userId);
2280 userInfo.partial = false;
2281 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002282 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002283 }
2284 updateUserIds();
2285 Bundle restrictions = new Bundle();
Fyodor Kupolove04462c2015-11-30 15:02:53 -08002286 if (isGuest) {
2287 synchronized (mGuestRestrictions) {
2288 restrictions.putAll(mGuestRestrictions);
2289 }
2290 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002291 synchronized (mRestrictionsLock) {
2292 mBaseUserRestrictions.append(userId, restrictions);
2293 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002294 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
2295 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
2296 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
2297 android.Manifest.permission.MANAGE_USERS);
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -08002298 MetricsLogger.count(mContext, isGuest ? TRON_GUEST_CREATED : TRON_USER_CREATED, 1);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002299 } finally {
2300 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07002301 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002302 return userInfo;
2303 }
2304
Amith Yamasani0b285492011-04-14 17:35:23 -07002305 /**
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002306 * @hide
2307 */
Amith Yamasani12747872015-12-07 14:19:49 -08002308 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002309 public UserInfo createRestrictedProfile(String name, int parentUserId) {
Sudheer Shanka53d41472016-06-16 09:11:08 -07002310 checkManageOrCreateUsersPermission("setupRestrictedProfile");
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002311 final UserInfo user = createProfileForUser(name, UserInfo.FLAG_RESTRICTED, parentUserId);
2312 if (user == null) {
2313 return null;
2314 }
Fyodor Kupolov9e912ba2016-02-09 18:29:43 -08002315 long identity = Binder.clearCallingIdentity();
2316 try {
2317 setUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, true, user.id);
2318 // Change the setting before applying the DISALLOW_SHARE_LOCATION restriction, otherwise
2319 // the putIntForUser() will fail.
2320 android.provider.Settings.Secure.putIntForUser(mContext.getContentResolver(),
2321 android.provider.Settings.Secure.LOCATION_MODE,
2322 android.provider.Settings.Secure.LOCATION_MODE_OFF, user.id);
2323 setUserRestriction(UserManager.DISALLOW_SHARE_LOCATION, true, user.id);
2324 } finally {
2325 Binder.restoreCallingIdentity(identity);
2326 }
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002327 return user;
2328 }
2329
2330 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07002331 * Find the current guest user. If the Guest user is partial,
2332 * then do not include it in the results as it is about to die.
Adam Lesinskieddeb492014-09-08 17:50:03 -07002333 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002334 private UserInfo findCurrentGuestUser() {
2335 synchronized (mUsersLock) {
2336 final int size = mUsers.size();
2337 for (int i = 0; i < size; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002338 final UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002339 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
2340 return user;
2341 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002342 }
2343 }
2344 return null;
2345 }
2346
2347 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07002348 * Mark this guest user for deletion to allow us to create another guest
2349 * and switch to that user before actually removing this guest.
2350 * @param userHandle the userid of the current guest
2351 * @return whether the user could be marked for deletion
2352 */
Amith Yamasani12747872015-12-07 14:19:49 -08002353 @Override
Amith Yamasani1df14732014-08-29 21:37:27 -07002354 public boolean markGuestForDeletion(int userHandle) {
2355 checkManageUsersPermission("Only the system can remove users");
2356 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
2357 UserManager.DISALLOW_REMOVE_USER, false)) {
2358 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
2359 return false;
2360 }
2361
2362 long ident = Binder.clearCallingIdentity();
2363 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002364 final UserData userData;
Amith Yamasani1df14732014-08-29 21:37:27 -07002365 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002366 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002367 userData = mUsers.get(userHandle);
2368 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002369 return false;
2370 }
Amith Yamasani1df14732014-08-29 21:37:27 -07002371 }
Amith Yamasani12747872015-12-07 14:19:49 -08002372 if (!userData.info.isGuest()) {
Amith Yamasani1df14732014-08-29 21:37:27 -07002373 return false;
2374 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002375 // We set this to a guest user that is to be removed. This is a temporary state
2376 // where we are allowed to add new Guest users, even if this one is still not
2377 // removed. This user will still show up in getUserInfo() calls.
2378 // If we don't get around to removing this Guest user, it will be purged on next
2379 // startup.
Amith Yamasani12747872015-12-07 14:19:49 -08002380 userData.info.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07002381 // Mark it as disabled, so that it isn't returned any more when
2382 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002383 userData.info.flags |= UserInfo.FLAG_DISABLED;
2384 writeUserLP(userData);
Amith Yamasani1df14732014-08-29 21:37:27 -07002385 }
2386 } finally {
2387 Binder.restoreCallingIdentity(ident);
2388 }
2389 return true;
2390 }
2391
2392 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002393 * Removes a user and all data directories created for that user. This method should be called
2394 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07002395 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07002396 */
Amith Yamasani12747872015-12-07 14:19:49 -08002397 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -07002398 public boolean removeUser(int userHandle) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002399 checkManageOrCreateUsersPermission("Only the system can remove users");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04002400 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
2401 UserManager.DISALLOW_REMOVE_USER, false)) {
2402 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
2403 return false;
2404 }
2405
Kenny Guyee58b4f2014-05-23 15:19:53 +01002406 long ident = Binder.clearCallingIdentity();
2407 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002408 final UserData userData;
Fyodor Kupolov0df68cd2015-10-01 13:54:22 -07002409 int currentUser = ActivityManager.getCurrentUser();
2410 if (currentUser == userHandle) {
2411 Log.w(LOG_TAG, "Current user cannot be removed");
2412 return false;
2413 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002414 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002415 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002416 userData = mUsers.get(userHandle);
2417 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002418 return false;
2419 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002420
Fyodor Kupolov82402752015-10-28 14:54:51 -07002421 // We remember deleted user IDs to prevent them from being
2422 // reused during the current boot; they can still be reused
2423 // after a reboot.
2424 mRemovingUserIds.put(userHandle, true);
2425 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002426
Kenny Guyee58b4f2014-05-23 15:19:53 +01002427 try {
2428 mAppOpsService.removeUser(userHandle);
2429 } catch (RemoteException e) {
2430 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
2431 }
2432 // Set this to a partially created user, so that the user will be purged
2433 // on next startup, in case the runtime stops now before stopping and
2434 // removing the user completely.
Amith Yamasani12747872015-12-07 14:19:49 -08002435 userData.info.partial = true;
Kenny Guyee58b4f2014-05-23 15:19:53 +01002436 // Mark it as disabled, so that it isn't returned any more when
2437 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002438 userData.info.flags |= UserInfo.FLAG_DISABLED;
2439 writeUserLP(userData);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002440 }
2441
Amith Yamasani12747872015-12-07 14:19:49 -08002442 if (userData.info.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
2443 && userData.info.isManagedProfile()) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002444 // Send broadcast to notify system that the user removed was a
2445 // managed user.
Amith Yamasani12747872015-12-07 14:19:49 -08002446 sendProfileRemovedBroadcast(userData.info.profileGroupId, userData.info.id);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002447 }
2448
2449 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
2450 int res;
2451 try {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07002452 res = ActivityManagerNative.getDefault().stopUser(userHandle, /* force= */ true,
2453 new IStopUserCallback.Stub() {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002454 @Override
2455 public void userStopped(int userId) {
2456 finishRemoveUser(userId);
2457 }
2458 @Override
2459 public void userStopAborted(int userId) {
2460 }
2461 });
2462 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002463 return false;
2464 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002465 return res == ActivityManager.USER_OP_SUCCESS;
2466 } finally {
2467 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002468 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002469 }
2470
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002471 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07002472 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002473 // Let other services shutdown any activity and clean up their state before completely
2474 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002475 long ident = Binder.clearCallingIdentity();
2476 try {
2477 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
2478 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002479 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
2480 android.Manifest.permission.MANAGE_USERS,
2481
2482 new BroadcastReceiver() {
2483 @Override
2484 public void onReceive(Context context, Intent intent) {
2485 if (DBG) {
2486 Slog.i(LOG_TAG,
2487 "USER_REMOVED broadcast sent, cleaning up user data "
2488 + userHandle);
2489 }
2490 new Thread() {
Amith Yamasani12747872015-12-07 14:19:49 -08002491 @Override
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002492 public void run() {
Amith Yamasani515d4062015-09-28 11:30:06 -07002493 // Clean up any ActivityManager state
2494 LocalServices.getService(ActivityManagerInternal.class)
2495 .onUserRemoved(userHandle);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002496 removeUserState(userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002497 }
2498 }.start();
2499 }
2500 },
2501
2502 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002503 } finally {
2504 Binder.restoreCallingIdentity(ident);
2505 }
Amith Yamasani2a003292012-08-14 18:25:45 -07002506 }
2507
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002508 private void removeUserState(final int userHandle) {
Paul Crowley91293792016-03-25 15:23:07 -07002509 try {
2510 mContext.getSystemService(StorageManager.class).destroyUserKey(userHandle);
2511 } catch (IllegalStateException e) {
2512 // This may be simply because the user was partially created.
2513 Slog.i(LOG_TAG,
2514 "Destroying key for user " + userHandle + " failed, continuing anyway", e);
2515 }
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002516
Amith Yamasanid04aaa32016-06-13 12:09:36 -07002517 // Cleanup gatekeeper secure user id
2518 try {
2519 final IGateKeeperService gk = GateKeeper.getService();
2520 if (gk != null) {
2521 gk.clearSecureUserId(userHandle);
2522 }
2523 } catch (Exception ex) {
2524 Slog.w(LOG_TAG, "unable to clear GK secure user id");
2525 }
2526
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002527 // Cleanup package manager settings
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002528 mPm.cleanUpUser(this, userHandle);
Amith Yamasanid04aaa32016-06-13 12:09:36 -07002529
2530 // Clean up all data before removing metadata
2531 mPm.destroyUserData(userHandle,
2532 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2533
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002534 // Remove this user from the list
Fyodor Kupolov82402752015-10-28 14:54:51 -07002535 synchronized (mUsersLock) {
2536 mUsers.remove(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08002537 mIsUserManaged.delete(userHandle);
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00002538 }
2539 synchronized (mUserStates) {
2540 mUserStates.delete(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08002541 }
2542 synchronized (mRestrictionsLock) {
2543 mBaseUserRestrictions.remove(userHandle);
2544 mAppliedUserRestrictions.remove(userHandle);
2545 mCachedEffectiveUserRestrictions.remove(userHandle);
2546 mDevicePolicyLocalUserRestrictions.remove(userHandle);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002547 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002548 // Update the user list
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002549 synchronized (mPackagesLock) {
2550 writeUserListLP();
2551 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06002552 // Remove user file
2553 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
2554 userFile.delete();
Fyodor Kupolov82402752015-10-28 14:54:51 -07002555 updateUserIds();
Amith Yamasani61f57372012-08-31 12:12:28 -07002556 }
2557
Kenny Guyf8d3a232014-05-15 16:09:52 +01002558 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01002559 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01002560 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
2561 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002562 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
Jeff Sharkeyaf6ec292015-12-17 11:19:00 -07002563 managedProfileIntent.putExtra(Intent.EXTRA_USER_HANDLE, removedUserId);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002564 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01002565 }
2566
Amith Yamasani2a003292012-08-14 18:25:45 -07002567 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002568 public Bundle getApplicationRestrictions(String packageName) {
2569 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
2570 }
2571
2572 @Override
2573 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002574 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07002575 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00002576 checkSystemOrRoot("get application restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002577 }
2578 synchronized (mPackagesLock) {
2579 // Read the restrictions from XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07002580 return readApplicationRestrictionsLP(packageName, userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002581 }
2582 }
2583
2584 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002585 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002586 int userId) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00002587 checkSystemOrRoot("set application restrictions");
Fyodor Kupolov0d88d542016-04-19 11:37:22 -07002588 if (restrictions != null) {
2589 restrictions.setDefusable(true);
2590 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002591 synchronized (mPackagesLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01002592 if (restrictions == null || restrictions.isEmpty()) {
2593 cleanAppRestrictionsForPackage(packageName, userId);
2594 } else {
2595 // Write the restrictions to XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07002596 writeApplicationRestrictionsLP(packageName, restrictions, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01002597 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002598 }
Robin Lee66e5d962014-04-09 16:44:21 +01002599
Fyodor Kupolovd2846122016-02-11 18:06:34 -08002600 // Notify package of changes via an intent - only sent to explicitly registered receivers.
2601 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
2602 changeIntent.setPackage(packageName);
2603 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
2604 mContext.sendBroadcastAsUser(changeIntent, UserHandle.of(userId));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002605 }
2606
2607 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07002608 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002609 try {
2610 return mContext.getPackageManager().getApplicationInfo(packageName,
Fyodor Kupolovd2846122016-02-11 18:06:34 -08002611 PackageManager.MATCH_UNINSTALLED_PACKAGES).uid;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002612 } catch (NameNotFoundException nnfe) {
2613 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07002614 } finally {
2615 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002616 }
2617 }
2618
Fyodor Kupolov82402752015-10-28 14:54:51 -07002619 private Bundle readApplicationRestrictionsLP(String packageName, int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002620 AtomicFile restrictionsFile =
2621 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
2622 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002623 return readApplicationRestrictionsLP(restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002624 }
2625
2626 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002627 static Bundle readApplicationRestrictionsLP(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002628 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002629 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002630 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07002631 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002632 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002633
2634 FileInputStream fis = null;
2635 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002636 fis = restrictionsFile.openRead();
2637 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002638 parser.setInput(fis, StandardCharsets.UTF_8.name());
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002639 XmlUtils.nextElement(parser);
2640 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002641 Slog.e(LOG_TAG, "Unable to read restrictions file "
2642 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002643 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002644 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002645 while (parser.next() != XmlPullParser.END_DOCUMENT) {
2646 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002647 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002648 } catch (IOException|XmlPullParserException e) {
2649 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002650 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002651 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002652 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002653 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002654 }
2655
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002656 private static void readEntry(Bundle restrictions, ArrayList<String> values,
2657 XmlPullParser parser) throws XmlPullParserException, IOException {
2658 int type = parser.getEventType();
2659 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
2660 String key = parser.getAttributeValue(null, ATTR_KEY);
2661 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
2662 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
2663 if (multiple != null) {
2664 values.clear();
2665 int count = Integer.parseInt(multiple);
2666 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
2667 if (type == XmlPullParser.START_TAG
2668 && parser.getName().equals(TAG_VALUE)) {
2669 values.add(parser.nextText().trim());
2670 count--;
2671 }
2672 }
2673 String [] valueStrings = new String[values.size()];
2674 values.toArray(valueStrings);
2675 restrictions.putStringArray(key, valueStrings);
2676 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
2677 restrictions.putBundle(key, readBundleEntry(parser, values));
2678 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
2679 final int outerDepth = parser.getDepth();
2680 ArrayList<Bundle> bundleList = new ArrayList<>();
2681 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2682 Bundle childBundle = readBundleEntry(parser, values);
2683 bundleList.add(childBundle);
2684 }
2685 restrictions.putParcelableArray(key,
2686 bundleList.toArray(new Bundle[bundleList.size()]));
2687 } else {
2688 String value = parser.nextText().trim();
2689 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
2690 restrictions.putBoolean(key, Boolean.parseBoolean(value));
2691 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
2692 restrictions.putInt(key, Integer.parseInt(value));
2693 } else {
2694 restrictions.putString(key, value);
2695 }
2696 }
2697 }
2698 }
2699
2700 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
2701 throws IOException, XmlPullParserException {
2702 Bundle childBundle = new Bundle();
2703 final int outerDepth = parser.getDepth();
2704 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2705 readEntry(childBundle, values, parser);
2706 }
2707 return childBundle;
2708 }
2709
Fyodor Kupolov82402752015-10-28 14:54:51 -07002710 private void writeApplicationRestrictionsLP(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002711 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002712 AtomicFile restrictionsFile = new AtomicFile(
2713 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07002714 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002715 writeApplicationRestrictionsLP(restrictions, restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002716 }
2717
2718 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002719 static void writeApplicationRestrictionsLP(Bundle restrictions, AtomicFile restrictionsFile) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002720 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002721 try {
2722 fos = restrictionsFile.startWrite();
2723 final BufferedOutputStream bos = new BufferedOutputStream(fos);
2724
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002725 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002726 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002727 serializer.startDocument(null, true);
2728 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2729
2730 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002731 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002732 serializer.endTag(null, TAG_RESTRICTIONS);
2733
2734 serializer.endDocument();
2735 restrictionsFile.finishWrite(fos);
2736 } catch (Exception e) {
2737 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002738 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
2739 }
2740 }
2741
2742 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
2743 throws IOException {
2744 for (String key : restrictions.keySet()) {
2745 Object value = restrictions.get(key);
2746 serializer.startTag(null, TAG_ENTRY);
2747 serializer.attribute(null, ATTR_KEY, key);
2748
2749 if (value instanceof Boolean) {
2750 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
2751 serializer.text(value.toString());
2752 } else if (value instanceof Integer) {
2753 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
2754 serializer.text(value.toString());
2755 } else if (value == null || value instanceof String) {
2756 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
2757 serializer.text(value != null ? (String) value : "");
2758 } else if (value instanceof Bundle) {
2759 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2760 writeBundle((Bundle) value, serializer);
2761 } else if (value instanceof Parcelable[]) {
2762 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
2763 Parcelable[] array = (Parcelable[]) value;
2764 for (Parcelable parcelable : array) {
2765 if (!(parcelable instanceof Bundle)) {
2766 throw new IllegalArgumentException("bundle-array can only hold Bundles");
2767 }
2768 serializer.startTag(null, TAG_ENTRY);
2769 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2770 writeBundle((Bundle) parcelable, serializer);
2771 serializer.endTag(null, TAG_ENTRY);
2772 }
2773 } else {
2774 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
2775 String[] values = (String[]) value;
2776 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
2777 for (String choice : values) {
2778 serializer.startTag(null, TAG_VALUE);
2779 serializer.text(choice != null ? choice : "");
2780 serializer.endTag(null, TAG_VALUE);
2781 }
2782 }
2783 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002784 }
2785 }
2786
2787 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07002788 public int getUserSerialNumber(int userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002789 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002790 if (!exists(userHandle)) return -1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002791 return getUserInfoLU(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07002792 }
2793 }
2794
2795 @Override
2796 public int getUserHandle(int userSerialNumber) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002797 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002798 for (int userId : mUserIds) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002799 UserInfo info = getUserInfoLU(userId);
Kenny Guy945f8832015-02-10 15:17:26 +00002800 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07002801 }
2802 // Not found
2803 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07002804 }
2805 }
2806
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002807 @Override
2808 public long getUserCreationTime(int userHandle) {
2809 int callingUserId = UserHandle.getCallingUserId();
2810 UserInfo userInfo = null;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002811 synchronized (mUsersLock) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002812 if (callingUserId == userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002813 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002814 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002815 UserInfo parent = getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002816 if (parent != null && parent.id == callingUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002817 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002818 }
2819 }
2820 }
2821 if (userInfo == null) {
2822 throw new SecurityException("userHandle can only be the calling user or a managed "
2823 + "profile associated with this user");
2824 }
2825 return userInfo.creationTime;
2826 }
2827
Amith Yamasani0b285492011-04-14 17:35:23 -07002828 /**
2829 * Caches the list of user ids in an array, adjusting the array size when necessary.
2830 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002831 private void updateUserIds() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002832 int num = 0;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002833 synchronized (mUsersLock) {
2834 final int userSize = mUsers.size();
2835 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002836 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002837 num++;
2838 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002839 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002840 final int[] newUsers = new int[num];
2841 int n = 0;
2842 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002843 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002844 newUsers[n++] = mUsers.keyAt(i);
2845 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002846 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002847 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07002848 }
2849 }
2850
2851 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002852 * Called right before a user is started. This gives us a chance to prepare
2853 * app storage and apply any user restrictions.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002854 */
2855 public void onBeforeStartUser(int userId) {
Jeff Sharkey47f71082016-02-01 17:03:54 -07002856 final int userSerial = getUserSerialNumber(userId);
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002857 mPm.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_DE);
Jeff Sharkey47f71082016-02-01 17:03:54 -07002858 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_DE);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002859
2860 if (userId != UserHandle.USER_SYSTEM) {
2861 synchronized (mRestrictionsLock) {
2862 applyUserRestrictionsLR(userId);
2863 }
Fyodor Kupolovb45d9832016-05-16 13:25:34 -07002864 UserInfo userInfo = getUserInfoNoChecks(userId);
2865 if (userInfo != null && !userInfo.isInitialized()) {
2866 mPm.onBeforeUserStartUninitialized(userId);
2867 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002868 }
Amith Yamasanieb437d42016-04-29 09:31:25 -07002869
2870 maybeInitializeDemoMode(userId);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002871 }
2872
2873 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002874 * Called right before a user is unlocked. This gives us a chance to prepare
2875 * app storage.
2876 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002877 public void onBeforeUnlockUser(@UserIdInt int userId) {
Jeff Sharkey47f71082016-02-01 17:03:54 -07002878 final int userSerial = getUserSerialNumber(userId);
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002879 mPm.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_CE);
Jeff Sharkey47f71082016-02-01 17:03:54 -07002880 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_CE);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002881 }
2882
2883 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002884 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasanieb437d42016-04-29 09:31:25 -07002885 * This is called with ActivityManagerService lock held.
Amith Yamasani920ace02012-09-20 22:15:37 -07002886 * @param userId the user that was just foregrounded
2887 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002888 public void onUserLoggedIn(@UserIdInt int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -08002889 UserData userData = getUserDataNoChecks(userId);
2890 if (userData == null || userData.info.partial) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002891 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
2892 return;
2893 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002894
2895 final long now = System.currentTimeMillis();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002896 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani12747872015-12-07 14:19:49 -08002897 userData.info.lastLoggedInTime = now;
Amith Yamasani920ace02012-09-20 22:15:37 -07002898 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002899 userData.info.lastLoggedInFingerprint = Build.FINGERPRINT;
2900 scheduleWriteUser(userData);
Amith Yamasani920ace02012-09-20 22:15:37 -07002901 }
2902
Amith Yamasanieb437d42016-04-29 09:31:25 -07002903 private void maybeInitializeDemoMode(int userId) {
2904 if (UserManager.isDeviceInDemoMode(mContext)) {
2905 String demoLauncher =
2906 mContext.getResources().getString(
2907 com.android.internal.R.string.config_demoModeLauncherComponent);
2908 if (!TextUtils.isEmpty(demoLauncher)) {
2909 ComponentName componentToEnable = ComponentName.unflattenFromString(demoLauncher);
2910 try {
2911 AppGlobals.getPackageManager().setComponentEnabledSetting(componentToEnable,
2912 PackageManager.COMPONENT_ENABLED_STATE_ENABLED, /* flags= */ 0,
2913 /* userId= */ userId);
2914 } catch (RemoteException re) {
2915 // Internal, shouldn't happen
2916 }
2917 }
2918 }
2919 }
2920
Amith Yamasani920ace02012-09-20 22:15:37 -07002921 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002922 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani742a6712011-05-04 14:49:28 -07002923 * TODO: May not be a good idea to recycle ids, in case it results in confusion
2924 * for data and battery stats collection, or unexpected cross-talk.
Amith Yamasani0b285492011-04-14 17:35:23 -07002925 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002926 private int getNextAvailableId() {
2927 synchronized (mUsersLock) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002928 int i = MIN_USER_ID;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002929 while (i < MAX_USER_ID) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002930 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002931 return i;
Amith Yamasani195263742012-08-21 15:40:12 -07002932 }
2933 i++;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002934 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002935 }
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002936 throw new IllegalStateException("No user id available!");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002937 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002938
Amith Yamasanifc95e702013-09-26 13:20:17 -07002939 private String packageToRestrictionsFileName(String packageName) {
2940 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
2941 }
2942
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002943 /**
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002944 * Enforce that serial number stored in user directory inode matches the
2945 * given expected value. Gracefully sets the serial number if currently
2946 * undefined.
2947 *
2948 * @throws IOException when problem extracting serial number, or serial
2949 * number is mismatched.
2950 */
2951 public static void enforceSerialNumber(File file, int serialNumber) throws IOException {
2952 final int foundSerial = getSerialNumber(file);
2953 Slog.v(LOG_TAG, "Found " + file + " with serial number " + foundSerial);
2954
2955 if (foundSerial == -1) {
2956 Slog.d(LOG_TAG, "Serial number missing on " + file + "; assuming current is valid");
2957 try {
2958 setSerialNumber(file, serialNumber);
2959 } catch (IOException e) {
2960 Slog.w(LOG_TAG, "Failed to set serial number on " + file, e);
2961 }
2962
2963 } else if (foundSerial != serialNumber) {
2964 throw new IOException("Found serial number " + foundSerial
2965 + " doesn't match expected " + serialNumber);
2966 }
2967 }
2968
2969 /**
2970 * Set serial number stored in user directory inode.
2971 *
2972 * @throws IOException if serial number was already set
2973 */
2974 private static void setSerialNumber(File file, int serialNumber)
2975 throws IOException {
2976 try {
2977 final byte[] buf = Integer.toString(serialNumber).getBytes(StandardCharsets.UTF_8);
2978 Os.setxattr(file.getAbsolutePath(), XATTR_SERIAL, buf, OsConstants.XATTR_CREATE);
2979 } catch (ErrnoException e) {
2980 throw e.rethrowAsIOException();
2981 }
2982 }
2983
2984 /**
2985 * Return serial number stored in user directory inode.
2986 *
2987 * @return parsed serial number, or -1 if not set
2988 */
2989 private static int getSerialNumber(File file) throws IOException {
2990 try {
2991 final byte[] buf = new byte[256];
2992 final int len = Os.getxattr(file.getAbsolutePath(), XATTR_SERIAL, buf);
2993 final String serial = new String(buf, 0, len);
2994 try {
2995 return Integer.parseInt(serial);
2996 } catch (NumberFormatException e) {
2997 throw new IOException("Bad serial number: " + serial);
2998 }
2999 } catch (ErrnoException e) {
3000 if (e.errno == OsConstants.ENODATA) {
3001 return -1;
3002 } else {
3003 throw e.rethrowAsIOException();
3004 }
3005 }
3006 }
3007
Amith Yamasani920ace02012-09-20 22:15:37 -07003008 @Override
Amith Yamasani12747872015-12-07 14:19:49 -08003009 public void setSeedAccountData(int userId, String accountName, String accountType,
3010 PersistableBundle accountOptions, boolean persist) {
3011 checkManageUsersPermission("Require MANAGE_USERS permission to set user seed data");
3012 synchronized (mPackagesLock) {
3013 final UserData userData;
3014 synchronized (mUsersLock) {
3015 userData = getUserDataLU(userId);
3016 if (userData == null) {
3017 Slog.e(LOG_TAG, "No such user for settings seed data u=" + userId);
3018 return;
3019 }
3020 userData.seedAccountName = accountName;
3021 userData.seedAccountType = accountType;
3022 userData.seedAccountOptions = accountOptions;
3023 userData.persistSeedData = persist;
3024 }
3025 if (persist) {
3026 writeUserLP(userData);
3027 }
3028 }
3029 }
3030
3031 @Override
3032 public String getSeedAccountName() throws RemoteException {
3033 checkManageUsersPermission("Cannot get seed account information");
3034 synchronized (mUsersLock) {
3035 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3036 return userData.seedAccountName;
3037 }
3038 }
3039
3040 @Override
3041 public String getSeedAccountType() throws RemoteException {
3042 checkManageUsersPermission("Cannot get seed account information");
3043 synchronized (mUsersLock) {
3044 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3045 return userData.seedAccountType;
3046 }
3047 }
3048
3049 @Override
3050 public PersistableBundle getSeedAccountOptions() throws RemoteException {
3051 checkManageUsersPermission("Cannot get seed account information");
3052 synchronized (mUsersLock) {
3053 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3054 return userData.seedAccountOptions;
3055 }
3056 }
3057
3058 @Override
3059 public void clearSeedAccountData() throws RemoteException {
3060 checkManageUsersPermission("Cannot clear seed account information");
3061 synchronized (mPackagesLock) {
3062 UserData userData;
3063 synchronized (mUsersLock) {
3064 userData = getUserDataLU(UserHandle.getCallingUserId());
3065 if (userData == null) return;
3066 userData.clearSeedAccountData();
3067 }
3068 writeUserLP(userData);
3069 }
3070 }
3071
3072 @Override
3073 public boolean someUserHasSeedAccount(String accountName, String accountType)
3074 throws RemoteException {
3075 checkManageUsersPermission("Cannot check seed account information");
3076 synchronized (mUsersLock) {
3077 final int userSize = mUsers.size();
3078 for (int i = 0; i < userSize; i++) {
3079 final UserData data = mUsers.valueAt(i);
3080 if (data.info.isInitialized()) continue;
3081 if (data.seedAccountName == null || !data.seedAccountName.equals(accountName)) {
3082 continue;
3083 }
3084 if (data.seedAccountType == null || !data.seedAccountType.equals(accountType)) {
3085 continue;
3086 }
3087 return true;
3088 }
3089 }
3090 return false;
3091 }
3092
3093 @Override
Todd Kennedy60459ab2015-10-30 11:32:16 -07003094 public void onShellCommand(FileDescriptor in, FileDescriptor out,
3095 FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
3096 (new Shell()).exec(this, in, out, err, args, resultReceiver);
3097 }
3098
3099 int onShellCommand(Shell shell, String cmd) {
3100 if (cmd == null) {
3101 return shell.handleDefaultCommands(cmd);
3102 }
3103
3104 final PrintWriter pw = shell.getOutPrintWriter();
3105 try {
3106 switch(cmd) {
3107 case "list":
3108 return runList(pw);
3109 }
3110 } catch (RemoteException e) {
3111 pw.println("Remote exception: " + e);
3112 }
3113 return -1;
3114 }
3115
3116 private int runList(PrintWriter pw) throws RemoteException {
3117 final IActivityManager am = ActivityManagerNative.getDefault();
3118 final List<UserInfo> users = getUsers(false);
3119 if (users == null) {
3120 pw.println("Error: couldn't get users");
3121 return 1;
3122 } else {
3123 pw.println("Users:");
3124 for (int i = 0; i < users.size(); i++) {
Jeff Sharkeye17ac152015-11-06 22:40:29 -08003125 String running = am.isUserRunning(users.get(i).id, 0) ? " running" : "";
Todd Kennedy60459ab2015-10-30 11:32:16 -07003126 pw.println("\t" + users.get(i).toString() + running);
3127 }
3128 return 0;
3129 }
3130 }
3131
3132 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -07003133 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
3134 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
3135 != PackageManager.PERMISSION_GRANTED) {
3136 pw.println("Permission Denial: can't dump UserManager from from pid="
3137 + Binder.getCallingPid()
3138 + ", uid=" + Binder.getCallingUid()
3139 + " without permission "
3140 + android.Manifest.permission.DUMP);
3141 return;
3142 }
3143
3144 long now = System.currentTimeMillis();
3145 StringBuilder sb = new StringBuilder();
3146 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003147 synchronized (mUsersLock) {
3148 pw.println("Users:");
3149 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003150 UserData userData = mUsers.valueAt(i);
3151 if (userData == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003152 continue;
3153 }
Amith Yamasani12747872015-12-07 14:19:49 -08003154 UserInfo userInfo = userData.info;
3155 final int userId = userInfo.id;
3156 pw.print(" "); pw.print(userInfo);
3157 pw.print(" serialNo="); pw.print(userInfo.serialNumber);
Makoto Onukie7927da2015-11-25 10:05:17 -08003158 if (mRemovingUserIds.get(userId)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003159 pw.print(" <removing> ");
3160 }
Amith Yamasani12747872015-12-07 14:19:49 -08003161 if (userInfo.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003162 pw.print(" <partial>");
3163 }
3164 pw.println();
3165 pw.print(" Created: ");
Amith Yamasani12747872015-12-07 14:19:49 -08003166 if (userInfo.creationTime == 0) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003167 pw.println("<unknown>");
3168 } else {
3169 sb.setLength(0);
Amith Yamasani12747872015-12-07 14:19:49 -08003170 TimeUtils.formatDuration(now - userInfo.creationTime, sb);
Fyodor Kupolov82402752015-10-28 14:54:51 -07003171 sb.append(" ago");
3172 pw.println(sb);
3173 }
3174 pw.print(" Last logged in: ");
Amith Yamasani12747872015-12-07 14:19:49 -08003175 if (userInfo.lastLoggedInTime == 0) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003176 pw.println("<unknown>");
3177 } else {
3178 sb.setLength(0);
Amith Yamasani12747872015-12-07 14:19:49 -08003179 TimeUtils.formatDuration(now - userInfo.lastLoggedInTime, sb);
Fyodor Kupolov82402752015-10-28 14:54:51 -07003180 sb.append(" ago");
3181 pw.println(sb);
3182 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003183 pw.print(" Last logged in fingerprint: ");
3184 pw.println(userInfo.lastLoggedInFingerprint);
Makoto Onukie7927da2015-11-25 10:05:17 -08003185 pw.print(" Has profile owner: ");
3186 pw.println(mIsUserManaged.get(userId));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003187 pw.println(" Restrictions:");
3188 synchronized (mRestrictionsLock) {
3189 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003190 pw, " ", mBaseUserRestrictions.get(userInfo.id));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003191 pw.println(" Device policy local restrictions:");
3192 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003193 pw, " ", mDevicePolicyLocalUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003194 pw.println(" Effective restrictions:");
3195 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003196 pw, " ", mCachedEffectiveUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003197 }
Amith Yamasani12747872015-12-07 14:19:49 -08003198
3199 if (userData.account != null) {
3200 pw.print(" Account name: " + userData.account);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08003201 pw.println();
3202 }
Amith Yamasani12747872015-12-07 14:19:49 -08003203
3204 if (userData.seedAccountName != null) {
3205 pw.print(" Seed account name: " + userData.seedAccountName);
3206 pw.println();
3207 if (userData.seedAccountType != null) {
3208 pw.print(" account type: " + userData.seedAccountType);
3209 pw.println();
3210 }
3211 if (userData.seedAccountOptions != null) {
3212 pw.print(" account options exist");
3213 pw.println();
3214 }
3215 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003216 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003217 }
Amith Yamasani12747872015-12-07 14:19:49 -08003218 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003219 pw.println(" Device policy global restrictions:");
3220 synchronized (mRestrictionsLock) {
3221 UserRestrictionsUtils
3222 .dumpRestrictions(pw, " ", mDevicePolicyGlobalUserRestrictions);
3223 }
Makoto Onukia4f11972015-10-01 13:19:58 -07003224 pw.println();
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01003225 pw.println(" Global restrictions owner id:" + mGlobalRestrictionOwnerUserId);
3226 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003227 pw.println(" Guest restrictions:");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003228 synchronized (mGuestRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003229 UserRestrictionsUtils.dumpRestrictions(pw, " ", mGuestRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003230 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003231 synchronized (mUsersLock) {
3232 pw.println();
3233 pw.println(" Device managed: " + mIsDeviceManaged);
3234 }
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003235 synchronized (mUserStates) {
3236 pw.println(" Started users state: " + mUserStates);
3237 }
Amith Yamasani12747872015-12-07 14:19:49 -08003238 // Dump some capabilities
3239 pw.println();
3240 pw.println(" Max users: " + UserManager.getMaxSupportedUsers());
3241 pw.println(" Supports switchable users: " + UserManager.supportsMultipleUsers());
Lenka Trochtova02fee152015-12-22 14:26:18 +01003242 pw.println(" All guests ephemeral: " + Resources.getSystem().getBoolean(
3243 com.android.internal.R.bool.config_guestUserEphemeral));
Amith Yamasani920ace02012-09-20 22:15:37 -07003244 }
3245 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08003246
3247 final class MainHandler extends Handler {
3248
3249 @Override
3250 public void handleMessage(Message msg) {
3251 switch (msg.what) {
3252 case WRITE_USER_MSG:
3253 removeMessages(WRITE_USER_MSG, msg.obj);
3254 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08003255 int userId = ((UserData) msg.obj).info.id;
3256 UserData userData = getUserDataNoChecks(userId);
3257 if (userData != null) {
3258 writeUserLP(userData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08003259 }
3260 }
3261 }
3262 }
3263 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07003264
3265 /**
3266 * @param userId
3267 * @return whether the user has been initialized yet
3268 */
3269 boolean isInitialized(int userId) {
3270 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
3271 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003272
3273 private class LocalService extends UserManagerInternal {
Makoto Onuki068c54a2015-10-13 14:34:03 -07003274 @Override
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003275 public void setDevicePolicyUserRestrictions(int userId, @NonNull Bundle localRestrictions,
3276 @Nullable Bundle globalRestrictions) {
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08003277 UserManagerService.this.setDevicePolicyUserRestrictionsInner(userId, localRestrictions,
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003278 globalRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003279 }
3280
3281 @Override
3282 public Bundle getBaseUserRestrictions(int userId) {
3283 synchronized (mRestrictionsLock) {
3284 return mBaseUserRestrictions.get(userId);
3285 }
3286 }
3287
3288 @Override
3289 public void setBaseUserRestrictionsByDpmsForMigration(
3290 int userId, Bundle baseRestrictions) {
3291 synchronized (mRestrictionsLock) {
3292 mBaseUserRestrictions.put(userId, new Bundle(baseRestrictions));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003293 invalidateEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003294 }
3295
Amith Yamasani12747872015-12-07 14:19:49 -08003296 final UserData userData = getUserDataNoChecks(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003297 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08003298 if (userData != null) {
3299 writeUserLP(userData);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003300 } else {
3301 Slog.w(LOG_TAG, "UserInfo not found for " + userId);
3302 }
3303 }
3304 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08003305
3306 @Override
3307 public boolean getUserRestriction(int userId, String key) {
3308 return getUserRestrictions(userId).getBoolean(key);
3309 }
3310
3311 @Override
3312 public void addUserRestrictionsListener(UserRestrictionsListener listener) {
3313 synchronized (mUserRestrictionsListeners) {
3314 mUserRestrictionsListeners.add(listener);
3315 }
3316 }
3317
3318 @Override
3319 public void removeUserRestrictionsListener(UserRestrictionsListener listener) {
3320 synchronized (mUserRestrictionsListeners) {
3321 mUserRestrictionsListeners.remove(listener);
3322 }
3323 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003324
3325 @Override
3326 public void setDeviceManaged(boolean isManaged) {
3327 synchronized (mUsersLock) {
3328 mIsDeviceManaged = isManaged;
3329 }
3330 }
3331
3332 @Override
3333 public void setUserManaged(int userId, boolean isManaged) {
3334 synchronized (mUsersLock) {
3335 mIsUserManaged.put(userId, isManaged);
3336 }
3337 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01003338
3339 @Override
3340 public void setUserIcon(int userId, Bitmap bitmap) {
3341 long ident = Binder.clearCallingIdentity();
3342 try {
3343 synchronized (mPackagesLock) {
3344 UserData userData = getUserDataNoChecks(userId);
3345 if (userData == null || userData.info.partial) {
3346 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
3347 return;
3348 }
3349 writeBitmapLP(userData.info, bitmap);
3350 writeUserLP(userData);
3351 }
3352 sendUserInfoChangedBroadcast(userId);
3353 } finally {
3354 Binder.restoreCallingIdentity(ident);
3355 }
3356 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01003357
3358 @Override
3359 public void setForceEphemeralUsers(boolean forceEphemeralUsers) {
3360 synchronized (mUsersLock) {
3361 mForceEphemeralUsers = forceEphemeralUsers;
3362 }
3363 }
3364
3365 @Override
3366 public void removeAllUsers() {
3367 if (UserHandle.USER_SYSTEM == ActivityManager.getCurrentUser()) {
3368 // Remove the non-system users straight away.
3369 removeNonSystemUsers();
3370 } else {
3371 // Switch to the system user first and then remove the other users.
3372 BroadcastReceiver userSwitchedReceiver = new BroadcastReceiver() {
3373 @Override
3374 public void onReceive(Context context, Intent intent) {
3375 int userId =
3376 intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3377 if (userId != UserHandle.USER_SYSTEM) {
3378 return;
3379 }
3380 mContext.unregisterReceiver(this);
3381 removeNonSystemUsers();
3382 }
3383 };
3384 IntentFilter userSwitchedFilter = new IntentFilter();
3385 userSwitchedFilter.addAction(Intent.ACTION_USER_SWITCHED);
3386 mContext.registerReceiver(
3387 userSwitchedReceiver, userSwitchedFilter, null, mHandler);
3388
3389 // Switch to the system user.
3390 ActivityManager am =
3391 (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
3392 am.switchUser(UserHandle.USER_SYSTEM);
3393 }
3394 }
phweisse9c44062016-02-10 12:57:38 +01003395
3396 @Override
Lenka Trochtova1ddda472016-02-12 10:42:12 +01003397 public void onEphemeralUserStop(int userId) {
3398 synchronized (mUsersLock) {
3399 UserInfo userInfo = getUserInfoLU(userId);
3400 if (userInfo != null && userInfo.isEphemeral()) {
3401 // Do not allow switching back to the ephemeral user again as the user is going
3402 // to be deleted.
3403 userInfo.flags |= UserInfo.FLAG_DISABLED;
3404 if (userInfo.isGuest()) {
3405 // Indicate that the guest will be deleted after it stops.
3406 userInfo.guestToRemove = true;
3407 }
3408 }
3409 }
3410 }
3411
3412 @Override
phweisse9c44062016-02-10 12:57:38 +01003413 public UserInfo createUserEvenWhenDisallowed(String name, int flags) {
3414 UserInfo user = createUserInternalUnchecked(name, flags, UserHandle.USER_NULL);
3415 // Keep this in sync with UserManager.createUser
3416 if (user != null && !user.isAdmin()) {
3417 setUserRestriction(UserManager.DISALLOW_SMS, true, user.id);
3418 setUserRestriction(UserManager.DISALLOW_OUTGOING_CALLS, true, user.id);
3419 }
3420 return user;
3421 }
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003422
3423 @Override
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003424 public boolean isUserRunning(int userId) {
3425 synchronized (mUserStates) {
3426 return mUserStates.get(userId, -1) >= 0;
3427 }
3428 }
3429
3430 @Override
3431 public void setUserState(int userId, int userState) {
3432 synchronized (mUserStates) {
3433 mUserStates.put(userId, userState);
3434 }
3435 }
3436
3437 @Override
3438 public void removeUserState(int userId) {
3439 synchronized (mUserStates) {
3440 mUserStates.delete(userId);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003441 }
3442 }
3443
3444 @Override
3445 public boolean isUserUnlockingOrUnlocked(int userId) {
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003446 synchronized (mUserStates) {
3447 int state = mUserStates.get(userId, -1);
3448 return (state == UserState.STATE_RUNNING_UNLOCKING)
3449 || (state == UserState.STATE_RUNNING_UNLOCKED);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003450 }
3451 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01003452 }
3453
3454 /* Remove all the users except of the system one. */
3455 private void removeNonSystemUsers() {
3456 ArrayList<UserInfo> usersToRemove = new ArrayList<>();
3457 synchronized (mUsersLock) {
3458 final int userSize = mUsers.size();
3459 for (int i = 0; i < userSize; i++) {
3460 UserInfo ui = mUsers.valueAt(i).info;
3461 if (ui.id != UserHandle.USER_SYSTEM) {
3462 usersToRemove.add(ui);
3463 }
3464 }
3465 }
3466 for (UserInfo ui: usersToRemove) {
3467 removeUser(ui.id);
3468 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003469 }
Todd Kennedy60459ab2015-10-30 11:32:16 -07003470
3471 private class Shell extends ShellCommand {
3472 @Override
3473 public int onCommand(String cmd) {
3474 return onShellCommand(this, cmd);
3475 }
3476
3477 @Override
3478 public void onHelp() {
3479 final PrintWriter pw = getOutPrintWriter();
3480 pw.println("User manager (user) commands:");
3481 pw.println(" help");
3482 pw.println(" Print this help text.");
3483 pw.println("");
3484 pw.println(" list");
3485 pw.println(" Prints all users on the system.");
3486 }
3487 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003488
3489 private static void debug(String message) {
3490 Log.d(LOG_TAG, message +
3491 (DBG_WITH_STACKTRACE ? " called at\n" + Debug.getCallers(10, " ") : ""));
3492 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003493}