blob: 681bf15832b944f055eba26a35f8b5ccb46a08a2 [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);
474 }
475 }
476 }
477 final int partialsSize = partials.size();
478 for (int i = 0; i < partialsSize; i++) {
479 UserInfo ui = partials.get(i);
480 Slog.w(LOG_TAG, "Removing partially created user " + ui.id
481 + " (name=" + ui.name + ")");
482 removeUserState(ui.id);
483 }
484 }
485
Amith Yamasani258848d2012-08-10 17:06:33 -0700486 @Override
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800487 public String getUserAccount(int userId) {
488 checkManageUserAndAcrossUsersFullPermission("get user account");
489 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800490 return mUsers.get(userId).account;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800491 }
492 }
493
494 @Override
495 public void setUserAccount(int userId, String accountName) {
496 checkManageUserAndAcrossUsersFullPermission("set user account");
Amith Yamasani12747872015-12-07 14:19:49 -0800497 UserData userToUpdate = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800498 synchronized (mPackagesLock) {
499 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800500 final UserData userData = mUsers.get(userId);
501 if (userData == null) {
502 Slog.e(LOG_TAG, "User not found for setting user account: u" + userId);
503 return;
504 }
505 String currentAccount = userData.account;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800506 if (!Objects.equal(currentAccount, accountName)) {
Amith Yamasani12747872015-12-07 14:19:49 -0800507 userData.account = accountName;
508 userToUpdate = userData;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800509 }
510 }
511
512 if (userToUpdate != null) {
513 writeUserLP(userToUpdate);
514 }
515 }
516 }
517
518 @Override
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700519 public UserInfo getPrimaryUser() {
520 checkManageUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700521 synchronized (mUsersLock) {
Amith Yamasani515d4062015-09-28 11:30:06 -0700522 final int userSize = mUsers.size();
523 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800524 UserInfo ui = mUsers.valueAt(i).info;
Xiaohui Chend3e9e182015-11-18 13:37:32 -0800525 if (ui.isPrimary() && !mRemovingUserIds.get(ui.id)) {
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700526 return ui;
527 }
528 }
529 }
530 return null;
531 }
532
533 @Override
Xiaohui Chen594f2082015-08-18 11:04:20 -0700534 public @NonNull List<UserInfo> getUsers(boolean excludeDying) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -0700535 checkManageOrCreateUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700536 synchronized (mUsersLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700537 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasani515d4062015-09-28 11:30:06 -0700538 final int userSize = mUsers.size();
539 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800540 UserInfo ui = mUsers.valueAt(i).info;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700541 if (ui.partial) {
542 continue;
543 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800544 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Amith Yamasani6f48d6e2016-03-23 14:28:25 -0700545 users.add(userWithName(ui));
Amith Yamasani920ace02012-09-20 22:15:37 -0700546 }
Amith Yamasani13593602012-03-22 16:16:17 -0700547 }
548 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700549 }
Amith Yamasani13593602012-03-22 16:16:17 -0700550 }
551
Amith Yamasani258848d2012-08-10 17:06:33 -0700552 @Override
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100553 public List<UserInfo> getProfiles(int userId, boolean enabledOnly) {
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700554 boolean returnFullInfo = true;
Amith Yamasani4f582632014-02-19 14:31:52 -0800555 if (userId != UserHandle.getCallingUserId()) {
556 checkManageUsersPermission("getting profiles related to user " + userId);
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700557 } else {
558 returnFullInfo = hasManageUsersPermission();
Amith Yamasani4f582632014-02-19 14:31:52 -0800559 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700560 final long ident = Binder.clearCallingIdentity();
561 try {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700562 synchronized (mUsersLock) {
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700563 return getProfilesLU(userId, enabledOnly, returnFullInfo);
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100564 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700565 } finally {
566 Binder.restoreCallingIdentity(ident);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000567 }
568 }
569
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700570 @Override
571 public int[] getProfileIds(int userId, boolean enabledOnly) {
572 if (userId != UserHandle.getCallingUserId()) {
573 checkManageUsersPermission("getting profiles related to user " + userId);
574 }
575 final long ident = Binder.clearCallingIdentity();
576 try {
577 synchronized (mUsersLock) {
578 return getProfileIdsLU(userId, enabledOnly).toArray();
579 }
580 } finally {
581 Binder.restoreCallingIdentity(ident);
582 }
583 }
584
Amith Yamasanibe465322014-04-24 13:45:17 -0700585 /** Assume permissions already checked and caller's identity cleared */
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700586 private List<UserInfo> getProfilesLU(int userId, boolean enabledOnly, boolean fullInfo) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700587 IntArray profileIds = getProfileIdsLU(userId, enabledOnly);
588 ArrayList<UserInfo> users = new ArrayList<>(profileIds.size());
589 for (int i = 0; i < profileIds.size(); i++) {
590 int profileId = profileIds.get(i);
591 UserInfo userInfo = mUsers.get(profileId).info;
592 // If full info is not required - clear PII data to prevent 3P apps from reading it
593 if (!fullInfo) {
594 userInfo = new UserInfo(userInfo);
595 userInfo.name = null;
596 userInfo.iconPath = null;
597 } else {
598 userInfo = userWithName(userInfo);
599 }
600 users.add(userInfo);
601 }
602 return users;
603 }
604
605 /**
606 * Assume permissions already checked and caller's identity cleared
607 */
608 private IntArray getProfileIdsLU(int userId, boolean enabledOnly) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700609 UserInfo user = getUserInfoLU(userId);
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700610 IntArray result = new IntArray(mUsers.size());
Amith Yamasanidda003f2014-08-28 18:06:51 -0700611 if (user == null) {
612 // Probably a dying user
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700613 return result;
Amith Yamasanidda003f2014-08-28 18:06:51 -0700614 }
Amith Yamasani515d4062015-09-28 11:30:06 -0700615 final int userSize = mUsers.size();
616 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800617 UserInfo profile = mUsers.valueAt(i).info;
Amith Yamasanibe465322014-04-24 13:45:17 -0700618 if (!isProfileOf(user, profile)) {
619 continue;
620 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100621 if (enabledOnly && !profile.isEnabled()) {
622 continue;
Amith Yamasanibe465322014-04-24 13:45:17 -0700623 }
Amith Yamasani70fcf0c2014-07-11 08:40:19 -0700624 if (mRemovingUserIds.get(profile.id)) {
625 continue;
626 }
Tony Mak80189cd2016-04-05 17:21:42 +0100627 if (profile.partial) {
628 continue;
629 }
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700630 result.add(profile.id);
Amith Yamasanibe465322014-04-24 13:45:17 -0700631 }
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700632 return result;
Amith Yamasanibe465322014-04-24 13:45:17 -0700633 }
634
Jessica Hummelbe81c802014-04-22 15:49:22 +0100635 @Override
Andres Moralesc5548c02015-08-05 10:23:12 -0700636 public int getCredentialOwnerProfile(int userHandle) {
637 checkManageUsersPermission("get the credential owner");
Clara Bayarria1771112015-12-18 16:29:18 +0000638 if (!mLockPatternUtils.isSeparateProfileChallengeEnabled(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700639 synchronized (mUsersLock) {
640 UserInfo profileParent = getProfileParentLU(userHandle);
Andres Moralesc5548c02015-08-05 10:23:12 -0700641 if (profileParent != null) {
642 return profileParent.id;
643 }
644 }
645 }
646
647 return userHandle;
648 }
649
650 @Override
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700651 public boolean isSameProfileGroup(int userId, int otherUserId) {
652 if (userId == otherUserId) return true;
653 checkManageUsersPermission("check if in the same profile group");
654 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700655 return isSameProfileGroupLP(userId, otherUserId);
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700656 }
657 }
658
Fyodor Kupolov82402752015-10-28 14:54:51 -0700659 private boolean isSameProfileGroupLP(int userId, int otherUserId) {
660 synchronized (mUsersLock) {
661 UserInfo userInfo = getUserInfoLU(userId);
662 if (userInfo == null || userInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
663 return false;
664 }
665 UserInfo otherUserInfo = getUserInfoLU(otherUserId);
666 if (otherUserInfo == null
667 || otherUserInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
668 return false;
669 }
670 return userInfo.profileGroupId == otherUserInfo.profileGroupId;
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700671 }
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700672 }
673
674 @Override
Jessica Hummelbe81c802014-04-22 15:49:22 +0100675 public UserInfo getProfileParent(int userHandle) {
676 checkManageUsersPermission("get the profile parent");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700677 synchronized (mUsersLock) {
678 return getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700679 }
680 }
681
Fyodor Kupolov82402752015-10-28 14:54:51 -0700682 private UserInfo getProfileParentLU(int userHandle) {
683 UserInfo profile = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700684 if (profile == null) {
685 return null;
686 }
687 int parentUserId = profile.profileGroupId;
688 if (parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
689 return null;
690 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700691 return getUserInfoLU(parentUserId);
Jessica Hummelbe81c802014-04-22 15:49:22 +0100692 }
693 }
694
Fyodor Kupolov82402752015-10-28 14:54:51 -0700695 private static boolean isProfileOf(UserInfo user, UserInfo profile) {
Kenny Guy2a764942014-04-02 13:29:20 +0100696 return user.id == profile.id ||
697 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
698 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000699 }
700
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000701 private void broadcastProfileAvailabilityChanges(UserHandle profileHandle,
Rubin Xuf13c9802016-01-21 18:06:00 +0000702 UserHandle parentHandle, boolean inQuietMode) {
Rubin Xue95057a2016-04-01 16:49:25 +0100703 Intent intent = new Intent();
704 if (inQuietMode) {
705 intent.setAction(Intent.ACTION_MANAGED_PROFILE_UNAVAILABLE);
706 } else {
707 intent.setAction(Intent.ACTION_MANAGED_PROFILE_AVAILABLE);
708 }
Rubin Xuf13c9802016-01-21 18:06:00 +0000709 intent.putExtra(Intent.EXTRA_QUIET_MODE, inQuietMode);
710 intent.putExtra(Intent.EXTRA_USER, profileHandle);
711 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileHandle.getIdentifier());
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000712 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Rubin Xuf13c9802016-01-21 18:06:00 +0000713 mContext.sendBroadcastAsUser(intent, parentHandle);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000714 }
715
716 @Override
717 public void setQuietModeEnabled(int userHandle, boolean enableQuietMode) {
718 checkManageUsersPermission("silence profile");
719 boolean changed = false;
720 UserInfo profile, parent;
721 synchronized (mPackagesLock) {
722 synchronized (mUsersLock) {
723 profile = getUserInfoLU(userHandle);
724 parent = getProfileParentLU(userHandle);
725
726 }
727 if (profile == null || !profile.isManagedProfile()) {
728 throw new IllegalArgumentException("User " + userHandle + " is not a profile");
729 }
730 if (profile.isQuietModeEnabled() != enableQuietMode) {
731 profile.flags ^= UserInfo.FLAG_QUIET_MODE;
Amith Yamasani12747872015-12-07 14:19:49 -0800732 writeUserLP(getUserDataLU(profile.id));
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000733 changed = true;
734 }
735 }
736 if (changed) {
Rubin Xuf13c9802016-01-21 18:06:00 +0000737 long identity = Binder.clearCallingIdentity();
738 try {
739 if (enableQuietMode) {
Nicolas Prevot1219c922016-06-20 17:25:12 +0100740 ActivityManagerNative.getDefault().stopUser(userHandle, /* force */true, null);
Rubin Xuf8451b92016-04-01 15:50:58 +0100741 LocalServices.getService(ActivityManagerInternal.class)
742 .killForegroundAppsForUser(userHandle);
Rubin Xuf13c9802016-01-21 18:06:00 +0000743 } else {
744 ActivityManagerNative.getDefault().startUserInBackground(userHandle);
745 }
746 } catch (RemoteException e) {
747 Slog.e(LOG_TAG, "fail to start/stop user for quiet mode", e);
748 } finally {
749 Binder.restoreCallingIdentity(identity);
750 }
751
752 broadcastProfileAvailabilityChanges(profile.getUserHandle(), parent.getUserHandle(),
753 enableQuietMode);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000754 }
755 }
756
757 @Override
758 public boolean isQuietModeEnabled(int userHandle) {
759 synchronized (mPackagesLock) {
760 UserInfo info;
761 synchronized (mUsersLock) {
762 info = getUserInfoLU(userHandle);
763 }
764 if (info == null || !info.isManagedProfile()) {
Rubin Xuf13c9802016-01-21 18:06:00 +0000765 return false;
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000766 }
767 return info.isQuietModeEnabled();
768 }
769 }
770
Kenny Guya52dc3e2014-02-11 15:33:14 +0000771 @Override
Benjamin Franzf02420c2016-04-04 18:52:21 +0100772 public boolean trySetQuietModeDisabled(int userHandle, IntentSender target) {
Ricky Waib1dd80b2016-06-07 18:00:55 +0100773 checkManageUsersPermission("silence profile");
Jeff Sharkeyce18c812016-04-27 16:00:41 -0600774 if (StorageManager.isUserKeyUnlocked(userHandle)
Ricky Wai9cc7ad62016-05-11 18:00:20 +0100775 || !mLockPatternUtils.isSecure(userHandle)) {
Benjamin Franzf02420c2016-04-04 18:52:21 +0100776 // if the user is already unlocked, no need to show a profile challenge
777 setQuietModeEnabled(userHandle, false);
778 return true;
779 }
780
781 long identity = Binder.clearCallingIdentity();
782 try {
783 // otherwise, we show a profile challenge to trigger decryption of the user
784 final KeyguardManager km = (KeyguardManager) mContext.getSystemService(
785 Context.KEYGUARD_SERVICE);
Ricky Wai7881cf82016-04-15 17:20:12 +0100786 // We should use userHandle not credentialOwnerUserId here, as even if it is unified
787 // lock, confirm screenlock page will know and show personal challenge, and unlock
788 // work profile when personal challenge is correct
Benjamin Franzf02420c2016-04-04 18:52:21 +0100789 final Intent unlockIntent = km.createConfirmDeviceCredentialIntent(null, null,
790 userHandle);
791 if (unlockIntent == null) {
792 return false;
793 }
Ricky Waib1dd80b2016-06-07 18:00:55 +0100794 final Intent callBackIntent = new Intent(
795 ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK);
Benjamin Franzf02420c2016-04-04 18:52:21 +0100796 if (target != null) {
Ricky Waib1dd80b2016-06-07 18:00:55 +0100797 callBackIntent.putExtra(Intent.EXTRA_INTENT, target);
Benjamin Franzf02420c2016-04-04 18:52:21 +0100798 }
Ricky Waib1dd80b2016-06-07 18:00:55 +0100799 callBackIntent.putExtra(Intent.EXTRA_USER_ID, userHandle);
800 callBackIntent.setPackage(mContext.getPackageName());
801 callBackIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
802 final PendingIntent pendingIntent = PendingIntent.getBroadcast(
803 mContext,
804 0,
805 callBackIntent,
806 PendingIntent.FLAG_CANCEL_CURRENT |
807 PendingIntent.FLAG_ONE_SHOT |
808 PendingIntent.FLAG_IMMUTABLE);
809 // After unlocking the challenge, it will disable quiet mode and run the original
810 // intentSender
811 unlockIntent.putExtra(Intent.EXTRA_INTENT, pendingIntent.getIntentSender());
Benjamin Franzf02420c2016-04-04 18:52:21 +0100812 unlockIntent.setFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
813 mContext.startActivity(unlockIntent);
814 } finally {
815 Binder.restoreCallingIdentity(identity);
816 }
817 return false;
818 }
819
820 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100821 public void setUserEnabled(int userId) {
822 checkManageUsersPermission("enable user");
823 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700824 UserInfo info;
825 synchronized (mUsersLock) {
826 info = getUserInfoLU(userId);
827 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100828 if (info != null && !info.isEnabled()) {
829 info.flags ^= UserInfo.FLAG_DISABLED;
Amith Yamasani12747872015-12-07 14:19:49 -0800830 writeUserLP(getUserDataLU(info.id));
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100831 }
832 }
833 }
834
835 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700836 public UserInfo getUserInfo(int userId) {
Sudheer Shankaaccaa082016-06-14 16:22:57 -0700837 checkManageOrCreateUsersPermission("query user");
Tony Mak8673b282016-03-21 21:10:59 +0000838 synchronized (mUsersLock) {
Amith Yamasani6f48d6e2016-03-23 14:28:25 -0700839 return userWithName(getUserInfoLU(userId));
840 }
841 }
842
843 /**
844 * Returns a UserInfo object with the name filled in, for Owner, or the original
845 * if the name is already set.
846 */
847 private UserInfo userWithName(UserInfo orig) {
848 if (orig != null && orig.name == null && orig.id == UserHandle.USER_SYSTEM) {
849 UserInfo withName = new UserInfo(orig);
850 withName.name = getOwnerName();
851 return withName;
852 } else {
853 return orig;
Tony Mak8673b282016-03-21 21:10:59 +0000854 }
855 }
856
857 @Override
858 public boolean isManagedProfile(int userId) {
Tony Makb531d082016-03-16 14:49:52 +0000859 int callingUserId = UserHandle.getCallingUserId();
860 if (callingUserId != userId && !hasManageUsersPermission()) {
861 synchronized (mPackagesLock) {
862 if (!isSameProfileGroupLP(callingUserId, userId)) {
863 throw new SecurityException(
Tony Mak8673b282016-03-21 21:10:59 +0000864 "You need MANAGE_USERS permission to: check if specified user a " +
865 "managed profile outside your profile group");
Tony Makb531d082016-03-16 14:49:52 +0000866 }
867 }
Tony Mak4dc008c2016-03-16 10:46:49 +0000868 }
Fyodor Kupolov82402752015-10-28 14:54:51 -0700869 synchronized (mUsersLock) {
Tony Mak8673b282016-03-21 21:10:59 +0000870 UserInfo userInfo = getUserInfoLU(userId);
871 return userInfo != null && userInfo.isManagedProfile();
Amith Yamasani13593602012-03-22 16:16:17 -0700872 }
873 }
874
Amith Yamasani71e6c692013-03-24 17:39:28 -0700875 @Override
876 public boolean isRestricted() {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700877 synchronized (mUsersLock) {
878 return getUserInfoLU(UserHandle.getCallingUserId()).isRestricted();
Amith Yamasani71e6c692013-03-24 17:39:28 -0700879 }
880 }
881
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700882 @Override
883 public boolean canHaveRestrictedProfile(int userId) {
884 checkManageUsersPermission("canHaveRestrictedProfile");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700885 synchronized (mUsersLock) {
886 final UserInfo userInfo = getUserInfoLU(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700887 if (userInfo == null || !userInfo.canHaveProfile()) {
888 return false;
889 }
890 if (!userInfo.isAdmin()) {
891 return false;
892 }
Makoto Onukie7927da2015-11-25 10:05:17 -0800893 // restricted profile can be created if there is no DO set and the admin user has no PO;
894 return !mIsDeviceManaged && !mIsUserManaged.get(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700895 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700896 }
897
Amith Yamasani195263742012-08-21 15:40:12 -0700898 /*
899 * Should be locked on mUsers before calling this.
900 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700901 private UserInfo getUserInfoLU(int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -0800902 final UserData userData = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -0700903 // If it is partial and not in the process of being removed, return as unknown user.
Amith Yamasani12747872015-12-07 14:19:49 -0800904 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700905 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
906 return null;
907 }
Amith Yamasani12747872015-12-07 14:19:49 -0800908 return userData != null ? userData.info : null;
909 }
910
911 private UserData getUserDataLU(int userId) {
912 final UserData userData = mUsers.get(userId);
913 // If it is partial and not in the process of being removed, return as unknown user.
914 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
915 return null;
916 }
917 return userData;
Amith Yamasani195263742012-08-21 15:40:12 -0700918 }
919
Fyodor Kupolov82402752015-10-28 14:54:51 -0700920 /**
921 * Obtains {@link #mUsersLock} and return UserInfo from mUsers.
922 * <p>No permissions checking or any addition checks are made</p>
923 */
924 private UserInfo getUserInfoNoChecks(int userId) {
925 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800926 final UserData userData = mUsers.get(userId);
927 return userData != null ? userData.info : null;
928 }
929 }
930
931 /**
932 * Obtains {@link #mUsersLock} and return UserData from mUsers.
933 * <p>No permissions checking or any addition checks are made</p>
934 */
935 private UserData getUserDataNoChecks(int userId) {
936 synchronized (mUsersLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700937 return mUsers.get(userId);
938 }
939 }
940
Amith Yamasani236b2b52015-08-18 14:32:14 -0700941 /** Called by PackageManagerService */
Amith Yamasani13593602012-03-22 16:16:17 -0700942 public boolean exists(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700943 return getUserInfoNoChecks(userId) != null;
Amith Yamasani13593602012-03-22 16:16:17 -0700944 }
945
Amith Yamasani258848d2012-08-10 17:06:33 -0700946 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700947 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700948 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700949 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700950 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800951 UserData userData = getUserDataNoChecks(userId);
952 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700953 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
954 return;
955 }
Amith Yamasani12747872015-12-07 14:19:49 -0800956 if (name != null && !name.equals(userData.info.name)) {
957 userData.info.name = name;
958 writeUserLP(userData);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700959 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -0700960 }
961 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700962 if (changed) {
963 sendUserInfoChangedBroadcast(userId);
964 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700965 }
966
Amith Yamasani258848d2012-08-10 17:06:33 -0700967 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700968 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700969 checkManageUsersPermission("update users");
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +0100970 if (hasUserRestriction(UserManager.DISALLOW_SET_USER_ICON, userId)) {
971 Log.w(LOG_TAG, "Cannot set user icon. DISALLOW_SET_USER_ICON is enabled.");
972 return;
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700973 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +0100974 mLocalService.setUserIcon(userId, bitmap);
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700975 }
976
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +0100977
978
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700979 private void sendUserInfoChangedBroadcast(int userId) {
980 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
981 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
982 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -0700983 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700984 }
985
Amith Yamasani258848d2012-08-10 17:06:33 -0700986 @Override
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +0100987 public ParcelFileDescriptor getUserIcon(int targetUserId) {
Adrian Roos1bdff912015-02-17 15:51:35 +0100988 String iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700989 synchronized (mPackagesLock) {
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +0100990 UserInfo targetUserInfo = getUserInfoNoChecks(targetUserId);
991 if (targetUserInfo == null || targetUserInfo.partial) {
992 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + targetUserId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700993 return null;
994 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +0100995
996 final int callingUserId = UserHandle.getCallingUserId();
997 final int callingGroupId = getUserInfoNoChecks(callingUserId).profileGroupId;
998 final int targetGroupId = targetUserInfo.profileGroupId;
999 final boolean sameGroup = (callingGroupId != UserInfo.NO_PROFILE_GROUP_ID
1000 && callingGroupId == targetGroupId);
1001 if ((callingUserId != targetUserId) && !sameGroup) {
Nicolas Prevot88cc3462014-05-14 14:51:48 +01001002 checkManageUsersPermission("get the icon of a user who is not related");
1003 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001004
1005 if (targetUserInfo.iconPath == null) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001006 return null;
1007 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001008 iconPath = targetUserInfo.iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001009 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001010
1011 try {
1012 return ParcelFileDescriptor.open(
1013 new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
1014 } catch (FileNotFoundException e) {
1015 Log.e(LOG_TAG, "Couldn't find icon file", e);
1016 }
1017 return null;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001018 }
1019
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001020 public void makeInitialized(int userId) {
1021 checkManageUsersPermission("makeInitialized");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001022 boolean scheduleWriteUser = false;
Amith Yamasani12747872015-12-07 14:19:49 -08001023 UserData userData;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001024 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001025 userData = mUsers.get(userId);
1026 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001027 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001028 return;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001029 }
Amith Yamasani12747872015-12-07 14:19:49 -08001030 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1031 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001032 scheduleWriteUser = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001033 }
1034 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001035 if (scheduleWriteUser) {
Amith Yamasani12747872015-12-07 14:19:49 -08001036 scheduleWriteUser(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001037 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001038 }
1039
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001040 /**
1041 * If default guest restrictions haven't been initialized yet, add the basic
1042 * restrictions.
1043 */
1044 private void initDefaultGuestRestrictions() {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001045 synchronized (mGuestRestrictions) {
1046 if (mGuestRestrictions.isEmpty()) {
Samuel Tand9453b82016-03-14 15:57:02 -07001047 mGuestRestrictions.putBoolean(UserManager.DISALLOW_CONFIG_WIFI, true);
Fyodor Kupolove04462c2015-11-30 15:02:53 -08001048 mGuestRestrictions.putBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, true);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001049 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
1050 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
1051 }
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001052 }
1053 }
1054
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001055 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301056 public Bundle getDefaultGuestRestrictions() {
1057 checkManageUsersPermission("getDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001058 synchronized (mGuestRestrictions) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301059 return new Bundle(mGuestRestrictions);
1060 }
1061 }
1062
1063 @Override
1064 public void setDefaultGuestRestrictions(Bundle restrictions) {
1065 checkManageUsersPermission("setDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001066 synchronized (mGuestRestrictions) {
1067 mGuestRestrictions.clear();
1068 mGuestRestrictions.putAll(restrictions);
1069 }
1070 synchronized (mPackagesLock) {
1071 writeUserListLP();
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301072 }
1073 }
1074
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001075 /**
1076 * See {@link UserManagerInternal#setDevicePolicyUserRestrictions(int, Bundle, Bundle)}
1077 */
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08001078 void setDevicePolicyUserRestrictionsInner(int userId, @NonNull Bundle local,
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001079 @Nullable Bundle global) {
1080 Preconditions.checkNotNull(local);
1081 boolean globalChanged = false;
1082 boolean localChanged;
1083 synchronized (mRestrictionsLock) {
1084 if (global != null) {
1085 // Update global.
1086 globalChanged = !UserRestrictionsUtils.areEqual(
1087 mDevicePolicyGlobalUserRestrictions, global);
1088 if (globalChanged) {
1089 mDevicePolicyGlobalUserRestrictions = global;
1090 }
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001091 // Remember the global restriction owner userId to be able to make a distinction
1092 // in getUserRestrictionSource on who set local policies.
1093 mGlobalRestrictionOwnerUserId = userId;
1094 } else {
Zoltan Szatmary-Ban8a5536d2016-05-27 17:56:44 +01001095 if (mGlobalRestrictionOwnerUserId == userId) {
1096 // When profile owner sets restrictions it passes null global bundle and we
1097 // reset global restriction owner userId.
1098 // This means this user used to have DO, but now the DO is gone and the user
1099 // instead has PO.
1100 mGlobalRestrictionOwnerUserId = UserHandle.USER_NULL;
1101 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001102 }
1103 {
1104 // Update local.
1105 final Bundle prev = mDevicePolicyLocalUserRestrictions.get(userId);
1106 localChanged = !UserRestrictionsUtils.areEqual(prev, local);
1107 if (localChanged) {
1108 mDevicePolicyLocalUserRestrictions.put(userId, local);
1109 }
1110 }
1111 }
1112 if (DBG) {
1113 Log.d(LOG_TAG, "setDevicePolicyUserRestrictions: userId=" + userId
1114 + " global=" + global + (globalChanged ? " (changed)" : "")
1115 + " local=" + local + (localChanged ? " (changed)" : "")
1116 );
1117 }
1118 // Don't call them within the mRestrictionsLock.
1119 synchronized (mPackagesLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001120 if (localChanged) {
Amith Yamasani12747872015-12-07 14:19:49 -08001121 writeUserLP(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001122 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06001123 if (globalChanged) {
1124 writeUserListLP();
1125 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001126 }
1127
1128 synchronized (mRestrictionsLock) {
1129 if (globalChanged) {
1130 applyUserRestrictionsForAllUsersLR();
1131 } else if (localChanged) {
1132 applyUserRestrictionsLR(userId);
1133 }
1134 }
1135 }
1136
Makoto Onuki068c54a2015-10-13 14:34:03 -07001137 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001138 private Bundle computeEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001139 final Bundle baseRestrictions =
1140 UserRestrictionsUtils.nonNull(mBaseUserRestrictions.get(userId));
1141 final Bundle global = mDevicePolicyGlobalUserRestrictions;
1142 final Bundle local = mDevicePolicyLocalUserRestrictions.get(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001143
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001144 if (UserRestrictionsUtils.isEmpty(global) && UserRestrictionsUtils.isEmpty(local)) {
1145 // Common case first.
1146 return baseRestrictions;
Makoto Onuki068c54a2015-10-13 14:34:03 -07001147 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001148 final Bundle effective = UserRestrictionsUtils.clone(baseRestrictions);
1149 UserRestrictionsUtils.merge(effective, global);
1150 UserRestrictionsUtils.merge(effective, local);
1151
Makoto Onuki068c54a2015-10-13 14:34:03 -07001152 return effective;
1153 }
1154
1155 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001156 private void invalidateEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki068c54a2015-10-13 14:34:03 -07001157 if (DBG) {
1158 Log.d(LOG_TAG, "invalidateEffectiveUserRestrictions userId=" + userId);
1159 }
1160 mCachedEffectiveUserRestrictions.remove(userId);
1161 }
1162
1163 private Bundle getEffectiveUserRestrictions(int userId) {
1164 synchronized (mRestrictionsLock) {
1165 Bundle restrictions = mCachedEffectiveUserRestrictions.get(userId);
1166 if (restrictions == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001167 restrictions = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001168 mCachedEffectiveUserRestrictions.put(userId, restrictions);
1169 }
1170 return restrictions;
Amith Yamasani8cd28b52014-06-08 17:54:27 -07001171 }
1172 }
1173
Makoto Onuki068c54a2015-10-13 14:34:03 -07001174 /** @return a specific user restriction that's in effect currently. */
1175 @Override
1176 public boolean hasUserRestriction(String restrictionKey, int userId) {
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001177 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1178 return false;
1179 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001180 Bundle restrictions = getEffectiveUserRestrictions(userId);
1181 return restrictions != null && restrictions.getBoolean(restrictionKey);
1182 }
1183
1184 /**
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001185 * @hide
1186 *
1187 * Returns who set a user restriction on a user.
1188 * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
1189 * @param restrictionKey the string key representing the restriction
1190 * @param userId the id of the user for whom to retrieve the restrictions.
1191 * @return The source of user restriction. Any combination of
1192 * {@link UserManager#RESTRICTION_NOT_SET},
1193 * {@link UserManager#RESTRICTION_SOURCE_SYSTEM},
1194 * {@link UserManager#RESTRICTION_SOURCE_DEVICE_OWNER}
1195 * and {@link UserManager#RESTRICTION_SOURCE_PROFILE_OWNER}
1196 */
1197 @Override
1198 public int getUserRestrictionSource(String restrictionKey, int userId) {
1199 checkManageUsersPermission("getUserRestrictionSource");
1200 int result = UserManager.RESTRICTION_NOT_SET;
1201
1202 // Shortcut for the most common case
1203 if (!hasUserRestriction(restrictionKey, userId)) {
1204 return result;
1205 }
1206
1207 if (hasBaseUserRestriction(restrictionKey, userId)) {
1208 result |= UserManager.RESTRICTION_SOURCE_SYSTEM;
1209 }
1210
1211 synchronized(mRestrictionsLock) {
1212 Bundle localRestrictions = mDevicePolicyLocalUserRestrictions.get(userId);
1213 if (!UserRestrictionsUtils.isEmpty(localRestrictions)
1214 && localRestrictions.getBoolean(restrictionKey)) {
1215 // Local restrictions may have been set by device owner the userId of which is
1216 // stored in mGlobalRestrictionOwnerUserId.
1217 if (mGlobalRestrictionOwnerUserId == userId) {
1218 result |= UserManager.RESTRICTION_SOURCE_DEVICE_OWNER;
1219 } else {
1220 result |= UserManager.RESTRICTION_SOURCE_PROFILE_OWNER;
1221 }
1222 }
1223 if (!UserRestrictionsUtils.isEmpty(mDevicePolicyGlobalUserRestrictions)
1224 && mDevicePolicyGlobalUserRestrictions.getBoolean(restrictionKey)) {
1225 result |= UserManager.RESTRICTION_SOURCE_DEVICE_OWNER;
1226 }
1227 }
1228
1229 return result;
1230 }
1231
1232 /**
Makoto Onuki068c54a2015-10-13 14:34:03 -07001233 * @return UserRestrictions that are in effect currently. This always returns a new
1234 * {@link Bundle}.
1235 */
Amith Yamasani8cd28b52014-06-08 17:54:27 -07001236 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001237 public Bundle getUserRestrictions(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001238 return UserRestrictionsUtils.clone(getEffectiveUserRestrictions(userId));
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001239 }
1240
1241 @Override
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +00001242 public boolean hasBaseUserRestriction(String restrictionKey, int userId) {
1243 checkManageUsersPermission("hasBaseUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001244 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1245 return false;
1246 }
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +00001247 synchronized (mRestrictionsLock) {
1248 Bundle bundle = mBaseUserRestrictions.get(userId);
1249 return (bundle != null && bundle.getBoolean(restrictionKey, false));
1250 }
1251 }
1252
1253 @Override
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001254 public void setUserRestriction(String key, boolean value, int userId) {
Fyodor Kupolovd4b26042015-07-27 14:30:59 -07001255 checkManageUsersPermission("setUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001256 if (!UserRestrictionsUtils.isValidRestriction(key)) {
1257 return;
1258 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001259 synchronized (mRestrictionsLock) {
1260 // Note we can't modify Bundles stored in mBaseUserRestrictions directly, so create
1261 // a copy.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001262 final Bundle newRestrictions = UserRestrictionsUtils.clone(
1263 mBaseUserRestrictions.get(userId));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001264 newRestrictions.putBoolean(key, value);
1265
Fyodor Kupolov82402752015-10-28 14:54:51 -07001266 updateUserRestrictionsInternalLR(newRestrictions, userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001267 }
1268 }
1269
Makoto Onuki068c54a2015-10-13 14:34:03 -07001270 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001271 * Optionally updating user restrictions, calculate the effective user restrictions and also
1272 * propagate to other services and system settings.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001273 *
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001274 * @param newRestrictions User restrictions to set.
1275 * If null, will not update user restrictions and only does the propagation.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001276 * @param userId target user ID.
1277 */
1278 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001279 private void updateUserRestrictionsInternalLR(
Makoto Onuki068c54a2015-10-13 14:34:03 -07001280 @Nullable Bundle newRestrictions, int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001281
1282 final Bundle prevAppliedRestrictions = UserRestrictionsUtils.nonNull(
1283 mAppliedUserRestrictions.get(userId));
1284
1285 // Update base restrictions.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001286 if (newRestrictions != null) {
1287 // If newRestrictions == the current one, it's probably a bug.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001288 final Bundle prevBaseRestrictions = mBaseUserRestrictions.get(userId);
1289
1290 Preconditions.checkState(prevBaseRestrictions != newRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001291 Preconditions.checkState(mCachedEffectiveUserRestrictions.get(userId)
1292 != newRestrictions);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001293
1294 if (!UserRestrictionsUtils.areEqual(prevBaseRestrictions, newRestrictions)) {
1295 mBaseUserRestrictions.put(userId, newRestrictions);
Amith Yamasani12747872015-12-07 14:19:49 -08001296 scheduleWriteUser(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001297 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001298 }
1299
Fyodor Kupolov82402752015-10-28 14:54:51 -07001300 final Bundle effective = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001301
Makoto Onuki759a7632015-10-28 16:43:10 -07001302 mCachedEffectiveUserRestrictions.put(userId, effective);
1303
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001304 // Apply the new restrictions.
Makoto Onuki4f160732015-10-27 17:15:38 -07001305 if (DBG) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001306 debug("Applying user restrictions: userId=" + userId
1307 + " new=" + effective + " prev=" + prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001308 }
1309
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001310 if (mAppOpsService != null) { // We skip it until system-ready.
Fyodor Kupolovec30ca32016-06-16 15:09:29 -07001311 mHandler.post(new Runnable() {
1312 @Override
1313 public void run() {
1314 try {
1315 mAppOpsService.setUserRestrictions(effective, mUserRestriconToken, userId);
1316 } catch (RemoteException e) {
1317 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
1318 }
1319 }
1320 });
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001321 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001322
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001323 propagateUserRestrictionsLR(userId, effective, prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001324
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001325 mAppliedUserRestrictions.put(userId, new Bundle(effective));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001326 }
1327
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001328 private void propagateUserRestrictionsLR(final int userId,
Makoto Onukid45a4a22015-11-02 17:17:38 -08001329 Bundle newRestrictions, Bundle prevRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001330 // Note this method doesn't touch any state, meaning it doesn't require mRestrictionsLock
1331 // actually, but we still need some kind of synchronization otherwise we might end up
1332 // calling listeners out-of-order, thus "LR".
1333
1334 if (UserRestrictionsUtils.areEqual(newRestrictions, prevRestrictions)) {
1335 return;
1336 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08001337
1338 final Bundle newRestrictionsFinal = new Bundle(newRestrictions);
1339 final Bundle prevRestrictionsFinal = new Bundle(prevRestrictions);
1340
1341 mHandler.post(new Runnable() {
1342 @Override
1343 public void run() {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07001344 UserRestrictionsUtils.applyUserRestrictions(
1345 mContext, userId, newRestrictionsFinal, prevRestrictionsFinal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001346
Makoto Onukid45a4a22015-11-02 17:17:38 -08001347 final UserRestrictionsListener[] listeners;
1348 synchronized (mUserRestrictionsListeners) {
1349 listeners = new UserRestrictionsListener[mUserRestrictionsListeners.size()];
1350 mUserRestrictionsListeners.toArray(listeners);
1351 }
1352 for (int i = 0; i < listeners.length; i++) {
1353 listeners[i].onUserRestrictionsChanged(userId,
1354 newRestrictionsFinal, prevRestrictionsFinal);
1355 }
1356 }
1357 });
1358 }
1359
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001360 // Package private for the inner class.
1361 void applyUserRestrictionsLR(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001362 updateUserRestrictionsInternalLR(null, userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001363 }
1364
1365 @GuardedBy("mRestrictionsLock")
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001366 // Package private for the inner class.
1367 void applyUserRestrictionsForAllUsersLR() {
1368 if (DBG) {
1369 debug("applyUserRestrictionsForAllUsersLR");
1370 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001371 // First, invalidate all cached values.
Makoto Onuki4f160732015-10-27 17:15:38 -07001372 mCachedEffectiveUserRestrictions.clear();
1373
Makoto Onuki068c54a2015-10-13 14:34:03 -07001374 // We don't want to call into ActivityManagerNative while taking a lock, so we'll call
1375 // it on a handler.
1376 final Runnable r = new Runnable() {
1377 @Override
1378 public void run() {
1379 // Then get the list of running users.
1380 final int[] runningUsers;
1381 try {
1382 runningUsers = ActivityManagerNative.getDefault().getRunningUserIds();
1383 } catch (RemoteException e) {
1384 Log.w(LOG_TAG, "Unable to access ActivityManagerNative");
1385 return;
1386 }
1387 // Then re-calculate the effective restrictions and apply, only for running users.
1388 // It's okay if a new user has started after the getRunningUserIds() call,
1389 // because we'll do the same thing (re-calculate the restrictions and apply)
1390 // when we start a user.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001391 synchronized (mRestrictionsLock) {
1392 for (int i = 0; i < runningUsers.length; i++) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001393 applyUserRestrictionsLR(runningUsers[i]);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001394 }
1395 }
1396 }
1397 };
1398 mHandler.post(r);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001399 }
1400
Amith Yamasani258848d2012-08-10 17:06:33 -07001401 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001402 * Check if we've hit the limit of how many users can be created.
1403 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001404 private boolean isUserLimitReached() {
1405 int count;
1406 synchronized (mUsersLock) {
1407 count = getAliveUsersExcludingGuestsCountLU();
1408 }
1409 return count >= UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001410 }
1411
1412 @Override
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001413 public boolean canAddMoreManagedProfiles(int userId, boolean allowedToRemoveOne) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001414 checkManageUsersPermission("check if more managed profiles can be added.");
1415 if (ActivityManager.isLowRamDeviceStatic()) {
1416 return false;
1417 }
Fyodor Kupolovb6157992015-06-05 15:32:28 -07001418 if (!mContext.getPackageManager().hasSystemFeature(
1419 PackageManager.FEATURE_MANAGED_USERS)) {
1420 return false;
1421 }
Nicolas Prevotb8186812015-08-06 15:00:03 +01001422 // Limit number of managed profiles that can be created
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001423 final int managedProfilesCount = getProfiles(userId, true).size() - 1;
1424 final int profilesRemovedCount = managedProfilesCount > 0 && allowedToRemoveOne ? 1 : 0;
1425 if (managedProfilesCount - profilesRemovedCount >= MAX_MANAGED_PROFILES) {
Nicolas Prevotb8186812015-08-06 15:00:03 +01001426 return false;
1427 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001428 synchronized(mUsersLock) {
1429 UserInfo userInfo = getUserInfoLU(userId);
Nicolas Prevotb8186812015-08-06 15:00:03 +01001430 if (!userInfo.canHaveProfile()) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001431 return false;
1432 }
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001433 int usersCountAfterRemoving = getAliveUsersExcludingGuestsCountLU()
1434 - profilesRemovedCount;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001435 // We allow creating a managed profile in the special case where there is only one user.
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001436 return usersCountAfterRemoving == 1
1437 || usersCountAfterRemoving < UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001438 }
1439 }
1440
Fyodor Kupolov82402752015-10-28 14:54:51 -07001441 private int getAliveUsersExcludingGuestsCountLU() {
Amith Yamasanif584f012014-05-19 17:57:25 -07001442 int aliveUserCount = 0;
1443 final int totalUserCount = mUsers.size();
1444 // Skip over users being removed
1445 for (int i = 0; i < totalUserCount; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001446 UserInfo user = mUsers.valueAt(i).info;
Amith Yamasani95ab7842014-08-11 17:09:26 -07001447 if (!mRemovingUserIds.get(user.id)
Amith Yamasani1df14732014-08-29 21:37:27 -07001448 && !user.isGuest() && !user.partial) {
Amith Yamasanif584f012014-05-19 17:57:25 -07001449 aliveUserCount++;
1450 }
1451 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001452 return aliveUserCount;
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001453 }
1454
1455 /**
Amith Yamasani195263742012-08-21 15:40:12 -07001456 * Enforces that only the system UID or root's UID or apps that have the
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001457 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} and
1458 * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL INTERACT_ACROSS_USERS_FULL}
1459 * permissions can make certain calls to the UserManager.
1460 *
1461 * @param message used as message if SecurityException is thrown
1462 * @throws SecurityException if the caller does not have enough privilege.
1463 */
1464 private static final void checkManageUserAndAcrossUsersFullPermission(String message) {
1465 final int uid = Binder.getCallingUid();
1466 if (uid != Process.SYSTEM_UID && uid != 0
1467 && ActivityManager.checkComponentPermission(
1468 Manifest.permission.MANAGE_USERS,
1469 uid, -1, true) != PackageManager.PERMISSION_GRANTED
1470 && ActivityManager.checkComponentPermission(
1471 Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1472 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
1473 throw new SecurityException(
1474 "You need MANAGE_USERS and INTERACT_ACROSS_USERS_FULL permission to: "
1475 + message);
1476 }
1477 }
1478
1479 /**
1480 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001481 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -07001482 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -07001483 *
1484 * @param message used as message if SecurityException is thrown
1485 * @throws SecurityException if the caller is not system or root
Tony Mak4dc008c2016-03-16 10:46:49 +00001486 * @see #hasManageUsersPermission()
Amith Yamasani258848d2012-08-10 17:06:33 -07001487 */
Amith Yamasanibe465322014-04-24 13:45:17 -07001488 private static final void checkManageUsersPermission(String message) {
Tony Mak4dc008c2016-03-16 10:46:49 +00001489 if (!hasManageUsersPermission()) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001490 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
1491 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -04001492 }
1493
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001494 /**
Sudheer Shankaf5cea032016-06-08 17:13:24 -07001495 * Enforces that only the system UID or root's UID or apps that have the
1496 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or
1497 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS}
1498 * can make certain calls to the UserManager.
1499 *
1500 * @param message used as message if SecurityException is thrown
1501 * @throws SecurityException if the caller is not system or root
1502 * @see #hasManageOrCreateUsersPermission()
1503 */
1504 private static final void checkManageOrCreateUsersPermission(String message) {
1505 if (!hasManageOrCreateUsersPermission()) {
1506 throw new SecurityException(
1507 "You either need MANAGE_USERS or CREATE_USERS permission to: " + message);
1508 }
1509 }
1510
1511 /**
1512 * Similar to {@link #checkManageOrCreateUsersPermission(String)} but when the caller is tries
1513 * to create user/profiles other than what is allowed for
1514 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS} permission, then it will only
1515 * allow callers with {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} permission.
1516 */
1517 private static final void checkManageOrCreateUsersPermission(int creationFlags) {
1518 if ((creationFlags & ~ALLOWED_FLAGS_FOR_CREATE_USERS_PERMISSION) == 0) {
1519 if (!hasManageOrCreateUsersPermission()) {
1520 throw new SecurityException("You either need MANAGE_USERS or CREATE_USERS "
1521 + "permission to create an user with flags: " + creationFlags);
1522 }
1523 } else if (!hasManageUsersPermission()) {
1524 throw new SecurityException("You need MANAGE_USERS permission to create an user "
1525 + " with flags: " + creationFlags);
1526 }
1527 }
1528
1529 /**
Tony Mak4dc008c2016-03-16 10:46:49 +00001530 * @return whether the calling UID is system UID or root's UID or the calling app has the
1531 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}.
1532 */
1533 private static final boolean hasManageUsersPermission() {
1534 final int callingUid = Binder.getCallingUid();
1535 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
1536 || callingUid == Process.ROOT_UID
1537 || ActivityManager.checkComponentPermission(
1538 android.Manifest.permission.MANAGE_USERS,
1539 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED;
1540 }
1541
1542 /**
Sudheer Shankaf5cea032016-06-08 17:13:24 -07001543 * @return whether the calling UID is system UID or root's UID or the calling app has the
1544 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or
1545 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS}.
1546 */
1547 private static final boolean hasManageOrCreateUsersPermission() {
1548 final int callingUid = Binder.getCallingUid();
1549 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
1550 || callingUid == Process.ROOT_UID
1551 || ActivityManager.checkComponentPermission(
1552 android.Manifest.permission.MANAGE_USERS,
1553 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED
1554 || ActivityManager.checkComponentPermission(
1555 android.Manifest.permission.CREATE_USERS,
1556 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED;
1557 }
1558
1559 /**
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001560 * Enforces that only the system UID or root's UID (on any user) can make certain calls to the
1561 * UserManager.
1562 *
1563 * @param message used as message if SecurityException is thrown
1564 * @throws SecurityException if the caller is not system or root
1565 */
1566 private static void checkSystemOrRoot(String message) {
1567 final int uid = Binder.getCallingUid();
1568 if (!UserHandle.isSameApp(uid, Process.SYSTEM_UID) && uid != Process.ROOT_UID) {
1569 throw new SecurityException("Only system may: " + message);
1570 }
1571 }
1572
Fyodor Kupolov82402752015-10-28 14:54:51 -07001573 private void writeBitmapLP(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001574 try {
1575 File dir = new File(mUsersDir, Integer.toString(info.id));
1576 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +01001577 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001578 if (!dir.exists()) {
1579 dir.mkdir();
1580 FileUtils.setPermissions(
1581 dir.getPath(),
1582 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
1583 -1, -1);
1584 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001585 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +01001586 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001587 && tmp.renameTo(file) && SELinux.restorecon(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -07001588 info.iconPath = file.getAbsolutePath();
1589 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001590 try {
1591 os.close();
1592 } catch (IOException ioe) {
1593 // What the ... !
1594 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001595 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001596 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001597 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001598 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001599 }
1600
Amith Yamasani0b285492011-04-14 17:35:23 -07001601 /**
1602 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
1603 * cache it elsewhere.
1604 * @return the array of user ids.
1605 */
Dianne Hackborn1676c852012-09-10 14:52:30 -07001606 public int[] getUserIds() {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001607 synchronized (mUsersLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001608 return mUserIds;
1609 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001610 }
1611
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001612 private void readUserListLP() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001613 if (!mUserListFile.exists()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001614 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001615 return;
1616 }
1617 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001618 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001619 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001620 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001621 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001622 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001623 int type;
1624 while ((type = parser.next()) != XmlPullParser.START_TAG
1625 && type != XmlPullParser.END_DOCUMENT) {
Amith Yamasani12747872015-12-07 14:19:49 -08001626 // Skip
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001627 }
1628
1629 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001630 Slog.e(LOG_TAG, "Unable to read user list");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001631 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001632 return;
1633 }
1634
Amith Yamasani2a003292012-08-14 18:25:45 -07001635 mNextSerialNumber = -1;
1636 if (parser.getName().equals(TAG_USERS)) {
1637 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
1638 if (lastSerialNumber != null) {
1639 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
1640 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001641 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
1642 if (versionNumber != null) {
1643 mUserVersion = Integer.parseInt(versionNumber);
1644 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001645 }
1646
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001647 final Bundle newDevicePolicyGlobalUserRestrictions = new Bundle();
1648
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001649 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301650 if (type == XmlPullParser.START_TAG) {
1651 final String name = parser.getName();
1652 if (name.equals(TAG_USER)) {
1653 String id = parser.getAttributeValue(null, ATTR_ID);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001654
Amith Yamasani12747872015-12-07 14:19:49 -08001655 UserData userData = readUserLP(Integer.parseInt(id));
1656
1657 if (userData != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001658 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001659 mUsers.put(userData.info.id, userData);
1660 if (mNextSerialNumber < 0
1661 || mNextSerialNumber <= userData.info.id) {
1662 mNextSerialNumber = userData.info.id + 1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001663 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301664 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001665 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301666 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -08001667 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1668 && type != XmlPullParser.END_TAG) {
1669 if (type == XmlPullParser.START_TAG) {
1670 if (parser.getName().equals(TAG_RESTRICTIONS)) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001671 synchronized (mGuestRestrictions) {
1672 UserRestrictionsUtils
1673 .readRestrictions(parser, mGuestRestrictions);
1674 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001675 } else if (parser.getName().equals(TAG_DEVICE_POLICY_RESTRICTIONS)
1676 ) {
1677 UserRestrictionsUtils.readRestrictions(parser,
1678 newDevicePolicyGlobalUserRestrictions);
Amith Yamasanida0b1682014-11-21 12:58:17 -08001679 }
1680 break;
1681 }
1682 }
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001683 } else if (name.equals(TAG_GLOBAL_RESTRICTION_OWNER_ID)) {
1684 String ownerUserId = parser.getAttributeValue(null, ATTR_ID);
1685 if (ownerUserId != null) {
1686 mGlobalRestrictionOwnerUserId = Integer.parseInt(ownerUserId);
1687 }
Amith Yamasani258848d2012-08-10 17:06:33 -07001688 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001689 }
1690 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001691 synchronized (mRestrictionsLock) {
1692 mDevicePolicyGlobalUserRestrictions = newDevicePolicyGlobalUserRestrictions;
1693 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001694 updateUserIds();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001695 upgradeIfNecessaryLP();
1696 } catch (IOException | XmlPullParserException e) {
1697 fallbackToSingleUserLP();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001698 } finally {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001699 IoUtils.closeQuietly(fis);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001700 }
1701 }
1702
Amith Yamasani6f34b412012-10-22 18:19:27 -07001703 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -08001704 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -07001705 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001706 private void upgradeIfNecessaryLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001707 final int originalVersion = mUserVersion;
Amith Yamasani6f34b412012-10-22 18:19:27 -07001708 int userVersion = mUserVersion;
1709 if (userVersion < 1) {
1710 // Assign a proper name for the owner, if not initialized correctly before
Amith Yamasani12747872015-12-07 14:19:49 -08001711 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
1712 if ("Primary".equals(userData.info.name)) {
1713 userData.info.name =
1714 mContext.getResources().getString(com.android.internal.R.string.owner_name);
1715 scheduleWriteUser(userData);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001716 }
1717 userVersion = 1;
1718 }
1719
Amith Yamasanibc9625052012-11-15 14:39:18 -08001720 if (userVersion < 2) {
1721 // Owner should be marked as initialized
Amith Yamasani12747872015-12-07 14:19:49 -08001722 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
1723 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1724 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
1725 scheduleWriteUser(userData);
Amith Yamasanibc9625052012-11-15 14:39:18 -08001726 }
1727 userVersion = 2;
1728 }
1729
Amith Yamasani350962c2013-08-06 11:18:53 -07001730
Amith Yamasani5e486f52013-08-07 11:06:44 -07001731 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -07001732 userVersion = 4;
1733 }
1734
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001735 if (userVersion < 5) {
1736 initDefaultGuestRestrictions();
1737 userVersion = 5;
1738 }
1739
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001740 if (userVersion < 6) {
1741 final boolean splitSystemUser = UserManager.isSplitSystemUser();
Fyodor Kupolov82402752015-10-28 14:54:51 -07001742 synchronized (mUsersLock) {
1743 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001744 UserData userData = mUsers.valueAt(i);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001745 // In non-split mode, only user 0 can have restricted profiles
Amith Yamasani12747872015-12-07 14:19:49 -08001746 if (!splitSystemUser && userData.info.isRestricted()
1747 && (userData.info.restrictedProfileParentId
1748 == UserInfo.NO_PROFILE_GROUP_ID)) {
1749 userData.info.restrictedProfileParentId = UserHandle.USER_SYSTEM;
1750 scheduleWriteUser(userData);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001751 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001752 }
1753 }
1754 userVersion = 6;
1755 }
1756
Amith Yamasani6f34b412012-10-22 18:19:27 -07001757 if (userVersion < USER_VERSION) {
1758 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
1759 + USER_VERSION);
1760 } else {
1761 mUserVersion = userVersion;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001762
1763 if (originalVersion < mUserVersion) {
1764 writeUserListLP();
1765 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001766 }
1767 }
1768
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001769 private void fallbackToSingleUserLP() {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001770 int flags = UserInfo.FLAG_INITIALIZED;
1771 // In split system user mode, the admin and primary flags are assigned to the first human
1772 // user.
1773 if (!UserManager.isSplitSystemUser()) {
1774 flags |= UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY;
1775 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001776 // Create the system user
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001777 UserInfo system = new UserInfo(UserHandle.USER_SYSTEM, null, null, flags);
Amith Yamasani12747872015-12-07 14:19:49 -08001778 UserData userData = new UserData();
1779 userData.info = system;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001780 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001781 mUsers.put(system.id, userData);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001782 }
Amith Yamasani634cf312012-10-04 17:34:21 -07001783 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -04001784 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -08001785
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001786 Bundle restrictions = new Bundle();
Makoto Onuki068c54a2015-10-13 14:34:03 -07001787 synchronized (mRestrictionsLock) {
1788 mBaseUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions);
1789 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001790
Fyodor Kupolov82402752015-10-28 14:54:51 -07001791 updateUserIds();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001792 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001793
Amith Yamasani12747872015-12-07 14:19:49 -08001794 writeUserLP(userData);
Jeff Sharkeycd575992016-03-29 14:12:49 -06001795 writeUserListLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001796 }
1797
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001798 private String getOwnerName() {
1799 return mContext.getResources().getString(com.android.internal.R.string.owner_name);
1800 }
1801
Amith Yamasani12747872015-12-07 14:19:49 -08001802 private void scheduleWriteUser(UserData UserData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001803 if (DBG) {
1804 debug("scheduleWriteUser");
1805 }
Makoto Onuki9e935a32015-11-06 14:24:24 -08001806 // No need to wrap it within a lock -- worst case, we'll just post the same message
1807 // twice.
Amith Yamasani12747872015-12-07 14:19:49 -08001808 if (!mHandler.hasMessages(WRITE_USER_MSG, UserData)) {
1809 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, UserData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001810 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
1811 }
1812 }
1813
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001814 /*
1815 * Writes the user file in this format:
1816 *
1817 * <user flags="20039023" id="0">
1818 * <name>Primary</name>
1819 * </user>
1820 */
Amith Yamasani12747872015-12-07 14:19:49 -08001821 private void writeUserLP(UserData userData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001822 if (DBG) {
Amith Yamasani12747872015-12-07 14:19:49 -08001823 debug("writeUserLP " + userData);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001824 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001825 FileOutputStream fos = null;
Amith Yamasani12747872015-12-07 14:19:49 -08001826 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userData.info.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001827 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001828 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001829 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1830
1831 // XmlSerializer serializer = XmlUtils.serializerInstance();
1832 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001833 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001834 serializer.startDocument(null, true);
1835 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1836
Amith Yamasani12747872015-12-07 14:19:49 -08001837 final UserInfo userInfo = userData.info;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001838 serializer.startTag(null, TAG_USER);
1839 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
Amith Yamasani2a003292012-08-14 18:25:45 -07001840 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001841 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Amith Yamasani920ace02012-09-20 22:15:37 -07001842 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
1843 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
1844 Long.toString(userInfo.lastLoggedInTime));
Jeff Sharkeycd575992016-03-29 14:12:49 -06001845 if (userInfo.lastLoggedInFingerprint != null) {
1846 serializer.attribute(null, ATTR_LAST_LOGGED_IN_FINGERPRINT,
1847 userInfo.lastLoggedInFingerprint);
1848 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001849 if (userInfo.iconPath != null) {
1850 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
1851 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001852 if (userInfo.partial) {
1853 serializer.attribute(null, ATTR_PARTIAL, "true");
1854 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001855 if (userInfo.guestToRemove) {
1856 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
1857 }
Kenny Guy2a764942014-04-02 13:29:20 +01001858 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
1859 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
1860 Integer.toString(userInfo.profileGroupId));
Kenny Guya52dc3e2014-02-11 15:33:14 +00001861 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001862 if (userInfo.restrictedProfileParentId != UserInfo.NO_PROFILE_GROUP_ID) {
1863 serializer.attribute(null, ATTR_RESTRICTED_PROFILE_PARENT_ID,
1864 Integer.toString(userInfo.restrictedProfileParentId));
1865 }
Amith Yamasani12747872015-12-07 14:19:49 -08001866 // Write seed data
1867 if (userData.persistSeedData) {
1868 if (userData.seedAccountName != null) {
1869 serializer.attribute(null, ATTR_SEED_ACCOUNT_NAME, userData.seedAccountName);
1870 }
1871 if (userData.seedAccountType != null) {
1872 serializer.attribute(null, ATTR_SEED_ACCOUNT_TYPE, userData.seedAccountType);
1873 }
1874 }
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001875 if (userInfo.name != null) {
1876 serializer.startTag(null, TAG_NAME);
1877 serializer.text(userInfo.name);
1878 serializer.endTag(null, TAG_NAME);
1879 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001880 synchronized (mRestrictionsLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001881 UserRestrictionsUtils.writeRestrictions(serializer,
1882 mBaseUserRestrictions.get(userInfo.id), TAG_RESTRICTIONS);
1883 UserRestrictionsUtils.writeRestrictions(serializer,
1884 mDevicePolicyLocalUserRestrictions.get(userInfo.id),
1885 TAG_DEVICE_POLICY_RESTRICTIONS);
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001886 }
Amith Yamasani12747872015-12-07 14:19:49 -08001887
1888 if (userData.account != null) {
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001889 serializer.startTag(null, TAG_ACCOUNT);
Amith Yamasani12747872015-12-07 14:19:49 -08001890 serializer.text(userData.account);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001891 serializer.endTag(null, TAG_ACCOUNT);
1892 }
1893
Amith Yamasani12747872015-12-07 14:19:49 -08001894 if (userData.persistSeedData && userData.seedAccountOptions != null) {
1895 serializer.startTag(null, TAG_SEED_ACCOUNT_OPTIONS);
1896 userData.seedAccountOptions.saveToXml(serializer);
1897 serializer.endTag(null, TAG_SEED_ACCOUNT_OPTIONS);
1898 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001899 serializer.endTag(null, TAG_USER);
1900
1901 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001902 userFile.finishWrite(fos);
1903 } catch (Exception ioe) {
Jeff Sharkeycd575992016-03-29 14:12:49 -06001904 Slog.e(LOG_TAG, "Error writing user info " + userData.info.id, ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -07001905 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001906 }
1907 }
1908
1909 /*
1910 * Writes the user list file in this format:
1911 *
Amith Yamasani2a003292012-08-14 18:25:45 -07001912 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001913 * <user id="0"></user>
1914 * <user id="2"></user>
1915 * </users>
1916 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001917 private void writeUserListLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001918 if (DBG) {
1919 debug("writeUserList");
1920 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001921 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001922 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001923 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001924 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001925 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1926
1927 // XmlSerializer serializer = XmlUtils.serializerInstance();
1928 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001929 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001930 serializer.startDocument(null, true);
1931 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1932
1933 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -07001934 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -07001935 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001936
Adam Lesinskieddeb492014-09-08 17:50:03 -07001937 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001938 synchronized (mGuestRestrictions) {
1939 UserRestrictionsUtils
1940 .writeRestrictions(serializer, mGuestRestrictions, TAG_RESTRICTIONS);
1941 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301942 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001943 synchronized (mRestrictionsLock) {
1944 UserRestrictionsUtils.writeRestrictions(serializer,
1945 mDevicePolicyGlobalUserRestrictions, TAG_DEVICE_POLICY_RESTRICTIONS);
1946 }
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001947 serializer.startTag(null, TAG_GLOBAL_RESTRICTION_OWNER_ID);
1948 serializer.attribute(null, ATTR_ID, Integer.toString(mGlobalRestrictionOwnerUserId));
1949 serializer.endTag(null, TAG_GLOBAL_RESTRICTION_OWNER_ID);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001950 int[] userIdsToWrite;
1951 synchronized (mUsersLock) {
1952 userIdsToWrite = new int[mUsers.size()];
1953 for (int i = 0; i < userIdsToWrite.length; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001954 UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001955 userIdsToWrite[i] = user.id;
1956 }
1957 }
1958 for (int id : userIdsToWrite) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001959 serializer.startTag(null, TAG_USER);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001960 serializer.attribute(null, ATTR_ID, Integer.toString(id));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001961 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001962 }
1963
1964 serializer.endTag(null, TAG_USERS);
1965
1966 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001967 userListFile.finishWrite(fos);
1968 } catch (Exception e) {
1969 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -07001970 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001971 }
1972 }
1973
Amith Yamasani12747872015-12-07 14:19:49 -08001974 private UserData readUserLP(int id) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001975 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -07001976 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001977 String name = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001978 String account = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001979 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -07001980 long creationTime = 0L;
1981 long lastLoggedInTime = 0L;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06001982 String lastLoggedInFingerprint = null;
Kenny Guy2a764942014-04-02 13:29:20 +01001983 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001984 int restrictedProfileParentId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001985 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001986 boolean guestToRemove = false;
Amith Yamasani12747872015-12-07 14:19:49 -08001987 boolean persistSeedData = false;
1988 String seedAccountName = null;
1989 String seedAccountType = null;
1990 PersistableBundle seedAccountOptions = null;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001991 Bundle baseRestrictions = new Bundle();
1992 Bundle localRestrictions = new Bundle();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001993
1994 FileInputStream fis = null;
1995 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001996 AtomicFile userFile =
Amith Yamasanifc95e702013-09-26 13:20:17 -07001997 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
Amith Yamasani2a003292012-08-14 18:25:45 -07001998 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001999 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002000 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002001 int type;
2002 while ((type = parser.next()) != XmlPullParser.START_TAG
2003 && type != XmlPullParser.END_DOCUMENT) {
Amith Yamasani12747872015-12-07 14:19:49 -08002004 // Skip
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002005 }
2006
2007 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07002008 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002009 return null;
2010 }
2011
2012 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -07002013 int storedId = readIntAttribute(parser, ATTR_ID, -1);
2014 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -07002015 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002016 return null;
2017 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002018 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
2019 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002020 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -07002021 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
2022 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002023 lastLoggedInFingerprint = parser.getAttributeValue(null,
2024 ATTR_LAST_LOGGED_IN_FINGERPRINT);
Kenny Guy2a764942014-04-02 13:29:20 +01002025 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
2026 UserInfo.NO_PROFILE_GROUP_ID);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002027 restrictedProfileParentId = readIntAttribute(parser,
2028 ATTR_RESTRICTED_PROFILE_PARENT_ID, UserInfo.NO_PROFILE_GROUP_ID);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002029 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
2030 if ("true".equals(valueString)) {
2031 partial = true;
2032 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002033 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
2034 if ("true".equals(valueString)) {
2035 guestToRemove = true;
2036 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002037
Amith Yamasani12747872015-12-07 14:19:49 -08002038 seedAccountName = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_NAME);
2039 seedAccountType = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_TYPE);
2040 if (seedAccountName != null || seedAccountType != null) {
2041 persistSeedData = true;
2042 }
2043
Amith Yamasanie4cf7342012-12-17 11:12:09 -08002044 int outerDepth = parser.getDepth();
2045 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2046 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2047 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2048 continue;
2049 }
2050 String tag = parser.getName();
2051 if (TAG_NAME.equals(tag)) {
2052 type = parser.next();
2053 if (type == XmlPullParser.TEXT) {
2054 name = parser.getText();
2055 }
2056 } else if (TAG_RESTRICTIONS.equals(tag)) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002057 UserRestrictionsUtils.readRestrictions(parser, baseRestrictions);
2058 } else if (TAG_DEVICE_POLICY_RESTRICTIONS.equals(tag)) {
2059 UserRestrictionsUtils.readRestrictions(parser, localRestrictions);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08002060 } else if (TAG_ACCOUNT.equals(tag)) {
2061 type = parser.next();
2062 if (type == XmlPullParser.TEXT) {
2063 account = parser.getText();
2064 }
Amith Yamasani12747872015-12-07 14:19:49 -08002065 } else if (TAG_SEED_ACCOUNT_OPTIONS.equals(tag)) {
2066 seedAccountOptions = PersistableBundle.restoreFromXml(parser);
2067 persistSeedData = true;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002068 }
2069 }
2070 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002071
Amith Yamasani12747872015-12-07 14:19:49 -08002072 // Create the UserInfo object that gets passed around
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002073 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -07002074 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -07002075 userInfo.creationTime = creationTime;
2076 userInfo.lastLoggedInTime = lastLoggedInTime;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002077 userInfo.lastLoggedInFingerprint = lastLoggedInFingerprint;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002078 userInfo.partial = partial;
Adam Lesinskieddeb492014-09-08 17:50:03 -07002079 userInfo.guestToRemove = guestToRemove;
Kenny Guy2a764942014-04-02 13:29:20 +01002080 userInfo.profileGroupId = profileGroupId;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002081 userInfo.restrictedProfileParentId = restrictedProfileParentId;
Amith Yamasani12747872015-12-07 14:19:49 -08002082
2083 // Create the UserData object that's internal to this class
2084 UserData userData = new UserData();
2085 userData.info = userInfo;
2086 userData.account = account;
2087 userData.seedAccountName = seedAccountName;
2088 userData.seedAccountType = seedAccountType;
2089 userData.persistSeedData = persistSeedData;
2090 userData.seedAccountOptions = seedAccountOptions;
2091
Makoto Onuki068c54a2015-10-13 14:34:03 -07002092 synchronized (mRestrictionsLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002093 mBaseUserRestrictions.put(id, baseRestrictions);
2094 mDevicePolicyLocalUserRestrictions.put(id, localRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002095 }
Amith Yamasani12747872015-12-07 14:19:49 -08002096 return userData;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002097 } catch (IOException ioe) {
2098 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08002099 } finally {
2100 if (fis != null) {
2101 try {
2102 fis.close();
2103 } catch (IOException e) {
2104 }
2105 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002106 }
2107 return null;
2108 }
2109
Amith Yamasani920ace02012-09-20 22:15:37 -07002110 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
2111 String valueString = parser.getAttributeValue(null, attr);
2112 if (valueString == null) return defaultValue;
2113 try {
2114 return Integer.parseInt(valueString);
2115 } catch (NumberFormatException nfe) {
2116 return defaultValue;
2117 }
2118 }
2119
2120 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
2121 String valueString = parser.getAttributeValue(null, attr);
2122 if (valueString == null) return defaultValue;
2123 try {
2124 return Long.parseLong(valueString);
2125 } catch (NumberFormatException nfe) {
2126 return defaultValue;
2127 }
2128 }
2129
Amith Yamasanib82add22013-07-09 11:24:44 -07002130 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002131 * Removes the app restrictions file for a specific package and user id, if it exists.
2132 */
2133 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
2134 synchronized (mPackagesLock) {
2135 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07002136 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002137 if (resFile.exists()) {
2138 resFile.delete();
2139 }
2140 }
2141 }
2142
Kenny Guya52dc3e2014-02-11 15:33:14 +00002143 @Override
Kenny Guy2a764942014-04-02 13:29:20 +01002144 public UserInfo createProfileForUser(String name, int flags, int userId) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002145 checkManageOrCreateUsersPermission(flags);
Kenny Guy2a764942014-04-02 13:29:20 +01002146 return createUserInternal(name, flags, userId);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002147 }
2148
Amith Yamasani258848d2012-08-10 17:06:33 -07002149 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07002150 public UserInfo createUser(String name, int flags) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002151 checkManageOrCreateUsersPermission(flags);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00002152 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002153 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07002154
Jessica Hummelbe81c802014-04-22 15:49:22 +01002155 private UserInfo createUserInternal(String name, int flags, int parentId) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002156 if (hasUserRestriction(UserManager.DISALLOW_ADD_USER, UserHandle.getCallingUserId())) {
Julia Reynolds75175022014-06-26 16:35:00 -04002157 Log.w(LOG_TAG, "Cannot add user. DISALLOW_ADD_USER is enabled.");
2158 return null;
2159 }
phweisse9c44062016-02-10 12:57:38 +01002160 return createUserInternalUnchecked(name, flags, parentId);
2161 }
2162
2163 private UserInfo createUserInternalUnchecked(String name, int flags, int parentId) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07002164 if (ActivityManager.isLowRamDeviceStatic()) {
2165 return null;
2166 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07002167 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Nicolas Prevot12678a92015-05-13 12:15:03 -07002168 final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002169 final boolean isRestricted = (flags & UserInfo.FLAG_RESTRICTED) != 0;
Amith Yamasani52c21e32016-05-31 09:12:20 -07002170 final boolean isDemo = (flags & UserInfo.FLAG_DEMO) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002171 final long ident = Binder.clearCallingIdentity();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002172 UserInfo userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08002173 UserData userData;
Amith Yamasanibb054c92015-07-09 14:16:27 -07002174 final int userId;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002175 try {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002176 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002177 UserData parent = null;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002178 if (parentId != UserHandle.USER_NULL) {
2179 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002180 parent = getUserDataLU(parentId);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00002181 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002182 if (parent == null) return null;
2183 }
2184 if (isManagedProfile && !canAddMoreManagedProfiles(parentId, false)) {
2185 Log.e(LOG_TAG, "Cannot add more managed profiles for user " + parentId);
2186 return null;
2187 }
Amith Yamasani52c21e32016-05-31 09:12:20 -07002188 if (!isGuest && !isManagedProfile && !isDemo && isUserLimitReached()) {
2189 // If we're not adding a guest/demo user or a managed profile and the limit has
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002190 // been reached, cannot add a user.
2191 return null;
2192 }
2193 // If we're adding a guest and there already exists one, bail.
2194 if (isGuest && findCurrentGuestUser() != null) {
2195 return null;
2196 }
2197 // In legacy mode, restricted profile's parent can only be the owner user
2198 if (isRestricted && !UserManager.isSplitSystemUser()
2199 && (parentId != UserHandle.USER_SYSTEM)) {
2200 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
2201 return null;
2202 }
2203 if (isRestricted && UserManager.isSplitSystemUser()) {
2204 if (parent == null) {
2205 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be "
2206 + "specified");
Nicolas Prevot12678a92015-05-13 12:15:03 -07002207 return null;
2208 }
Amith Yamasani12747872015-12-07 14:19:49 -08002209 if (!parent.info.canHaveProfile()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002210 Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be "
2211 + "created for the specified parent user id " + parentId);
Amith Yamasani95ab7842014-08-11 17:09:26 -07002212 return null;
2213 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002214 }
Suprabh Shuklacc30b0e72016-05-20 14:41:22 -07002215 if (!UserManager.isSplitSystemUser() && (flags & UserInfo.FLAG_EPHEMERAL) != 0
2216 && (flags & UserInfo.FLAG_DEMO) == 0) {
Lenka Trochtova024f9792016-02-17 13:55:17 +01002217 Log.e(LOG_TAG,
2218 "Ephemeral users are supported on split-system-user systems only.");
2219 return null;
2220 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002221 // In split system user mode, we assign the first human user the primary flag.
2222 // And if there is no device owner, we also assign the admin flag to primary user.
2223 if (UserManager.isSplitSystemUser()
2224 && !isGuest && !isManagedProfile && getPrimaryUser() == null) {
2225 flags |= UserInfo.FLAG_PRIMARY;
Makoto Onukie7927da2015-11-25 10:05:17 -08002226 synchronized (mUsersLock) {
2227 if (!mIsDeviceManaged) {
2228 flags |= UserInfo.FLAG_ADMIN;
2229 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07002230 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002231 }
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002232
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002233 userId = getNextAvailableId();
2234 Environment.getUserSystemDirectory(userId).mkdirs();
Lenka Trochtova02fee152015-12-22 14:26:18 +01002235 boolean ephemeralGuests = Resources.getSystem()
2236 .getBoolean(com.android.internal.R.bool.config_guestUserEphemeral);
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002237
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002238 synchronized (mUsersLock) {
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002239 // Add ephemeral flag to guests/users if required. Also inherit it from parent.
2240 if ((isGuest && ephemeralGuests) || mForceEphemeralUsers
2241 || (parent != null && parent.info.isEphemeral())) {
2242 flags |= UserInfo.FLAG_EPHEMERAL;
2243 }
2244
2245 userInfo = new UserInfo(userId, name, null, flags);
2246 userInfo.serialNumber = mNextSerialNumber++;
2247 long now = System.currentTimeMillis();
2248 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
2249 userInfo.partial = true;
Fyodor Kupolov83c24242016-03-31 13:30:42 -07002250 userInfo.lastLoggedInFingerprint = Build.FINGERPRINT;
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002251 userData = new UserData();
2252 userData.info = userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08002253 mUsers.put(userId, userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002254 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06002255 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002256 writeUserListLP();
2257 if (parent != null) {
2258 if (isManagedProfile) {
Amith Yamasani12747872015-12-07 14:19:49 -08002259 if (parent.info.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
2260 parent.info.profileGroupId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002261 writeUserLP(parent);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002262 }
Amith Yamasani12747872015-12-07 14:19:49 -08002263 userInfo.profileGroupId = parent.info.profileGroupId;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002264 } else if (isRestricted) {
Amith Yamasani12747872015-12-07 14:19:49 -08002265 if (parent.info.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) {
2266 parent.info.restrictedProfileParentId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002267 writeUserLP(parent);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002268 }
Amith Yamasani12747872015-12-07 14:19:49 -08002269 userInfo.restrictedProfileParentId = parent.info.restrictedProfileParentId;
Makoto Onuki068c54a2015-10-13 14:34:03 -07002270 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002271 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07002272 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002273 final StorageManager storage = mContext.getSystemService(StorageManager.class);
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002274 storage.createUserKey(userId, userInfo.serialNumber, userInfo.isEphemeral());
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002275 mPm.prepareUserData(userId, userInfo.serialNumber,
Jeff Sharkey47f71082016-02-01 17:03:54 -07002276 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002277 mPm.createNewUser(userId);
2278 userInfo.partial = false;
2279 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002280 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002281 }
2282 updateUserIds();
2283 Bundle restrictions = new Bundle();
Fyodor Kupolove04462c2015-11-30 15:02:53 -08002284 if (isGuest) {
2285 synchronized (mGuestRestrictions) {
2286 restrictions.putAll(mGuestRestrictions);
2287 }
2288 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002289 synchronized (mRestrictionsLock) {
2290 mBaseUserRestrictions.append(userId, restrictions);
2291 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002292 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
2293 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
2294 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
2295 android.Manifest.permission.MANAGE_USERS);
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -08002296 MetricsLogger.count(mContext, isGuest ? TRON_GUEST_CREATED : TRON_USER_CREATED, 1);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002297 } finally {
2298 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07002299 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002300 return userInfo;
2301 }
2302
Amith Yamasani0b285492011-04-14 17:35:23 -07002303 /**
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002304 * @hide
2305 */
Amith Yamasani12747872015-12-07 14:19:49 -08002306 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002307 public UserInfo createRestrictedProfile(String name, int parentUserId) {
Sudheer Shanka53d41472016-06-16 09:11:08 -07002308 checkManageOrCreateUsersPermission("setupRestrictedProfile");
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002309 final UserInfo user = createProfileForUser(name, UserInfo.FLAG_RESTRICTED, parentUserId);
2310 if (user == null) {
2311 return null;
2312 }
Fyodor Kupolov9e912ba2016-02-09 18:29:43 -08002313 long identity = Binder.clearCallingIdentity();
2314 try {
2315 setUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, true, user.id);
2316 // Change the setting before applying the DISALLOW_SHARE_LOCATION restriction, otherwise
2317 // the putIntForUser() will fail.
2318 android.provider.Settings.Secure.putIntForUser(mContext.getContentResolver(),
2319 android.provider.Settings.Secure.LOCATION_MODE,
2320 android.provider.Settings.Secure.LOCATION_MODE_OFF, user.id);
2321 setUserRestriction(UserManager.DISALLOW_SHARE_LOCATION, true, user.id);
2322 } finally {
2323 Binder.restoreCallingIdentity(identity);
2324 }
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002325 return user;
2326 }
2327
2328 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07002329 * Find the current guest user. If the Guest user is partial,
2330 * then do not include it in the results as it is about to die.
Adam Lesinskieddeb492014-09-08 17:50:03 -07002331 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002332 private UserInfo findCurrentGuestUser() {
2333 synchronized (mUsersLock) {
2334 final int size = mUsers.size();
2335 for (int i = 0; i < size; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002336 final UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002337 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
2338 return user;
2339 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002340 }
2341 }
2342 return null;
2343 }
2344
2345 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07002346 * Mark this guest user for deletion to allow us to create another guest
2347 * and switch to that user before actually removing this guest.
2348 * @param userHandle the userid of the current guest
2349 * @return whether the user could be marked for deletion
2350 */
Amith Yamasani12747872015-12-07 14:19:49 -08002351 @Override
Amith Yamasani1df14732014-08-29 21:37:27 -07002352 public boolean markGuestForDeletion(int userHandle) {
2353 checkManageUsersPermission("Only the system can remove users");
2354 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
2355 UserManager.DISALLOW_REMOVE_USER, false)) {
2356 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
2357 return false;
2358 }
2359
2360 long ident = Binder.clearCallingIdentity();
2361 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002362 final UserData userData;
Amith Yamasani1df14732014-08-29 21:37:27 -07002363 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002364 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002365 userData = mUsers.get(userHandle);
2366 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002367 return false;
2368 }
Amith Yamasani1df14732014-08-29 21:37:27 -07002369 }
Amith Yamasani12747872015-12-07 14:19:49 -08002370 if (!userData.info.isGuest()) {
Amith Yamasani1df14732014-08-29 21:37:27 -07002371 return false;
2372 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002373 // We set this to a guest user that is to be removed. This is a temporary state
2374 // where we are allowed to add new Guest users, even if this one is still not
2375 // removed. This user will still show up in getUserInfo() calls.
2376 // If we don't get around to removing this Guest user, it will be purged on next
2377 // startup.
Amith Yamasani12747872015-12-07 14:19:49 -08002378 userData.info.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07002379 // Mark it as disabled, so that it isn't returned any more when
2380 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002381 userData.info.flags |= UserInfo.FLAG_DISABLED;
2382 writeUserLP(userData);
Amith Yamasani1df14732014-08-29 21:37:27 -07002383 }
2384 } finally {
2385 Binder.restoreCallingIdentity(ident);
2386 }
2387 return true;
2388 }
2389
2390 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002391 * Removes a user and all data directories created for that user. This method should be called
2392 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07002393 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07002394 */
Amith Yamasani12747872015-12-07 14:19:49 -08002395 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -07002396 public boolean removeUser(int userHandle) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002397 checkManageOrCreateUsersPermission("Only the system can remove users");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04002398 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
2399 UserManager.DISALLOW_REMOVE_USER, false)) {
2400 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
2401 return false;
2402 }
2403
Kenny Guyee58b4f2014-05-23 15:19:53 +01002404 long ident = Binder.clearCallingIdentity();
2405 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002406 final UserData userData;
Fyodor Kupolov0df68cd2015-10-01 13:54:22 -07002407 int currentUser = ActivityManager.getCurrentUser();
2408 if (currentUser == userHandle) {
2409 Log.w(LOG_TAG, "Current user cannot be removed");
2410 return false;
2411 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002412 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002413 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002414 userData = mUsers.get(userHandle);
2415 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002416 return false;
2417 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002418
Fyodor Kupolov82402752015-10-28 14:54:51 -07002419 // We remember deleted user IDs to prevent them from being
2420 // reused during the current boot; they can still be reused
2421 // after a reboot.
2422 mRemovingUserIds.put(userHandle, true);
2423 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002424
Kenny Guyee58b4f2014-05-23 15:19:53 +01002425 try {
2426 mAppOpsService.removeUser(userHandle);
2427 } catch (RemoteException e) {
2428 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
2429 }
2430 // Set this to a partially created user, so that the user will be purged
2431 // on next startup, in case the runtime stops now before stopping and
2432 // removing the user completely.
Amith Yamasani12747872015-12-07 14:19:49 -08002433 userData.info.partial = true;
Kenny Guyee58b4f2014-05-23 15:19:53 +01002434 // Mark it as disabled, so that it isn't returned any more when
2435 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002436 userData.info.flags |= UserInfo.FLAG_DISABLED;
2437 writeUserLP(userData);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002438 }
2439
Amith Yamasani12747872015-12-07 14:19:49 -08002440 if (userData.info.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
2441 && userData.info.isManagedProfile()) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002442 // Send broadcast to notify system that the user removed was a
2443 // managed user.
Amith Yamasani12747872015-12-07 14:19:49 -08002444 sendProfileRemovedBroadcast(userData.info.profileGroupId, userData.info.id);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002445 }
2446
2447 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
2448 int res;
2449 try {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07002450 res = ActivityManagerNative.getDefault().stopUser(userHandle, /* force= */ true,
2451 new IStopUserCallback.Stub() {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002452 @Override
2453 public void userStopped(int userId) {
2454 finishRemoveUser(userId);
2455 }
2456 @Override
2457 public void userStopAborted(int userId) {
2458 }
2459 });
2460 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002461 return false;
2462 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002463 return res == ActivityManager.USER_OP_SUCCESS;
2464 } finally {
2465 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002466 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002467 }
2468
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002469 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07002470 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002471 // Let other services shutdown any activity and clean up their state before completely
2472 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002473 long ident = Binder.clearCallingIdentity();
2474 try {
2475 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
2476 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002477 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
2478 android.Manifest.permission.MANAGE_USERS,
2479
2480 new BroadcastReceiver() {
2481 @Override
2482 public void onReceive(Context context, Intent intent) {
2483 if (DBG) {
2484 Slog.i(LOG_TAG,
2485 "USER_REMOVED broadcast sent, cleaning up user data "
2486 + userHandle);
2487 }
2488 new Thread() {
Amith Yamasani12747872015-12-07 14:19:49 -08002489 @Override
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002490 public void run() {
Amith Yamasani515d4062015-09-28 11:30:06 -07002491 // Clean up any ActivityManager state
2492 LocalServices.getService(ActivityManagerInternal.class)
2493 .onUserRemoved(userHandle);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002494 removeUserState(userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002495 }
2496 }.start();
2497 }
2498 },
2499
2500 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002501 } finally {
2502 Binder.restoreCallingIdentity(ident);
2503 }
Amith Yamasani2a003292012-08-14 18:25:45 -07002504 }
2505
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002506 private void removeUserState(final int userHandle) {
Paul Crowley91293792016-03-25 15:23:07 -07002507 try {
2508 mContext.getSystemService(StorageManager.class).destroyUserKey(userHandle);
2509 } catch (IllegalStateException e) {
2510 // This may be simply because the user was partially created.
2511 Slog.i(LOG_TAG,
2512 "Destroying key for user " + userHandle + " failed, continuing anyway", e);
2513 }
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002514
Amith Yamasanid04aaa32016-06-13 12:09:36 -07002515 // Cleanup gatekeeper secure user id
2516 try {
2517 final IGateKeeperService gk = GateKeeper.getService();
2518 if (gk != null) {
2519 gk.clearSecureUserId(userHandle);
2520 }
2521 } catch (Exception ex) {
2522 Slog.w(LOG_TAG, "unable to clear GK secure user id");
2523 }
2524
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002525 // Cleanup package manager settings
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002526 mPm.cleanUpUser(this, userHandle);
Amith Yamasanid04aaa32016-06-13 12:09:36 -07002527
2528 // Clean up all data before removing metadata
2529 mPm.destroyUserData(userHandle,
2530 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2531
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002532 // Remove this user from the list
Fyodor Kupolov82402752015-10-28 14:54:51 -07002533 synchronized (mUsersLock) {
2534 mUsers.remove(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08002535 mIsUserManaged.delete(userHandle);
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00002536 }
2537 synchronized (mUserStates) {
2538 mUserStates.delete(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08002539 }
2540 synchronized (mRestrictionsLock) {
2541 mBaseUserRestrictions.remove(userHandle);
2542 mAppliedUserRestrictions.remove(userHandle);
2543 mCachedEffectiveUserRestrictions.remove(userHandle);
2544 mDevicePolicyLocalUserRestrictions.remove(userHandle);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002545 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002546 // Update the user list
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002547 synchronized (mPackagesLock) {
2548 writeUserListLP();
2549 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06002550 // Remove user file
2551 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
2552 userFile.delete();
Fyodor Kupolov82402752015-10-28 14:54:51 -07002553 updateUserIds();
Amith Yamasani61f57372012-08-31 12:12:28 -07002554 }
2555
Kenny Guyf8d3a232014-05-15 16:09:52 +01002556 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01002557 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01002558 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
2559 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002560 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
Jeff Sharkeyaf6ec292015-12-17 11:19:00 -07002561 managedProfileIntent.putExtra(Intent.EXTRA_USER_HANDLE, removedUserId);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002562 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01002563 }
2564
Amith Yamasani2a003292012-08-14 18:25:45 -07002565 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002566 public Bundle getApplicationRestrictions(String packageName) {
2567 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
2568 }
2569
2570 @Override
2571 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002572 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07002573 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00002574 checkSystemOrRoot("get application restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002575 }
2576 synchronized (mPackagesLock) {
2577 // Read the restrictions from XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07002578 return readApplicationRestrictionsLP(packageName, userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002579 }
2580 }
2581
2582 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002583 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002584 int userId) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00002585 checkSystemOrRoot("set application restrictions");
Fyodor Kupolov0d88d542016-04-19 11:37:22 -07002586 if (restrictions != null) {
2587 restrictions.setDefusable(true);
2588 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002589 synchronized (mPackagesLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01002590 if (restrictions == null || restrictions.isEmpty()) {
2591 cleanAppRestrictionsForPackage(packageName, userId);
2592 } else {
2593 // Write the restrictions to XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07002594 writeApplicationRestrictionsLP(packageName, restrictions, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01002595 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002596 }
Robin Lee66e5d962014-04-09 16:44:21 +01002597
Fyodor Kupolovd2846122016-02-11 18:06:34 -08002598 // Notify package of changes via an intent - only sent to explicitly registered receivers.
2599 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
2600 changeIntent.setPackage(packageName);
2601 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
2602 mContext.sendBroadcastAsUser(changeIntent, UserHandle.of(userId));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002603 }
2604
2605 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07002606 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002607 try {
2608 return mContext.getPackageManager().getApplicationInfo(packageName,
Fyodor Kupolovd2846122016-02-11 18:06:34 -08002609 PackageManager.MATCH_UNINSTALLED_PACKAGES).uid;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002610 } catch (NameNotFoundException nnfe) {
2611 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07002612 } finally {
2613 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002614 }
2615 }
2616
Fyodor Kupolov82402752015-10-28 14:54:51 -07002617 private Bundle readApplicationRestrictionsLP(String packageName, int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002618 AtomicFile restrictionsFile =
2619 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
2620 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002621 return readApplicationRestrictionsLP(restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002622 }
2623
2624 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002625 static Bundle readApplicationRestrictionsLP(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002626 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002627 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002628 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07002629 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002630 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002631
2632 FileInputStream fis = null;
2633 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002634 fis = restrictionsFile.openRead();
2635 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002636 parser.setInput(fis, StandardCharsets.UTF_8.name());
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002637 XmlUtils.nextElement(parser);
2638 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002639 Slog.e(LOG_TAG, "Unable to read restrictions file "
2640 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002641 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002642 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002643 while (parser.next() != XmlPullParser.END_DOCUMENT) {
2644 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002645 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002646 } catch (IOException|XmlPullParserException e) {
2647 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002648 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002649 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002650 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002651 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002652 }
2653
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002654 private static void readEntry(Bundle restrictions, ArrayList<String> values,
2655 XmlPullParser parser) throws XmlPullParserException, IOException {
2656 int type = parser.getEventType();
2657 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
2658 String key = parser.getAttributeValue(null, ATTR_KEY);
2659 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
2660 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
2661 if (multiple != null) {
2662 values.clear();
2663 int count = Integer.parseInt(multiple);
2664 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
2665 if (type == XmlPullParser.START_TAG
2666 && parser.getName().equals(TAG_VALUE)) {
2667 values.add(parser.nextText().trim());
2668 count--;
2669 }
2670 }
2671 String [] valueStrings = new String[values.size()];
2672 values.toArray(valueStrings);
2673 restrictions.putStringArray(key, valueStrings);
2674 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
2675 restrictions.putBundle(key, readBundleEntry(parser, values));
2676 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
2677 final int outerDepth = parser.getDepth();
2678 ArrayList<Bundle> bundleList = new ArrayList<>();
2679 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2680 Bundle childBundle = readBundleEntry(parser, values);
2681 bundleList.add(childBundle);
2682 }
2683 restrictions.putParcelableArray(key,
2684 bundleList.toArray(new Bundle[bundleList.size()]));
2685 } else {
2686 String value = parser.nextText().trim();
2687 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
2688 restrictions.putBoolean(key, Boolean.parseBoolean(value));
2689 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
2690 restrictions.putInt(key, Integer.parseInt(value));
2691 } else {
2692 restrictions.putString(key, value);
2693 }
2694 }
2695 }
2696 }
2697
2698 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
2699 throws IOException, XmlPullParserException {
2700 Bundle childBundle = new Bundle();
2701 final int outerDepth = parser.getDepth();
2702 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2703 readEntry(childBundle, values, parser);
2704 }
2705 return childBundle;
2706 }
2707
Fyodor Kupolov82402752015-10-28 14:54:51 -07002708 private void writeApplicationRestrictionsLP(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002709 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002710 AtomicFile restrictionsFile = new AtomicFile(
2711 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07002712 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002713 writeApplicationRestrictionsLP(restrictions, restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002714 }
2715
2716 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002717 static void writeApplicationRestrictionsLP(Bundle restrictions, AtomicFile restrictionsFile) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002718 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002719 try {
2720 fos = restrictionsFile.startWrite();
2721 final BufferedOutputStream bos = new BufferedOutputStream(fos);
2722
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002723 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002724 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002725 serializer.startDocument(null, true);
2726 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2727
2728 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002729 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002730 serializer.endTag(null, TAG_RESTRICTIONS);
2731
2732 serializer.endDocument();
2733 restrictionsFile.finishWrite(fos);
2734 } catch (Exception e) {
2735 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002736 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
2737 }
2738 }
2739
2740 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
2741 throws IOException {
2742 for (String key : restrictions.keySet()) {
2743 Object value = restrictions.get(key);
2744 serializer.startTag(null, TAG_ENTRY);
2745 serializer.attribute(null, ATTR_KEY, key);
2746
2747 if (value instanceof Boolean) {
2748 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
2749 serializer.text(value.toString());
2750 } else if (value instanceof Integer) {
2751 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
2752 serializer.text(value.toString());
2753 } else if (value == null || value instanceof String) {
2754 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
2755 serializer.text(value != null ? (String) value : "");
2756 } else if (value instanceof Bundle) {
2757 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2758 writeBundle((Bundle) value, serializer);
2759 } else if (value instanceof Parcelable[]) {
2760 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
2761 Parcelable[] array = (Parcelable[]) value;
2762 for (Parcelable parcelable : array) {
2763 if (!(parcelable instanceof Bundle)) {
2764 throw new IllegalArgumentException("bundle-array can only hold Bundles");
2765 }
2766 serializer.startTag(null, TAG_ENTRY);
2767 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2768 writeBundle((Bundle) parcelable, serializer);
2769 serializer.endTag(null, TAG_ENTRY);
2770 }
2771 } else {
2772 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
2773 String[] values = (String[]) value;
2774 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
2775 for (String choice : values) {
2776 serializer.startTag(null, TAG_VALUE);
2777 serializer.text(choice != null ? choice : "");
2778 serializer.endTag(null, TAG_VALUE);
2779 }
2780 }
2781 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002782 }
2783 }
2784
2785 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07002786 public int getUserSerialNumber(int userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002787 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002788 if (!exists(userHandle)) return -1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002789 return getUserInfoLU(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07002790 }
2791 }
2792
2793 @Override
2794 public int getUserHandle(int userSerialNumber) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002795 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002796 for (int userId : mUserIds) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002797 UserInfo info = getUserInfoLU(userId);
Kenny Guy945f8832015-02-10 15:17:26 +00002798 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07002799 }
2800 // Not found
2801 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07002802 }
2803 }
2804
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002805 @Override
2806 public long getUserCreationTime(int userHandle) {
2807 int callingUserId = UserHandle.getCallingUserId();
2808 UserInfo userInfo = null;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002809 synchronized (mUsersLock) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002810 if (callingUserId == userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002811 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002812 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002813 UserInfo parent = getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002814 if (parent != null && parent.id == callingUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002815 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002816 }
2817 }
2818 }
2819 if (userInfo == null) {
2820 throw new SecurityException("userHandle can only be the calling user or a managed "
2821 + "profile associated with this user");
2822 }
2823 return userInfo.creationTime;
2824 }
2825
Amith Yamasani0b285492011-04-14 17:35:23 -07002826 /**
2827 * Caches the list of user ids in an array, adjusting the array size when necessary.
2828 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002829 private void updateUserIds() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002830 int num = 0;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002831 synchronized (mUsersLock) {
2832 final int userSize = mUsers.size();
2833 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002834 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002835 num++;
2836 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002837 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002838 final int[] newUsers = new int[num];
2839 int n = 0;
2840 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002841 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002842 newUsers[n++] = mUsers.keyAt(i);
2843 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002844 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002845 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07002846 }
2847 }
2848
2849 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002850 * Called right before a user is started. This gives us a chance to prepare
2851 * app storage and apply any user restrictions.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002852 */
2853 public void onBeforeStartUser(int userId) {
Jeff Sharkey47f71082016-02-01 17:03:54 -07002854 final int userSerial = getUserSerialNumber(userId);
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002855 mPm.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_DE);
Jeff Sharkey47f71082016-02-01 17:03:54 -07002856 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_DE);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002857
2858 if (userId != UserHandle.USER_SYSTEM) {
2859 synchronized (mRestrictionsLock) {
2860 applyUserRestrictionsLR(userId);
2861 }
Fyodor Kupolovb45d9832016-05-16 13:25:34 -07002862 UserInfo userInfo = getUserInfoNoChecks(userId);
2863 if (userInfo != null && !userInfo.isInitialized()) {
2864 mPm.onBeforeUserStartUninitialized(userId);
2865 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002866 }
Amith Yamasanieb437d42016-04-29 09:31:25 -07002867
2868 maybeInitializeDemoMode(userId);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002869 }
2870
2871 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002872 * Called right before a user is unlocked. This gives us a chance to prepare
2873 * app storage.
2874 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002875 public void onBeforeUnlockUser(@UserIdInt int userId) {
Jeff Sharkey47f71082016-02-01 17:03:54 -07002876 final int userSerial = getUserSerialNumber(userId);
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002877 mPm.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_CE);
Jeff Sharkey47f71082016-02-01 17:03:54 -07002878 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_CE);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002879 }
2880
2881 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002882 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasanieb437d42016-04-29 09:31:25 -07002883 * This is called with ActivityManagerService lock held.
Amith Yamasani920ace02012-09-20 22:15:37 -07002884 * @param userId the user that was just foregrounded
2885 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002886 public void onUserLoggedIn(@UserIdInt int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -08002887 UserData userData = getUserDataNoChecks(userId);
2888 if (userData == null || userData.info.partial) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002889 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
2890 return;
2891 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002892
2893 final long now = System.currentTimeMillis();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002894 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani12747872015-12-07 14:19:49 -08002895 userData.info.lastLoggedInTime = now;
Amith Yamasani920ace02012-09-20 22:15:37 -07002896 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002897 userData.info.lastLoggedInFingerprint = Build.FINGERPRINT;
2898 scheduleWriteUser(userData);
Amith Yamasani920ace02012-09-20 22:15:37 -07002899 }
2900
Amith Yamasanieb437d42016-04-29 09:31:25 -07002901 private void maybeInitializeDemoMode(int userId) {
2902 if (UserManager.isDeviceInDemoMode(mContext)) {
2903 String demoLauncher =
2904 mContext.getResources().getString(
2905 com.android.internal.R.string.config_demoModeLauncherComponent);
2906 if (!TextUtils.isEmpty(demoLauncher)) {
2907 ComponentName componentToEnable = ComponentName.unflattenFromString(demoLauncher);
2908 try {
2909 AppGlobals.getPackageManager().setComponentEnabledSetting(componentToEnable,
2910 PackageManager.COMPONENT_ENABLED_STATE_ENABLED, /* flags= */ 0,
2911 /* userId= */ userId);
2912 } catch (RemoteException re) {
2913 // Internal, shouldn't happen
2914 }
2915 }
2916 }
2917 }
2918
Amith Yamasani920ace02012-09-20 22:15:37 -07002919 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002920 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani742a6712011-05-04 14:49:28 -07002921 * TODO: May not be a good idea to recycle ids, in case it results in confusion
2922 * for data and battery stats collection, or unexpected cross-talk.
Amith Yamasani0b285492011-04-14 17:35:23 -07002923 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002924 private int getNextAvailableId() {
2925 synchronized (mUsersLock) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002926 int i = MIN_USER_ID;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002927 while (i < MAX_USER_ID) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002928 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002929 return i;
Amith Yamasani195263742012-08-21 15:40:12 -07002930 }
2931 i++;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002932 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002933 }
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002934 throw new IllegalStateException("No user id available!");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002935 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002936
Amith Yamasanifc95e702013-09-26 13:20:17 -07002937 private String packageToRestrictionsFileName(String packageName) {
2938 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
2939 }
2940
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002941 /**
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002942 * Enforce that serial number stored in user directory inode matches the
2943 * given expected value. Gracefully sets the serial number if currently
2944 * undefined.
2945 *
2946 * @throws IOException when problem extracting serial number, or serial
2947 * number is mismatched.
2948 */
2949 public static void enforceSerialNumber(File file, int serialNumber) throws IOException {
Jeff Sharkeya52c9d92016-06-27 17:27:43 -06002950 if (StorageManager.isFileEncryptedEmulatedOnly()) {
2951 // When we're emulating FBE, the directory may have been chmod
2952 // 000'ed, meaning we can't read the serial number to enforce it;
2953 // instead of destroying the user, just log a warning.
2954 Slog.w(LOG_TAG, "Device is emulating FBE; assuming current serial number is valid");
2955 return;
2956 }
2957
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002958 final int foundSerial = getSerialNumber(file);
2959 Slog.v(LOG_TAG, "Found " + file + " with serial number " + foundSerial);
2960
2961 if (foundSerial == -1) {
2962 Slog.d(LOG_TAG, "Serial number missing on " + file + "; assuming current is valid");
2963 try {
2964 setSerialNumber(file, serialNumber);
2965 } catch (IOException e) {
2966 Slog.w(LOG_TAG, "Failed to set serial number on " + file, e);
2967 }
2968
2969 } else if (foundSerial != serialNumber) {
2970 throw new IOException("Found serial number " + foundSerial
2971 + " doesn't match expected " + serialNumber);
2972 }
2973 }
2974
2975 /**
2976 * Set serial number stored in user directory inode.
2977 *
2978 * @throws IOException if serial number was already set
2979 */
2980 private static void setSerialNumber(File file, int serialNumber)
2981 throws IOException {
2982 try {
2983 final byte[] buf = Integer.toString(serialNumber).getBytes(StandardCharsets.UTF_8);
2984 Os.setxattr(file.getAbsolutePath(), XATTR_SERIAL, buf, OsConstants.XATTR_CREATE);
2985 } catch (ErrnoException e) {
2986 throw e.rethrowAsIOException();
2987 }
2988 }
2989
2990 /**
2991 * Return serial number stored in user directory inode.
2992 *
2993 * @return parsed serial number, or -1 if not set
2994 */
2995 private static int getSerialNumber(File file) throws IOException {
2996 try {
2997 final byte[] buf = new byte[256];
2998 final int len = Os.getxattr(file.getAbsolutePath(), XATTR_SERIAL, buf);
2999 final String serial = new String(buf, 0, len);
3000 try {
3001 return Integer.parseInt(serial);
3002 } catch (NumberFormatException e) {
3003 throw new IOException("Bad serial number: " + serial);
3004 }
3005 } catch (ErrnoException e) {
3006 if (e.errno == OsConstants.ENODATA) {
3007 return -1;
3008 } else {
3009 throw e.rethrowAsIOException();
3010 }
3011 }
3012 }
3013
Amith Yamasani920ace02012-09-20 22:15:37 -07003014 @Override
Amith Yamasani12747872015-12-07 14:19:49 -08003015 public void setSeedAccountData(int userId, String accountName, String accountType,
3016 PersistableBundle accountOptions, boolean persist) {
3017 checkManageUsersPermission("Require MANAGE_USERS permission to set user seed data");
3018 synchronized (mPackagesLock) {
3019 final UserData userData;
3020 synchronized (mUsersLock) {
3021 userData = getUserDataLU(userId);
3022 if (userData == null) {
3023 Slog.e(LOG_TAG, "No such user for settings seed data u=" + userId);
3024 return;
3025 }
3026 userData.seedAccountName = accountName;
3027 userData.seedAccountType = accountType;
3028 userData.seedAccountOptions = accountOptions;
3029 userData.persistSeedData = persist;
3030 }
3031 if (persist) {
3032 writeUserLP(userData);
3033 }
3034 }
3035 }
3036
3037 @Override
3038 public String getSeedAccountName() throws RemoteException {
3039 checkManageUsersPermission("Cannot get seed account information");
3040 synchronized (mUsersLock) {
3041 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3042 return userData.seedAccountName;
3043 }
3044 }
3045
3046 @Override
3047 public String getSeedAccountType() throws RemoteException {
3048 checkManageUsersPermission("Cannot get seed account information");
3049 synchronized (mUsersLock) {
3050 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3051 return userData.seedAccountType;
3052 }
3053 }
3054
3055 @Override
3056 public PersistableBundle getSeedAccountOptions() throws RemoteException {
3057 checkManageUsersPermission("Cannot get seed account information");
3058 synchronized (mUsersLock) {
3059 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3060 return userData.seedAccountOptions;
3061 }
3062 }
3063
3064 @Override
3065 public void clearSeedAccountData() throws RemoteException {
3066 checkManageUsersPermission("Cannot clear seed account information");
3067 synchronized (mPackagesLock) {
3068 UserData userData;
3069 synchronized (mUsersLock) {
3070 userData = getUserDataLU(UserHandle.getCallingUserId());
3071 if (userData == null) return;
3072 userData.clearSeedAccountData();
3073 }
3074 writeUserLP(userData);
3075 }
3076 }
3077
3078 @Override
3079 public boolean someUserHasSeedAccount(String accountName, String accountType)
3080 throws RemoteException {
3081 checkManageUsersPermission("Cannot check seed account information");
3082 synchronized (mUsersLock) {
3083 final int userSize = mUsers.size();
3084 for (int i = 0; i < userSize; i++) {
3085 final UserData data = mUsers.valueAt(i);
3086 if (data.info.isInitialized()) continue;
3087 if (data.seedAccountName == null || !data.seedAccountName.equals(accountName)) {
3088 continue;
3089 }
3090 if (data.seedAccountType == null || !data.seedAccountType.equals(accountType)) {
3091 continue;
3092 }
3093 return true;
3094 }
3095 }
3096 return false;
3097 }
3098
3099 @Override
Todd Kennedy60459ab2015-10-30 11:32:16 -07003100 public void onShellCommand(FileDescriptor in, FileDescriptor out,
3101 FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
3102 (new Shell()).exec(this, in, out, err, args, resultReceiver);
3103 }
3104
3105 int onShellCommand(Shell shell, String cmd) {
3106 if (cmd == null) {
3107 return shell.handleDefaultCommands(cmd);
3108 }
3109
3110 final PrintWriter pw = shell.getOutPrintWriter();
3111 try {
3112 switch(cmd) {
3113 case "list":
3114 return runList(pw);
3115 }
3116 } catch (RemoteException e) {
3117 pw.println("Remote exception: " + e);
3118 }
3119 return -1;
3120 }
3121
3122 private int runList(PrintWriter pw) throws RemoteException {
3123 final IActivityManager am = ActivityManagerNative.getDefault();
3124 final List<UserInfo> users = getUsers(false);
3125 if (users == null) {
3126 pw.println("Error: couldn't get users");
3127 return 1;
3128 } else {
3129 pw.println("Users:");
3130 for (int i = 0; i < users.size(); i++) {
Jeff Sharkeye17ac152015-11-06 22:40:29 -08003131 String running = am.isUserRunning(users.get(i).id, 0) ? " running" : "";
Todd Kennedy60459ab2015-10-30 11:32:16 -07003132 pw.println("\t" + users.get(i).toString() + running);
3133 }
3134 return 0;
3135 }
3136 }
3137
3138 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -07003139 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
3140 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
3141 != PackageManager.PERMISSION_GRANTED) {
3142 pw.println("Permission Denial: can't dump UserManager from from pid="
3143 + Binder.getCallingPid()
3144 + ", uid=" + Binder.getCallingUid()
3145 + " without permission "
3146 + android.Manifest.permission.DUMP);
3147 return;
3148 }
3149
3150 long now = System.currentTimeMillis();
3151 StringBuilder sb = new StringBuilder();
3152 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003153 synchronized (mUsersLock) {
3154 pw.println("Users:");
3155 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003156 UserData userData = mUsers.valueAt(i);
3157 if (userData == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003158 continue;
3159 }
Amith Yamasani12747872015-12-07 14:19:49 -08003160 UserInfo userInfo = userData.info;
3161 final int userId = userInfo.id;
3162 pw.print(" "); pw.print(userInfo);
3163 pw.print(" serialNo="); pw.print(userInfo.serialNumber);
Makoto Onukie7927da2015-11-25 10:05:17 -08003164 if (mRemovingUserIds.get(userId)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003165 pw.print(" <removing> ");
3166 }
Amith Yamasani12747872015-12-07 14:19:49 -08003167 if (userInfo.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003168 pw.print(" <partial>");
3169 }
3170 pw.println();
3171 pw.print(" Created: ");
Amith Yamasani12747872015-12-07 14:19:49 -08003172 if (userInfo.creationTime == 0) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003173 pw.println("<unknown>");
3174 } else {
3175 sb.setLength(0);
Amith Yamasani12747872015-12-07 14:19:49 -08003176 TimeUtils.formatDuration(now - userInfo.creationTime, sb);
Fyodor Kupolov82402752015-10-28 14:54:51 -07003177 sb.append(" ago");
3178 pw.println(sb);
3179 }
3180 pw.print(" Last logged in: ");
Amith Yamasani12747872015-12-07 14:19:49 -08003181 if (userInfo.lastLoggedInTime == 0) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003182 pw.println("<unknown>");
3183 } else {
3184 sb.setLength(0);
Amith Yamasani12747872015-12-07 14:19:49 -08003185 TimeUtils.formatDuration(now - userInfo.lastLoggedInTime, sb);
Fyodor Kupolov82402752015-10-28 14:54:51 -07003186 sb.append(" ago");
3187 pw.println(sb);
3188 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003189 pw.print(" Last logged in fingerprint: ");
3190 pw.println(userInfo.lastLoggedInFingerprint);
Makoto Onukie7927da2015-11-25 10:05:17 -08003191 pw.print(" Has profile owner: ");
3192 pw.println(mIsUserManaged.get(userId));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003193 pw.println(" Restrictions:");
3194 synchronized (mRestrictionsLock) {
3195 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003196 pw, " ", mBaseUserRestrictions.get(userInfo.id));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003197 pw.println(" Device policy local restrictions:");
3198 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003199 pw, " ", mDevicePolicyLocalUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003200 pw.println(" Effective restrictions:");
3201 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003202 pw, " ", mCachedEffectiveUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003203 }
Amith Yamasani12747872015-12-07 14:19:49 -08003204
3205 if (userData.account != null) {
3206 pw.print(" Account name: " + userData.account);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08003207 pw.println();
3208 }
Amith Yamasani12747872015-12-07 14:19:49 -08003209
3210 if (userData.seedAccountName != null) {
3211 pw.print(" Seed account name: " + userData.seedAccountName);
3212 pw.println();
3213 if (userData.seedAccountType != null) {
3214 pw.print(" account type: " + userData.seedAccountType);
3215 pw.println();
3216 }
3217 if (userData.seedAccountOptions != null) {
3218 pw.print(" account options exist");
3219 pw.println();
3220 }
3221 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003222 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003223 }
Amith Yamasani12747872015-12-07 14:19:49 -08003224 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003225 pw.println(" Device policy global restrictions:");
3226 synchronized (mRestrictionsLock) {
3227 UserRestrictionsUtils
3228 .dumpRestrictions(pw, " ", mDevicePolicyGlobalUserRestrictions);
3229 }
Makoto Onukia4f11972015-10-01 13:19:58 -07003230 pw.println();
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01003231 pw.println(" Global restrictions owner id:" + mGlobalRestrictionOwnerUserId);
3232 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003233 pw.println(" Guest restrictions:");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003234 synchronized (mGuestRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003235 UserRestrictionsUtils.dumpRestrictions(pw, " ", mGuestRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003236 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003237 synchronized (mUsersLock) {
3238 pw.println();
3239 pw.println(" Device managed: " + mIsDeviceManaged);
3240 }
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003241 synchronized (mUserStates) {
3242 pw.println(" Started users state: " + mUserStates);
3243 }
Amith Yamasani12747872015-12-07 14:19:49 -08003244 // Dump some capabilities
3245 pw.println();
3246 pw.println(" Max users: " + UserManager.getMaxSupportedUsers());
3247 pw.println(" Supports switchable users: " + UserManager.supportsMultipleUsers());
Lenka Trochtova02fee152015-12-22 14:26:18 +01003248 pw.println(" All guests ephemeral: " + Resources.getSystem().getBoolean(
3249 com.android.internal.R.bool.config_guestUserEphemeral));
Amith Yamasani920ace02012-09-20 22:15:37 -07003250 }
3251 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08003252
3253 final class MainHandler extends Handler {
3254
3255 @Override
3256 public void handleMessage(Message msg) {
3257 switch (msg.what) {
3258 case WRITE_USER_MSG:
3259 removeMessages(WRITE_USER_MSG, msg.obj);
3260 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08003261 int userId = ((UserData) msg.obj).info.id;
3262 UserData userData = getUserDataNoChecks(userId);
3263 if (userData != null) {
3264 writeUserLP(userData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08003265 }
3266 }
3267 }
3268 }
3269 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07003270
3271 /**
3272 * @param userId
3273 * @return whether the user has been initialized yet
3274 */
3275 boolean isInitialized(int userId) {
3276 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
3277 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003278
3279 private class LocalService extends UserManagerInternal {
Makoto Onuki068c54a2015-10-13 14:34:03 -07003280 @Override
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003281 public void setDevicePolicyUserRestrictions(int userId, @NonNull Bundle localRestrictions,
3282 @Nullable Bundle globalRestrictions) {
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08003283 UserManagerService.this.setDevicePolicyUserRestrictionsInner(userId, localRestrictions,
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003284 globalRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003285 }
3286
3287 @Override
3288 public Bundle getBaseUserRestrictions(int userId) {
3289 synchronized (mRestrictionsLock) {
3290 return mBaseUserRestrictions.get(userId);
3291 }
3292 }
3293
3294 @Override
3295 public void setBaseUserRestrictionsByDpmsForMigration(
3296 int userId, Bundle baseRestrictions) {
3297 synchronized (mRestrictionsLock) {
3298 mBaseUserRestrictions.put(userId, new Bundle(baseRestrictions));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003299 invalidateEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003300 }
3301
Amith Yamasani12747872015-12-07 14:19:49 -08003302 final UserData userData = getUserDataNoChecks(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003303 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08003304 if (userData != null) {
3305 writeUserLP(userData);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003306 } else {
3307 Slog.w(LOG_TAG, "UserInfo not found for " + userId);
3308 }
3309 }
3310 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08003311
3312 @Override
3313 public boolean getUserRestriction(int userId, String key) {
3314 return getUserRestrictions(userId).getBoolean(key);
3315 }
3316
3317 @Override
3318 public void addUserRestrictionsListener(UserRestrictionsListener listener) {
3319 synchronized (mUserRestrictionsListeners) {
3320 mUserRestrictionsListeners.add(listener);
3321 }
3322 }
3323
3324 @Override
3325 public void removeUserRestrictionsListener(UserRestrictionsListener listener) {
3326 synchronized (mUserRestrictionsListeners) {
3327 mUserRestrictionsListeners.remove(listener);
3328 }
3329 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003330
3331 @Override
3332 public void setDeviceManaged(boolean isManaged) {
3333 synchronized (mUsersLock) {
3334 mIsDeviceManaged = isManaged;
3335 }
3336 }
3337
3338 @Override
3339 public void setUserManaged(int userId, boolean isManaged) {
3340 synchronized (mUsersLock) {
3341 mIsUserManaged.put(userId, isManaged);
3342 }
3343 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01003344
3345 @Override
3346 public void setUserIcon(int userId, Bitmap bitmap) {
3347 long ident = Binder.clearCallingIdentity();
3348 try {
3349 synchronized (mPackagesLock) {
3350 UserData userData = getUserDataNoChecks(userId);
3351 if (userData == null || userData.info.partial) {
3352 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
3353 return;
3354 }
3355 writeBitmapLP(userData.info, bitmap);
3356 writeUserLP(userData);
3357 }
3358 sendUserInfoChangedBroadcast(userId);
3359 } finally {
3360 Binder.restoreCallingIdentity(ident);
3361 }
3362 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01003363
3364 @Override
3365 public void setForceEphemeralUsers(boolean forceEphemeralUsers) {
3366 synchronized (mUsersLock) {
3367 mForceEphemeralUsers = forceEphemeralUsers;
3368 }
3369 }
3370
3371 @Override
3372 public void removeAllUsers() {
3373 if (UserHandle.USER_SYSTEM == ActivityManager.getCurrentUser()) {
3374 // Remove the non-system users straight away.
3375 removeNonSystemUsers();
3376 } else {
3377 // Switch to the system user first and then remove the other users.
3378 BroadcastReceiver userSwitchedReceiver = new BroadcastReceiver() {
3379 @Override
3380 public void onReceive(Context context, Intent intent) {
3381 int userId =
3382 intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3383 if (userId != UserHandle.USER_SYSTEM) {
3384 return;
3385 }
3386 mContext.unregisterReceiver(this);
3387 removeNonSystemUsers();
3388 }
3389 };
3390 IntentFilter userSwitchedFilter = new IntentFilter();
3391 userSwitchedFilter.addAction(Intent.ACTION_USER_SWITCHED);
3392 mContext.registerReceiver(
3393 userSwitchedReceiver, userSwitchedFilter, null, mHandler);
3394
3395 // Switch to the system user.
3396 ActivityManager am =
3397 (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
3398 am.switchUser(UserHandle.USER_SYSTEM);
3399 }
3400 }
phweisse9c44062016-02-10 12:57:38 +01003401
3402 @Override
Lenka Trochtova1ddda472016-02-12 10:42:12 +01003403 public void onEphemeralUserStop(int userId) {
3404 synchronized (mUsersLock) {
3405 UserInfo userInfo = getUserInfoLU(userId);
3406 if (userInfo != null && userInfo.isEphemeral()) {
3407 // Do not allow switching back to the ephemeral user again as the user is going
3408 // to be deleted.
3409 userInfo.flags |= UserInfo.FLAG_DISABLED;
3410 if (userInfo.isGuest()) {
3411 // Indicate that the guest will be deleted after it stops.
3412 userInfo.guestToRemove = true;
3413 }
3414 }
3415 }
3416 }
3417
3418 @Override
phweisse9c44062016-02-10 12:57:38 +01003419 public UserInfo createUserEvenWhenDisallowed(String name, int flags) {
3420 UserInfo user = createUserInternalUnchecked(name, flags, UserHandle.USER_NULL);
3421 // Keep this in sync with UserManager.createUser
3422 if (user != null && !user.isAdmin()) {
3423 setUserRestriction(UserManager.DISALLOW_SMS, true, user.id);
3424 setUserRestriction(UserManager.DISALLOW_OUTGOING_CALLS, true, user.id);
3425 }
3426 return user;
3427 }
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003428
3429 @Override
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003430 public boolean isUserRunning(int userId) {
3431 synchronized (mUserStates) {
3432 return mUserStates.get(userId, -1) >= 0;
3433 }
3434 }
3435
3436 @Override
3437 public void setUserState(int userId, int userState) {
3438 synchronized (mUserStates) {
3439 mUserStates.put(userId, userState);
3440 }
3441 }
3442
3443 @Override
3444 public void removeUserState(int userId) {
3445 synchronized (mUserStates) {
3446 mUserStates.delete(userId);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003447 }
3448 }
3449
3450 @Override
3451 public boolean isUserUnlockingOrUnlocked(int userId) {
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003452 synchronized (mUserStates) {
3453 int state = mUserStates.get(userId, -1);
3454 return (state == UserState.STATE_RUNNING_UNLOCKING)
3455 || (state == UserState.STATE_RUNNING_UNLOCKED);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003456 }
3457 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01003458 }
3459
3460 /* Remove all the users except of the system one. */
3461 private void removeNonSystemUsers() {
3462 ArrayList<UserInfo> usersToRemove = new ArrayList<>();
3463 synchronized (mUsersLock) {
3464 final int userSize = mUsers.size();
3465 for (int i = 0; i < userSize; i++) {
3466 UserInfo ui = mUsers.valueAt(i).info;
3467 if (ui.id != UserHandle.USER_SYSTEM) {
3468 usersToRemove.add(ui);
3469 }
3470 }
3471 }
3472 for (UserInfo ui: usersToRemove) {
3473 removeUser(ui.id);
3474 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003475 }
Todd Kennedy60459ab2015-10-30 11:32:16 -07003476
3477 private class Shell extends ShellCommand {
3478 @Override
3479 public int onCommand(String cmd) {
3480 return onShellCommand(this, cmd);
3481 }
3482
3483 @Override
3484 public void onHelp() {
3485 final PrintWriter pw = getOutPrintWriter();
3486 pw.println("User manager (user) commands:");
3487 pw.println(" help");
3488 pw.println(" Print this help text.");
3489 pw.println("");
3490 pw.println(" list");
3491 pw.println(" Prints all users on the system.");
3492 }
3493 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003494
3495 private static void debug(String message) {
3496 Log.d(LOG_TAG, message +
3497 (DBG_WITH_STACKTRACE ? " called at\n" + Debug.getCallers(10, " ") : ""));
3498 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003499}