blob: 6b0e5827d4e00eb4315ce913fe5fb11adb2e8782 [file] [log] [blame]
Tony Mak8673b282016-03-21 21:10:59 +00001
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002/*
3 * Copyright (C) 2011 The Android Open Source Project
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18package com.android.server.pm;
19
Benjamin Franzf02420c2016-04-04 18:52:21 +010020import static android.content.Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS;
21import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
22
Xiaohui Chenb3b92582015-12-07 11:22:13 -080023import android.Manifest;
Xiaohui Chen594f2082015-08-18 11:04:20 -070024import android.annotation.NonNull;
Makoto Onuki068c54a2015-10-13 14:34:03 -070025import android.annotation.Nullable;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -060026import android.annotation.UserIdInt;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070027import android.app.Activity;
Amith Yamasani2a003292012-08-14 18:25:45 -070028import android.app.ActivityManager;
Amith Yamasani515d4062015-09-28 11:30:06 -070029import android.app.ActivityManagerInternal;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070030import android.app.ActivityManagerNative;
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;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070034import android.content.BroadcastReceiver;
Amith Yamasani258848d2012-08-10 17:06:33 -070035import android.content.Context;
36import android.content.Intent;
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +010037import android.content.IntentFilter;
Benjamin Franzf02420c2016-04-04 18:52:21 +010038import android.content.IntentSender;
Amith Yamasani0b285492011-04-14 17:35:23 -070039import android.content.pm.PackageManager;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -080040import android.content.pm.PackageManager.NameNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070041import android.content.pm.UserInfo;
Lenka Trochtova02fee152015-12-22 14:26:18 +010042import android.content.res.Resources;
Amith Yamasanie928d7d2012-09-17 21:46:51 -070043import android.graphics.Bitmap;
Amith Yamasani258848d2012-08-10 17:06:33 -070044import android.os.Binder;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -060045import android.os.Build;
Amith Yamasanie4cf7342012-12-17 11:12:09 -080046import android.os.Bundle;
Makoto Onuki1a2cd742015-11-16 13:51:27 -080047import android.os.Debug;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070048import android.os.Environment;
49import android.os.FileUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080050import android.os.Handler;
Svet Ganov9cea80cd2016-02-16 11:47:00 -080051import android.os.IBinder;
Amith Yamasani258848d2012-08-10 17:06:33 -070052import android.os.IUserManager;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -080053import android.os.Message;
Adrian Roos1bdff912015-02-17 15:51:35 +010054import android.os.ParcelFileDescriptor;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070055import android.os.Parcelable;
Amith Yamasani12747872015-12-07 14:19:49 -080056import android.os.PersistableBundle;
Amith Yamasani258848d2012-08-10 17:06:33 -070057import android.os.Process;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070058import android.os.RemoteException;
Todd Kennedy60459ab2015-10-30 11:32:16 -070059import android.os.ResultReceiver;
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +010060import android.os.SELinux;
Jason Monk62062992014-05-06 09:55:28 -040061import android.os.ServiceManager;
Todd Kennedy60459ab2015-10-30 11:32:16 -070062import android.os.ShellCommand;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070063import android.os.UserHandle;
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070064import android.os.UserManager;
Makoto Onuki068c54a2015-10-13 14:34:03 -070065import android.os.UserManagerInternal;
Makoto Onukid45a4a22015-11-02 17:17:38 -080066import android.os.UserManagerInternal.UserRestrictionsListener;
Paul Crowley85e4e812015-05-19 12:42:00 +010067import android.os.storage.StorageManager;
Jeff Sharkey6dce4962015-07-03 18:08:41 -070068import android.system.ErrnoException;
69import android.system.Os;
70import android.system.OsConstants;
Amith Yamasani2a003292012-08-14 18:25:45 -070071import android.util.AtomicFile;
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -070072import android.util.IntArray;
Amith Yamasani655d0e22013-06-12 14:19:10 -070073import android.util.Log;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070074import android.util.Slog;
75import android.util.SparseArray;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080076import android.util.SparseBooleanArray;
Amith Yamasani920ace02012-09-20 22:15:37 -070077import android.util.TimeUtils;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070078import android.util.Xml;
79
Makoto Onuki068c54a2015-10-13 14:34:03 -070080import com.android.internal.annotations.GuardedBy;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070081import com.android.internal.annotations.VisibleForTesting;
Jason Monk62062992014-05-06 09:55:28 -040082import com.android.internal.app.IAppOpsService;
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -080083import com.android.internal.logging.MetricsLogger;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080084import com.android.internal.util.FastXmlSerializer;
Makoto Onuki068c54a2015-10-13 14:34:03 -070085import com.android.internal.util.Preconditions;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070086import com.android.internal.util.XmlUtils;
Clara Bayarri10ad84a2015-12-01 17:38:05 +000087import com.android.internal.widget.LockPatternUtils;
Amith Yamasani515d4062015-09-28 11:30:06 -070088import com.android.server.LocalServices;
Jeff Sharkey47f71082016-02-01 17:03:54 -070089
90import libcore.io.IoUtils;
91import libcore.util.Objects;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080092
93import org.xmlpull.v1.XmlPullParser;
94import org.xmlpull.v1.XmlPullParserException;
95import org.xmlpull.v1.XmlSerializer;
96
Amith Yamasani4b2e9342011-03-31 12:38:53 -070097import java.io.BufferedOutputStream;
98import java.io.File;
Amith Yamasani920ace02012-09-20 22:15:37 -070099import java.io.FileDescriptor;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700100import java.io.FileInputStream;
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700101import java.io.FileNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700102import java.io.FileOutputStream;
103import java.io.IOException;
Amith Yamasani920ace02012-09-20 22:15:37 -0700104import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100105import java.nio.charset.StandardCharsets;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700106import java.util.ArrayList;
107import java.util.List;
108
Makoto Onuki068c54a2015-10-13 14:34:03 -0700109/**
110 * Service for {@link UserManager}.
111 *
112 * Method naming convention:
Fyodor Kupolov82402752015-10-28 14:54:51 -0700113 * <ul>
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800114 * <li> Methods suffixed with "LP" should be called within the {@link #mPackagesLock} lock.
Fyodor Kupolov82402752015-10-28 14:54:51 -0700115 * <li> Methods suffixed with "LR" should be called within the {@link #mRestrictionsLock} lock.
116 * <li> Methods suffixed with "LU" should be called within the {@link #mUsersLock} lock.
117 * </ul>
Makoto Onuki068c54a2015-10-13 14:34:03 -0700118 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700119public class UserManagerService extends IUserManager.Stub {
Amith Yamasani2a003292012-08-14 18:25:45 -0700120 private static final String LOG_TAG = "UserManagerService";
Makoto Onuki81c61ea2016-01-22 11:22:26 -0800121 static final boolean DBG = false; // DO NOT SUBMIT WITH TRUE
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800122 private static final boolean DBG_WITH_STACKTRACE = false; // DO NOT SUBMIT WITH TRUE
Amith Yamasani16389312012-10-17 21:20:14 -0700123
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700124 private static final String TAG_NAME = "name";
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800125 private static final String TAG_ACCOUNT = "account";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700126 private static final String ATTR_FLAGS = "flags";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700127 private static final String ATTR_ICON_PATH = "icon";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700128 private static final String ATTR_ID = "id";
Amith Yamasani920ace02012-09-20 22:15:37 -0700129 private static final String ATTR_CREATION_TIME = "created";
130 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -0600131 private static final String ATTR_LAST_LOGGED_IN_FINGERPRINT = "lastLoggedInFingerprint";
Amith Yamasani2a003292012-08-14 18:25:45 -0700132 private static final String ATTR_SERIAL_NO = "serialNumber";
133 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700134 private static final String ATTR_PARTIAL = "partial";
Adam Lesinskieddeb492014-09-08 17:50:03 -0700135 private static final String ATTR_GUEST_TO_REMOVE = "guestToRemove";
Amith Yamasani6f34b412012-10-22 18:19:27 -0700136 private static final String ATTR_USER_VERSION = "version";
Kenny Guy2a764942014-04-02 13:29:20 +0100137 private static final String ATTR_PROFILE_GROUP_ID = "profileGroupId";
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700138 private static final String ATTR_RESTRICTED_PROFILE_PARENT_ID = "restrictedProfileParentId";
Amith Yamasani12747872015-12-07 14:19:49 -0800139 private static final String ATTR_SEED_ACCOUNT_NAME = "seedAccountName";
140 private static final String ATTR_SEED_ACCOUNT_TYPE = "seedAccountType";
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530141 private static final String TAG_GUEST_RESTRICTIONS = "guestRestrictions";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700142 private static final String TAG_USERS = "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700143 private static final String TAG_USER = "user";
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800144 private static final String TAG_RESTRICTIONS = "restrictions";
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800145 private static final String TAG_DEVICE_POLICY_RESTRICTIONS = "device_policy_restrictions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800146 private static final String TAG_ENTRY = "entry";
147 private static final String TAG_VALUE = "value";
Amith Yamasani12747872015-12-07 14:19:49 -0800148 private static final String TAG_SEED_ACCOUNT_OPTIONS = "seedAccountOptions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800149 private static final String ATTR_KEY = "key";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700150 private static final String ATTR_VALUE_TYPE = "type";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800151 private static final String ATTR_MULTIPLE = "m";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700152
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700153 private static final String ATTR_TYPE_STRING_ARRAY = "sa";
154 private static final String ATTR_TYPE_STRING = "s";
155 private static final String ATTR_TYPE_BOOLEAN = "b";
Amith Yamasani5b5aa402014-06-01 20:10:14 -0700156 private static final String ATTR_TYPE_INTEGER = "i";
Fyodor Kupolov262f9952015-03-23 18:55:11 -0700157 private static final String ATTR_TYPE_BUNDLE = "B";
158 private static final String ATTR_TYPE_BUNDLE_ARRAY = "BA";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700159
Amith Yamasani0b285492011-04-14 17:35:23 -0700160 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700161 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700162 private static final String USER_PHOTO_FILENAME = "photo.png";
Adrian Roos1bdff912015-02-17 15:51:35 +0100163 private static final String USER_PHOTO_FILENAME_TMP = USER_PHOTO_FILENAME + ".tmp";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700164
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800165 private static final String RESTRICTIONS_FILE_PREFIX = "res_";
Amith Yamasanifc95e702013-09-26 13:20:17 -0700166 private static final String XML_SUFFIX = ".xml";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800167
Amith Yamasani634cf312012-10-04 17:34:21 -0700168 private static final int MIN_USER_ID = 10;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700169 // We need to keep process uid within Integer.MAX_VALUE.
170 private static final int MAX_USER_ID = Integer.MAX_VALUE / UserHandle.PER_USER_RANGE;
Amith Yamasani634cf312012-10-04 17:34:21 -0700171
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700172 private static final int USER_VERSION = 6;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700173
Amith Yamasani920ace02012-09-20 22:15:37 -0700174 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
175
Nicolas Prevotb8186812015-08-06 15:00:03 +0100176 // Maximum number of managed profiles permitted per user is 1. This cannot be increased
Amith Yamasani95ab7842014-08-11 17:09:26 -0700177 // without first making sure that the rest of the framework is prepared for it.
178 private static final int MAX_MANAGED_PROFILES = 1;
179
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800180 static final int WRITE_USER_MSG = 1;
181 static final int WRITE_USER_DELAY = 2*1000; // 2 seconds
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530182
Jeff Sharkey6dce4962015-07-03 18:08:41 -0700183 private static final String XATTR_SERIAL = "user.serial";
184
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -0800185 // Tron counters
186 private static final String TRON_GUEST_CREATED = "users_guest_created";
187 private static final String TRON_USER_CREATED = "users_user_created";
188
Dianne Hackborn4428e172012-08-24 17:43:05 -0700189 private final Context mContext;
190 private final PackageManagerService mPm;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700191 private final Object mPackagesLock;
Fyodor Kupolov82402752015-10-28 14:54:51 -0700192 // Short-term lock for internal state, when interaction/sync with PM is not required
193 private final Object mUsersLock = new Object();
194 private final Object mRestrictionsLock = new Object();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700195
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800196 private final Handler mHandler;
197
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700198 private final File mUsersDir;
199 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700200
Svet Ganov9cea80cd2016-02-16 11:47:00 -0800201 private static final IBinder mUserRestriconToken = new Binder();
202
Makoto Onuki068c54a2015-10-13 14:34:03 -0700203 /**
Amith Yamasani12747872015-12-07 14:19:49 -0800204 * User-related information that is used for persisting to flash. Only UserInfo is
205 * directly exposed to other system apps.
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800206 */
Amith Yamasani12747872015-12-07 14:19:49 -0800207 private static class UserData {
208 // Basic user information and properties
209 UserInfo info;
210 // Account name used when there is a strong association between a user and an account
211 String account;
212 // Account information for seeding into a newly created user. This could also be
213 // used for login validation for an existing user, for updating their credentials.
214 // In the latter case, data may not need to be persisted as it is only valid for the
215 // current login session.
216 String seedAccountName;
217 String seedAccountType;
218 PersistableBundle seedAccountOptions;
219 // Whether to perist the seed account information to be available after a boot
220 boolean persistSeedData;
221
222 void clearSeedAccountData() {
223 seedAccountName = null;
224 seedAccountType = null;
225 seedAccountOptions = null;
226 persistSeedData = false;
227 }
228 }
229
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800230 @GuardedBy("mUsersLock")
Amith Yamasani12747872015-12-07 14:19:49 -0800231 private final SparseArray<UserData> mUsers = new SparseArray<>();
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800232
233 /**
Makoto Onuki068c54a2015-10-13 14:34:03 -0700234 * User restrictions set via UserManager. This doesn't include restrictions set by
235 * device owner / profile owners.
236 *
237 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
238 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
239 * maybe shared between {@link #mBaseUserRestrictions} and
240 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
241 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700242 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700243 */
244 @GuardedBy("mRestrictionsLock")
245 private final SparseArray<Bundle> mBaseUserRestrictions = new SparseArray<>();
246
247 /**
248 * Cached user restrictions that are in effect -- i.e. {@link #mBaseUserRestrictions} combined
249 * with device / profile owner restrictions. We'll initialize it lazily; use
250 * {@link #getEffectiveUserRestrictions} to access it.
251 *
252 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
253 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
254 * maybe shared between {@link #mBaseUserRestrictions} and
255 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
256 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700257 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700258 */
259 @GuardedBy("mRestrictionsLock")
260 private final SparseArray<Bundle> mCachedEffectiveUserRestrictions = new SparseArray<>();
261
Makoto Onuki4f160732015-10-27 17:15:38 -0700262 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800263 * User restrictions that have already been applied in
264 * {@link #updateUserRestrictionsInternalLR(Bundle, int)}. We use it to detect restrictions
265 * that have changed since the last
266 * {@link #updateUserRestrictionsInternalLR(Bundle, int)} call.
Makoto Onuki4f160732015-10-27 17:15:38 -0700267 */
268 @GuardedBy("mRestrictionsLock")
269 private final SparseArray<Bundle> mAppliedUserRestrictions = new SparseArray<>();
270
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800271 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800272 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
273 * that should be applied to all users, including guests.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800274 */
275 @GuardedBy("mRestrictionsLock")
276 private Bundle mDevicePolicyGlobalUserRestrictions;
277
278 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800279 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
280 * for each user.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800281 */
282 @GuardedBy("mRestrictionsLock")
283 private final SparseArray<Bundle> mDevicePolicyLocalUserRestrictions = new SparseArray<>();
284
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800285 @GuardedBy("mGuestRestrictions")
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530286 private final Bundle mGuestRestrictions = new Bundle();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800287
288 /**
289 * Set of user IDs being actively removed. Removed IDs linger in this set
290 * for several seconds to work around a VFS caching issue.
291 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700292 @GuardedBy("mUsersLock")
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800293 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700294
Fyodor Kupolov82402752015-10-28 14:54:51 -0700295 @GuardedBy("mUsersLock")
Amith Yamasani0b285492011-04-14 17:35:23 -0700296 private int[] mUserIds;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800297 @GuardedBy("mPackagesLock")
Amith Yamasani2a003292012-08-14 18:25:45 -0700298 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700299 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700300
Jason Monk62062992014-05-06 09:55:28 -0400301 private IAppOpsService mAppOpsService;
302
Makoto Onuki068c54a2015-10-13 14:34:03 -0700303 private final LocalService mLocalService;
304
Makoto Onukie7927da2015-11-25 10:05:17 -0800305 @GuardedBy("mUsersLock")
306 private boolean mIsDeviceManaged;
307
308 @GuardedBy("mUsersLock")
309 private final SparseBooleanArray mIsUserManaged = new SparseBooleanArray();
310
Makoto Onukid45a4a22015-11-02 17:17:38 -0800311 @GuardedBy("mUserRestrictionsListeners")
312 private final ArrayList<UserRestrictionsListener> mUserRestrictionsListeners =
313 new ArrayList<>();
314
Clara Bayarria1771112015-12-18 16:29:18 +0000315 private final LockPatternUtils mLockPatternUtils;
316
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +0100317 /**
318 * Whether all users should be created ephemeral.
319 */
320 @GuardedBy("mUsersLock")
321 private boolean mForceEphemeralUsers;
322
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -0700323 @GuardedBy("mUsersLock")
324 private final SparseBooleanArray mUnlockingOrUnlockedUsers = new SparseBooleanArray();
325
Amith Yamasani258848d2012-08-10 17:06:33 -0700326 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700327
Dianne Hackborn4428e172012-08-24 17:43:05 -0700328 public static UserManagerService getInstance() {
329 synchronized (UserManagerService.class) {
330 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700331 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700332 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700333
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800334 @VisibleForTesting
335 UserManagerService(File dataDir) {
336 this(null, null, new Object(), dataDir);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700337 }
338
Dianne Hackborn4428e172012-08-24 17:43:05 -0700339 /**
340 * Called by package manager to create the service. This is closely
341 * associated with the package manager, and the given lock is the
342 * package manager's own lock.
343 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800344 UserManagerService(Context context, PackageManagerService pm, Object packagesLock) {
345 this(context, pm, packagesLock, Environment.getDataDirectory());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700346 }
347
Dianne Hackborn4428e172012-08-24 17:43:05 -0700348 private UserManagerService(Context context, PackageManagerService pm,
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800349 Object packagesLock, File dataDir) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700350 mContext = context;
351 mPm = pm;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700352 mPackagesLock = packagesLock;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800353 mHandler = new MainHandler();
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800354 synchronized (mPackagesLock) {
355 mUsersDir = new File(dataDir, USER_INFO_DIR);
356 mUsersDir.mkdirs();
357 // Make zeroth user directory, for services to migrate their files to that location
358 File userZeroDir = new File(mUsersDir, String.valueOf(UserHandle.USER_SYSTEM));
359 userZeroDir.mkdirs();
360 FileUtils.setPermissions(mUsersDir.toString(),
361 FileUtils.S_IRWXU | FileUtils.S_IRWXG | FileUtils.S_IROTH | FileUtils.S_IXOTH,
362 -1, -1);
363 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
364 initDefaultGuestRestrictions();
365 readUserListLP();
366 sInstance = this;
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700367 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700368 mLocalService = new LocalService();
369 LocalServices.addService(UserManagerInternal.class, mLocalService);
Clara Bayarria1771112015-12-18 16:29:18 +0000370 mLockPatternUtils = new LockPatternUtils(mContext);
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700371 }
372
373 void systemReady() {
Lenka Trochtovac4dd0212015-11-18 12:22:06 +0100374 // Prune out any partially created, partially removed and ephemeral users.
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800375 ArrayList<UserInfo> partials = new ArrayList<>();
376 synchronized (mUsersLock) {
377 final int userSize = mUsers.size();
378 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800379 UserInfo ui = mUsers.valueAt(i).info;
Lenka Trochtovac4dd0212015-11-18 12:22:06 +0100380 if ((ui.partial || ui.guestToRemove || ui.isEphemeral()) && i != 0) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800381 partials.add(ui);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700382 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700383 }
Dianne Hackborn4428e172012-08-24 17:43:05 -0700384 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800385 final int partialsSize = partials.size();
386 for (int i = 0; i < partialsSize; i++) {
387 UserInfo ui = partials.get(i);
388 Slog.w(LOG_TAG, "Removing partially created user " + ui.id
389 + " (name=" + ui.name + ")");
390 removeUserState(ui.id);
391 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800392
Jason Monk62062992014-05-06 09:55:28 -0400393 mAppOpsService = IAppOpsService.Stub.asInterface(
394 ServiceManager.getService(Context.APP_OPS_SERVICE));
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800395
396 synchronized (mRestrictionsLock) {
397 applyUserRestrictionsLR(UserHandle.USER_SYSTEM);
Jason Monk62062992014-05-06 09:55:28 -0400398 }
Samuel Tand9453b82016-03-14 15:57:02 -0700399
400 UserInfo currentGuestUser = findCurrentGuestUser();
401 if (currentGuestUser != null && !hasUserRestriction(
402 UserManager.DISALLOW_CONFIG_WIFI, currentGuestUser.id)) {
403 // If a guest user currently exists, apply the DISALLOW_CONFIG_WIFI option
404 // to it, in case this guest was created in a previous version where this
405 // user restriction was not a default guest restriction.
406 setUserRestriction(UserManager.DISALLOW_CONFIG_WIFI, true, currentGuestUser.id);
407 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700408 }
409
410 @Override
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800411 public String getUserAccount(int userId) {
412 checkManageUserAndAcrossUsersFullPermission("get user account");
413 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800414 return mUsers.get(userId).account;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800415 }
416 }
417
418 @Override
419 public void setUserAccount(int userId, String accountName) {
420 checkManageUserAndAcrossUsersFullPermission("set user account");
Amith Yamasani12747872015-12-07 14:19:49 -0800421 UserData userToUpdate = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800422 synchronized (mPackagesLock) {
423 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800424 final UserData userData = mUsers.get(userId);
425 if (userData == null) {
426 Slog.e(LOG_TAG, "User not found for setting user account: u" + userId);
427 return;
428 }
429 String currentAccount = userData.account;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800430 if (!Objects.equal(currentAccount, accountName)) {
Amith Yamasani12747872015-12-07 14:19:49 -0800431 userData.account = accountName;
432 userToUpdate = userData;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800433 }
434 }
435
436 if (userToUpdate != null) {
437 writeUserLP(userToUpdate);
438 }
439 }
440 }
441
442 @Override
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700443 public UserInfo getPrimaryUser() {
444 checkManageUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700445 synchronized (mUsersLock) {
Amith Yamasani515d4062015-09-28 11:30:06 -0700446 final int userSize = mUsers.size();
447 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800448 UserInfo ui = mUsers.valueAt(i).info;
Xiaohui Chend3e9e182015-11-18 13:37:32 -0800449 if (ui.isPrimary() && !mRemovingUserIds.get(ui.id)) {
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700450 return ui;
451 }
452 }
453 }
454 return null;
455 }
456
457 @Override
Xiaohui Chen594f2082015-08-18 11:04:20 -0700458 public @NonNull List<UserInfo> getUsers(boolean excludeDying) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700459 checkManageUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700460 synchronized (mUsersLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700461 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasani515d4062015-09-28 11:30:06 -0700462 final int userSize = mUsers.size();
463 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800464 UserInfo ui = mUsers.valueAt(i).info;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700465 if (ui.partial) {
466 continue;
467 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800468 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Amith Yamasani6f48d6e2016-03-23 14:28:25 -0700469 users.add(userWithName(ui));
Amith Yamasani920ace02012-09-20 22:15:37 -0700470 }
Amith Yamasani13593602012-03-22 16:16:17 -0700471 }
472 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700473 }
Amith Yamasani13593602012-03-22 16:16:17 -0700474 }
475
Amith Yamasani258848d2012-08-10 17:06:33 -0700476 @Override
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100477 public List<UserInfo> getProfiles(int userId, boolean enabledOnly) {
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700478 boolean returnFullInfo = true;
Amith Yamasani4f582632014-02-19 14:31:52 -0800479 if (userId != UserHandle.getCallingUserId()) {
480 checkManageUsersPermission("getting profiles related to user " + userId);
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700481 } else {
482 returnFullInfo = hasManageUsersPermission();
Amith Yamasani4f582632014-02-19 14:31:52 -0800483 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700484 final long ident = Binder.clearCallingIdentity();
485 try {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700486 synchronized (mUsersLock) {
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700487 return getProfilesLU(userId, enabledOnly, returnFullInfo);
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100488 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700489 } finally {
490 Binder.restoreCallingIdentity(ident);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000491 }
492 }
493
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700494 @Override
495 public int[] getProfileIds(int userId, boolean enabledOnly) {
496 if (userId != UserHandle.getCallingUserId()) {
497 checkManageUsersPermission("getting profiles related to user " + userId);
498 }
499 final long ident = Binder.clearCallingIdentity();
500 try {
501 synchronized (mUsersLock) {
502 return getProfileIdsLU(userId, enabledOnly).toArray();
503 }
504 } finally {
505 Binder.restoreCallingIdentity(ident);
506 }
507 }
508
Amith Yamasanibe465322014-04-24 13:45:17 -0700509 /** Assume permissions already checked and caller's identity cleared */
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700510 private List<UserInfo> getProfilesLU(int userId, boolean enabledOnly, boolean fullInfo) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700511 IntArray profileIds = getProfileIdsLU(userId, enabledOnly);
512 ArrayList<UserInfo> users = new ArrayList<>(profileIds.size());
513 for (int i = 0; i < profileIds.size(); i++) {
514 int profileId = profileIds.get(i);
515 UserInfo userInfo = mUsers.get(profileId).info;
516 // If full info is not required - clear PII data to prevent 3P apps from reading it
517 if (!fullInfo) {
518 userInfo = new UserInfo(userInfo);
519 userInfo.name = null;
520 userInfo.iconPath = null;
521 } else {
522 userInfo = userWithName(userInfo);
523 }
524 users.add(userInfo);
525 }
526 return users;
527 }
528
529 /**
530 * Assume permissions already checked and caller's identity cleared
531 */
532 private IntArray getProfileIdsLU(int userId, boolean enabledOnly) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700533 UserInfo user = getUserInfoLU(userId);
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700534 IntArray result = new IntArray(mUsers.size());
Amith Yamasanidda003f2014-08-28 18:06:51 -0700535 if (user == null) {
536 // Probably a dying user
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700537 return result;
Amith Yamasanidda003f2014-08-28 18:06:51 -0700538 }
Amith Yamasani515d4062015-09-28 11:30:06 -0700539 final int userSize = mUsers.size();
540 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800541 UserInfo profile = mUsers.valueAt(i).info;
Amith Yamasanibe465322014-04-24 13:45:17 -0700542 if (!isProfileOf(user, profile)) {
543 continue;
544 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100545 if (enabledOnly && !profile.isEnabled()) {
546 continue;
Amith Yamasanibe465322014-04-24 13:45:17 -0700547 }
Amith Yamasani70fcf0c2014-07-11 08:40:19 -0700548 if (mRemovingUserIds.get(profile.id)) {
549 continue;
550 }
Tony Mak80189cd2016-04-05 17:21:42 +0100551 if (profile.partial) {
552 continue;
553 }
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700554 result.add(profile.id);
Amith Yamasanibe465322014-04-24 13:45:17 -0700555 }
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700556 return result;
Amith Yamasanibe465322014-04-24 13:45:17 -0700557 }
558
Jessica Hummelbe81c802014-04-22 15:49:22 +0100559 @Override
Andres Moralesc5548c02015-08-05 10:23:12 -0700560 public int getCredentialOwnerProfile(int userHandle) {
561 checkManageUsersPermission("get the credential owner");
Clara Bayarria1771112015-12-18 16:29:18 +0000562 if (!mLockPatternUtils.isSeparateProfileChallengeEnabled(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700563 synchronized (mUsersLock) {
564 UserInfo profileParent = getProfileParentLU(userHandle);
Andres Moralesc5548c02015-08-05 10:23:12 -0700565 if (profileParent != null) {
566 return profileParent.id;
567 }
568 }
569 }
570
571 return userHandle;
572 }
573
574 @Override
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700575 public boolean isSameProfileGroup(int userId, int otherUserId) {
576 if (userId == otherUserId) return true;
577 checkManageUsersPermission("check if in the same profile group");
578 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700579 return isSameProfileGroupLP(userId, otherUserId);
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700580 }
581 }
582
Fyodor Kupolov82402752015-10-28 14:54:51 -0700583 private boolean isSameProfileGroupLP(int userId, int otherUserId) {
584 synchronized (mUsersLock) {
585 UserInfo userInfo = getUserInfoLU(userId);
586 if (userInfo == null || userInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
587 return false;
588 }
589 UserInfo otherUserInfo = getUserInfoLU(otherUserId);
590 if (otherUserInfo == null
591 || otherUserInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
592 return false;
593 }
594 return userInfo.profileGroupId == otherUserInfo.profileGroupId;
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700595 }
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700596 }
597
598 @Override
Jessica Hummelbe81c802014-04-22 15:49:22 +0100599 public UserInfo getProfileParent(int userHandle) {
600 checkManageUsersPermission("get the profile parent");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700601 synchronized (mUsersLock) {
602 return getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700603 }
604 }
605
Fyodor Kupolov82402752015-10-28 14:54:51 -0700606 private UserInfo getProfileParentLU(int userHandle) {
607 UserInfo profile = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700608 if (profile == null) {
609 return null;
610 }
611 int parentUserId = profile.profileGroupId;
612 if (parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
613 return null;
614 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700615 return getUserInfoLU(parentUserId);
Jessica Hummelbe81c802014-04-22 15:49:22 +0100616 }
617 }
618
Fyodor Kupolov82402752015-10-28 14:54:51 -0700619 private static boolean isProfileOf(UserInfo user, UserInfo profile) {
Kenny Guy2a764942014-04-02 13:29:20 +0100620 return user.id == profile.id ||
621 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
622 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000623 }
624
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000625 private void broadcastProfileAvailabilityChanges(UserHandle profileHandle,
Rubin Xuf13c9802016-01-21 18:06:00 +0000626 UserHandle parentHandle, boolean inQuietMode) {
Rubin Xue95057a2016-04-01 16:49:25 +0100627 Intent intent = new Intent();
628 if (inQuietMode) {
629 intent.setAction(Intent.ACTION_MANAGED_PROFILE_UNAVAILABLE);
630 } else {
631 intent.setAction(Intent.ACTION_MANAGED_PROFILE_AVAILABLE);
632 }
Rubin Xuf13c9802016-01-21 18:06:00 +0000633 intent.putExtra(Intent.EXTRA_QUIET_MODE, inQuietMode);
634 intent.putExtra(Intent.EXTRA_USER, profileHandle);
635 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileHandle.getIdentifier());
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000636 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Rubin Xuf13c9802016-01-21 18:06:00 +0000637 mContext.sendBroadcastAsUser(intent, parentHandle);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000638 }
639
640 @Override
641 public void setQuietModeEnabled(int userHandle, boolean enableQuietMode) {
642 checkManageUsersPermission("silence profile");
643 boolean changed = false;
644 UserInfo profile, parent;
645 synchronized (mPackagesLock) {
646 synchronized (mUsersLock) {
647 profile = getUserInfoLU(userHandle);
648 parent = getProfileParentLU(userHandle);
649
650 }
651 if (profile == null || !profile.isManagedProfile()) {
652 throw new IllegalArgumentException("User " + userHandle + " is not a profile");
653 }
654 if (profile.isQuietModeEnabled() != enableQuietMode) {
655 profile.flags ^= UserInfo.FLAG_QUIET_MODE;
Amith Yamasani12747872015-12-07 14:19:49 -0800656 writeUserLP(getUserDataLU(profile.id));
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000657 changed = true;
658 }
659 }
660 if (changed) {
Rubin Xuf13c9802016-01-21 18:06:00 +0000661 long identity = Binder.clearCallingIdentity();
662 try {
663 if (enableQuietMode) {
Rubin Xuf8451b92016-04-01 15:50:58 +0100664 LocalServices.getService(ActivityManagerInternal.class)
665 .killForegroundAppsForUser(userHandle);
Rubin Xuf13c9802016-01-21 18:06:00 +0000666 ActivityManagerNative.getDefault().stopUser(userHandle, /* force */true, null);
667 } else {
668 ActivityManagerNative.getDefault().startUserInBackground(userHandle);
669 }
670 } catch (RemoteException e) {
671 Slog.e(LOG_TAG, "fail to start/stop user for quiet mode", e);
672 } finally {
673 Binder.restoreCallingIdentity(identity);
674 }
675
676 broadcastProfileAvailabilityChanges(profile.getUserHandle(), parent.getUserHandle(),
677 enableQuietMode);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000678 }
679 }
680
681 @Override
682 public boolean isQuietModeEnabled(int userHandle) {
683 synchronized (mPackagesLock) {
684 UserInfo info;
685 synchronized (mUsersLock) {
686 info = getUserInfoLU(userHandle);
687 }
688 if (info == null || !info.isManagedProfile()) {
Rubin Xuf13c9802016-01-21 18:06:00 +0000689 return false;
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000690 }
691 return info.isQuietModeEnabled();
692 }
693 }
694
Kenny Guya52dc3e2014-02-11 15:33:14 +0000695 @Override
Benjamin Franzf02420c2016-04-04 18:52:21 +0100696 public boolean trySetQuietModeDisabled(int userHandle, IntentSender target) {
Ricky Wai7881cf82016-04-15 17:20:12 +0100697 final int credentialOwnerUserId = getCredentialOwnerProfile(userHandle);
Jeff Sharkeyce18c812016-04-27 16:00:41 -0600698 if (StorageManager.isUserKeyUnlocked(userHandle)
Ricky Wai7881cf82016-04-15 17:20:12 +0100699 || !mLockPatternUtils.isSecure(credentialOwnerUserId)) {
Benjamin Franzf02420c2016-04-04 18:52:21 +0100700 // if the user is already unlocked, no need to show a profile challenge
701 setQuietModeEnabled(userHandle, false);
702 return true;
703 }
704
705 long identity = Binder.clearCallingIdentity();
706 try {
707 // otherwise, we show a profile challenge to trigger decryption of the user
708 final KeyguardManager km = (KeyguardManager) mContext.getSystemService(
709 Context.KEYGUARD_SERVICE);
Ricky Wai7881cf82016-04-15 17:20:12 +0100710 // We should use userHandle not credentialOwnerUserId here, as even if it is unified
711 // lock, confirm screenlock page will know and show personal challenge, and unlock
712 // work profile when personal challenge is correct
Benjamin Franzf02420c2016-04-04 18:52:21 +0100713 final Intent unlockIntent = km.createConfirmDeviceCredentialIntent(null, null,
714 userHandle);
715 if (unlockIntent == null) {
716 return false;
717 }
718 if (target != null) {
719 unlockIntent.putExtra(Intent.EXTRA_INTENT, target);
720 }
721 unlockIntent.setFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
722 mContext.startActivity(unlockIntent);
723 } finally {
724 Binder.restoreCallingIdentity(identity);
725 }
726 return false;
727 }
728
729 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100730 public void setUserEnabled(int userId) {
731 checkManageUsersPermission("enable user");
732 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700733 UserInfo info;
734 synchronized (mUsersLock) {
735 info = getUserInfoLU(userId);
736 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100737 if (info != null && !info.isEnabled()) {
738 info.flags ^= UserInfo.FLAG_DISABLED;
Amith Yamasani12747872015-12-07 14:19:49 -0800739 writeUserLP(getUserDataLU(info.id));
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100740 }
741 }
742 }
743
744 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700745 public UserInfo getUserInfo(int userId) {
Tony Mak8673b282016-03-21 21:10:59 +0000746 checkManageUsersPermission("query user");
747 synchronized (mUsersLock) {
Amith Yamasani6f48d6e2016-03-23 14:28:25 -0700748 return userWithName(getUserInfoLU(userId));
749 }
750 }
751
752 /**
753 * Returns a UserInfo object with the name filled in, for Owner, or the original
754 * if the name is already set.
755 */
756 private UserInfo userWithName(UserInfo orig) {
757 if (orig != null && orig.name == null && orig.id == UserHandle.USER_SYSTEM) {
758 UserInfo withName = new UserInfo(orig);
759 withName.name = getOwnerName();
760 return withName;
761 } else {
762 return orig;
Tony Mak8673b282016-03-21 21:10:59 +0000763 }
764 }
765
766 @Override
767 public boolean isManagedProfile(int userId) {
Tony Makb531d082016-03-16 14:49:52 +0000768 int callingUserId = UserHandle.getCallingUserId();
769 if (callingUserId != userId && !hasManageUsersPermission()) {
770 synchronized (mPackagesLock) {
771 if (!isSameProfileGroupLP(callingUserId, userId)) {
772 throw new SecurityException(
Tony Mak8673b282016-03-21 21:10:59 +0000773 "You need MANAGE_USERS permission to: check if specified user a " +
774 "managed profile outside your profile group");
Tony Makb531d082016-03-16 14:49:52 +0000775 }
776 }
Tony Mak4dc008c2016-03-16 10:46:49 +0000777 }
Fyodor Kupolov82402752015-10-28 14:54:51 -0700778 synchronized (mUsersLock) {
Tony Mak8673b282016-03-21 21:10:59 +0000779 UserInfo userInfo = getUserInfoLU(userId);
780 return userInfo != null && userInfo.isManagedProfile();
Amith Yamasani13593602012-03-22 16:16:17 -0700781 }
782 }
783
Amith Yamasani71e6c692013-03-24 17:39:28 -0700784 @Override
785 public boolean isRestricted() {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700786 synchronized (mUsersLock) {
787 return getUserInfoLU(UserHandle.getCallingUserId()).isRestricted();
Amith Yamasani71e6c692013-03-24 17:39:28 -0700788 }
789 }
790
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700791 @Override
792 public boolean canHaveRestrictedProfile(int userId) {
793 checkManageUsersPermission("canHaveRestrictedProfile");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700794 synchronized (mUsersLock) {
795 final UserInfo userInfo = getUserInfoLU(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700796 if (userInfo == null || !userInfo.canHaveProfile()) {
797 return false;
798 }
799 if (!userInfo.isAdmin()) {
800 return false;
801 }
Makoto Onukie7927da2015-11-25 10:05:17 -0800802 // restricted profile can be created if there is no DO set and the admin user has no PO;
803 return !mIsDeviceManaged && !mIsUserManaged.get(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700804 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700805 }
806
Amith Yamasani195263742012-08-21 15:40:12 -0700807 /*
808 * Should be locked on mUsers before calling this.
809 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700810 private UserInfo getUserInfoLU(int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -0800811 final UserData userData = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -0700812 // If it is partial and not in the process of being removed, return as unknown user.
Amith Yamasani12747872015-12-07 14:19:49 -0800813 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700814 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
815 return null;
816 }
Amith Yamasani12747872015-12-07 14:19:49 -0800817 return userData != null ? userData.info : null;
818 }
819
820 private UserData getUserDataLU(int userId) {
821 final UserData userData = mUsers.get(userId);
822 // If it is partial and not in the process of being removed, return as unknown user.
823 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
824 return null;
825 }
826 return userData;
Amith Yamasani195263742012-08-21 15:40:12 -0700827 }
828
Fyodor Kupolov82402752015-10-28 14:54:51 -0700829 /**
830 * Obtains {@link #mUsersLock} and return UserInfo from mUsers.
831 * <p>No permissions checking or any addition checks are made</p>
832 */
833 private UserInfo getUserInfoNoChecks(int userId) {
834 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800835 final UserData userData = mUsers.get(userId);
836 return userData != null ? userData.info : null;
837 }
838 }
839
840 /**
841 * Obtains {@link #mUsersLock} and return UserData from mUsers.
842 * <p>No permissions checking or any addition checks are made</p>
843 */
844 private UserData getUserDataNoChecks(int userId) {
845 synchronized (mUsersLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700846 return mUsers.get(userId);
847 }
848 }
849
Amith Yamasani236b2b52015-08-18 14:32:14 -0700850 /** Called by PackageManagerService */
Amith Yamasani13593602012-03-22 16:16:17 -0700851 public boolean exists(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700852 return getUserInfoNoChecks(userId) != null;
Amith Yamasani13593602012-03-22 16:16:17 -0700853 }
854
Amith Yamasani258848d2012-08-10 17:06:33 -0700855 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700856 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700857 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700858 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700859 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800860 UserData userData = getUserDataNoChecks(userId);
861 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700862 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
863 return;
864 }
Amith Yamasani12747872015-12-07 14:19:49 -0800865 if (name != null && !name.equals(userData.info.name)) {
866 userData.info.name = name;
867 writeUserLP(userData);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700868 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -0700869 }
870 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700871 if (changed) {
872 sendUserInfoChangedBroadcast(userId);
873 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700874 }
875
Amith Yamasani258848d2012-08-10 17:06:33 -0700876 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700877 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700878 checkManageUsersPermission("update users");
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +0100879 if (hasUserRestriction(UserManager.DISALLOW_SET_USER_ICON, userId)) {
880 Log.w(LOG_TAG, "Cannot set user icon. DISALLOW_SET_USER_ICON is enabled.");
881 return;
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700882 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +0100883 mLocalService.setUserIcon(userId, bitmap);
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700884 }
885
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +0100886
887
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700888 private void sendUserInfoChangedBroadcast(int userId) {
889 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
890 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
891 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -0700892 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700893 }
894
Amith Yamasani258848d2012-08-10 17:06:33 -0700895 @Override
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +0100896 public ParcelFileDescriptor getUserIcon(int targetUserId) {
Adrian Roos1bdff912015-02-17 15:51:35 +0100897 String iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700898 synchronized (mPackagesLock) {
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +0100899 UserInfo targetUserInfo = getUserInfoNoChecks(targetUserId);
900 if (targetUserInfo == null || targetUserInfo.partial) {
901 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + targetUserId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700902 return null;
903 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +0100904
905 final int callingUserId = UserHandle.getCallingUserId();
906 final int callingGroupId = getUserInfoNoChecks(callingUserId).profileGroupId;
907 final int targetGroupId = targetUserInfo.profileGroupId;
908 final boolean sameGroup = (callingGroupId != UserInfo.NO_PROFILE_GROUP_ID
909 && callingGroupId == targetGroupId);
910 if ((callingUserId != targetUserId) && !sameGroup) {
Nicolas Prevot88cc3462014-05-14 14:51:48 +0100911 checkManageUsersPermission("get the icon of a user who is not related");
912 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +0100913
914 if (targetUserInfo.iconPath == null) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700915 return null;
916 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +0100917 iconPath = targetUserInfo.iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700918 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100919
920 try {
921 return ParcelFileDescriptor.open(
922 new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
923 } catch (FileNotFoundException e) {
924 Log.e(LOG_TAG, "Couldn't find icon file", e);
925 }
926 return null;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700927 }
928
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700929 public void makeInitialized(int userId) {
930 checkManageUsersPermission("makeInitialized");
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800931 boolean scheduleWriteUser = false;
Amith Yamasani12747872015-12-07 14:19:49 -0800932 UserData userData;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800933 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800934 userData = mUsers.get(userId);
935 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700936 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800937 return;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700938 }
Amith Yamasani12747872015-12-07 14:19:49 -0800939 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
940 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800941 scheduleWriteUser = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700942 }
943 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800944 if (scheduleWriteUser) {
Amith Yamasani12747872015-12-07 14:19:49 -0800945 scheduleWriteUser(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800946 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700947 }
948
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700949 /**
950 * If default guest restrictions haven't been initialized yet, add the basic
951 * restrictions.
952 */
953 private void initDefaultGuestRestrictions() {
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800954 synchronized (mGuestRestrictions) {
955 if (mGuestRestrictions.isEmpty()) {
Samuel Tand9453b82016-03-14 15:57:02 -0700956 mGuestRestrictions.putBoolean(UserManager.DISALLOW_CONFIG_WIFI, true);
Fyodor Kupolove04462c2015-11-30 15:02:53 -0800957 mGuestRestrictions.putBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, true);
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800958 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
959 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
960 }
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700961 }
962 }
963
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800964 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530965 public Bundle getDefaultGuestRestrictions() {
966 checkManageUsersPermission("getDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800967 synchronized (mGuestRestrictions) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530968 return new Bundle(mGuestRestrictions);
969 }
970 }
971
972 @Override
973 public void setDefaultGuestRestrictions(Bundle restrictions) {
974 checkManageUsersPermission("setDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800975 synchronized (mGuestRestrictions) {
976 mGuestRestrictions.clear();
977 mGuestRestrictions.putAll(restrictions);
978 }
979 synchronized (mPackagesLock) {
980 writeUserListLP();
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530981 }
982 }
983
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800984 /**
985 * See {@link UserManagerInternal#setDevicePolicyUserRestrictions(int, Bundle, Bundle)}
986 */
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800987 void setDevicePolicyUserRestrictionsInner(int userId, @NonNull Bundle local,
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800988 @Nullable Bundle global) {
989 Preconditions.checkNotNull(local);
990 boolean globalChanged = false;
991 boolean localChanged;
992 synchronized (mRestrictionsLock) {
993 if (global != null) {
994 // Update global.
995 globalChanged = !UserRestrictionsUtils.areEqual(
996 mDevicePolicyGlobalUserRestrictions, global);
997 if (globalChanged) {
998 mDevicePolicyGlobalUserRestrictions = global;
999 }
1000 }
1001 {
1002 // Update local.
1003 final Bundle prev = mDevicePolicyLocalUserRestrictions.get(userId);
1004 localChanged = !UserRestrictionsUtils.areEqual(prev, local);
1005 if (localChanged) {
1006 mDevicePolicyLocalUserRestrictions.put(userId, local);
1007 }
1008 }
1009 }
1010 if (DBG) {
1011 Log.d(LOG_TAG, "setDevicePolicyUserRestrictions: userId=" + userId
1012 + " global=" + global + (globalChanged ? " (changed)" : "")
1013 + " local=" + local + (localChanged ? " (changed)" : "")
1014 );
1015 }
1016 // Don't call them within the mRestrictionsLock.
1017 synchronized (mPackagesLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001018 if (localChanged) {
Amith Yamasani12747872015-12-07 14:19:49 -08001019 writeUserLP(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001020 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06001021 if (globalChanged) {
1022 writeUserListLP();
1023 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001024 }
1025
1026 synchronized (mRestrictionsLock) {
1027 if (globalChanged) {
1028 applyUserRestrictionsForAllUsersLR();
1029 } else if (localChanged) {
1030 applyUserRestrictionsLR(userId);
1031 }
1032 }
1033 }
1034
Makoto Onuki068c54a2015-10-13 14:34:03 -07001035 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001036 private Bundle computeEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001037 final Bundle baseRestrictions =
1038 UserRestrictionsUtils.nonNull(mBaseUserRestrictions.get(userId));
1039 final Bundle global = mDevicePolicyGlobalUserRestrictions;
1040 final Bundle local = mDevicePolicyLocalUserRestrictions.get(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001041
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001042 if (UserRestrictionsUtils.isEmpty(global) && UserRestrictionsUtils.isEmpty(local)) {
1043 // Common case first.
1044 return baseRestrictions;
Makoto Onuki068c54a2015-10-13 14:34:03 -07001045 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001046 final Bundle effective = UserRestrictionsUtils.clone(baseRestrictions);
1047 UserRestrictionsUtils.merge(effective, global);
1048 UserRestrictionsUtils.merge(effective, local);
1049
Makoto Onuki068c54a2015-10-13 14:34:03 -07001050 return effective;
1051 }
1052
1053 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001054 private void invalidateEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki068c54a2015-10-13 14:34:03 -07001055 if (DBG) {
1056 Log.d(LOG_TAG, "invalidateEffectiveUserRestrictions userId=" + userId);
1057 }
1058 mCachedEffectiveUserRestrictions.remove(userId);
1059 }
1060
1061 private Bundle getEffectiveUserRestrictions(int userId) {
1062 synchronized (mRestrictionsLock) {
1063 Bundle restrictions = mCachedEffectiveUserRestrictions.get(userId);
1064 if (restrictions == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001065 restrictions = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001066 mCachedEffectiveUserRestrictions.put(userId, restrictions);
1067 }
1068 return restrictions;
Amith Yamasani8cd28b52014-06-08 17:54:27 -07001069 }
1070 }
1071
Makoto Onuki068c54a2015-10-13 14:34:03 -07001072 /** @return a specific user restriction that's in effect currently. */
1073 @Override
1074 public boolean hasUserRestriction(String restrictionKey, int userId) {
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001075 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1076 return false;
1077 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001078 Bundle restrictions = getEffectiveUserRestrictions(userId);
1079 return restrictions != null && restrictions.getBoolean(restrictionKey);
1080 }
1081
1082 /**
1083 * @return UserRestrictions that are in effect currently. This always returns a new
1084 * {@link Bundle}.
1085 */
Amith Yamasani8cd28b52014-06-08 17:54:27 -07001086 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001087 public Bundle getUserRestrictions(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001088 return UserRestrictionsUtils.clone(getEffectiveUserRestrictions(userId));
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001089 }
1090
1091 @Override
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +00001092 public boolean hasBaseUserRestriction(String restrictionKey, int userId) {
1093 checkManageUsersPermission("hasBaseUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001094 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1095 return false;
1096 }
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +00001097 synchronized (mRestrictionsLock) {
1098 Bundle bundle = mBaseUserRestrictions.get(userId);
1099 return (bundle != null && bundle.getBoolean(restrictionKey, false));
1100 }
1101 }
1102
1103 @Override
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001104 public void setUserRestriction(String key, boolean value, int userId) {
Fyodor Kupolovd4b26042015-07-27 14:30:59 -07001105 checkManageUsersPermission("setUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001106 if (!UserRestrictionsUtils.isValidRestriction(key)) {
1107 return;
1108 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001109 synchronized (mRestrictionsLock) {
1110 // Note we can't modify Bundles stored in mBaseUserRestrictions directly, so create
1111 // a copy.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001112 final Bundle newRestrictions = UserRestrictionsUtils.clone(
1113 mBaseUserRestrictions.get(userId));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001114 newRestrictions.putBoolean(key, value);
1115
Fyodor Kupolov82402752015-10-28 14:54:51 -07001116 updateUserRestrictionsInternalLR(newRestrictions, userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001117 }
1118 }
1119
Makoto Onuki068c54a2015-10-13 14:34:03 -07001120 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001121 * Optionally updating user restrictions, calculate the effective user restrictions and also
1122 * propagate to other services and system settings.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001123 *
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001124 * @param newRestrictions User restrictions to set.
1125 * If null, will not update user restrictions and only does the propagation.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001126 * @param userId target user ID.
1127 */
1128 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001129 private void updateUserRestrictionsInternalLR(
Makoto Onuki068c54a2015-10-13 14:34:03 -07001130 @Nullable Bundle newRestrictions, int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001131
1132 final Bundle prevAppliedRestrictions = UserRestrictionsUtils.nonNull(
1133 mAppliedUserRestrictions.get(userId));
1134
1135 // Update base restrictions.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001136 if (newRestrictions != null) {
1137 // If newRestrictions == the current one, it's probably a bug.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001138 final Bundle prevBaseRestrictions = mBaseUserRestrictions.get(userId);
1139
1140 Preconditions.checkState(prevBaseRestrictions != newRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001141 Preconditions.checkState(mCachedEffectiveUserRestrictions.get(userId)
1142 != newRestrictions);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001143
1144 if (!UserRestrictionsUtils.areEqual(prevBaseRestrictions, newRestrictions)) {
1145 mBaseUserRestrictions.put(userId, newRestrictions);
Amith Yamasani12747872015-12-07 14:19:49 -08001146 scheduleWriteUser(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001147 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001148 }
1149
Fyodor Kupolov82402752015-10-28 14:54:51 -07001150 final Bundle effective = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001151
Makoto Onuki759a7632015-10-28 16:43:10 -07001152 mCachedEffectiveUserRestrictions.put(userId, effective);
1153
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001154 // Apply the new restrictions.
Makoto Onuki4f160732015-10-27 17:15:38 -07001155 if (DBG) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001156 debug("Applying user restrictions: userId=" + userId
1157 + " new=" + effective + " prev=" + prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001158 }
1159
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001160 if (mAppOpsService != null) { // We skip it until system-ready.
1161 final long token = Binder.clearCallingIdentity();
1162 try {
Svet Ganov9cea80cd2016-02-16 11:47:00 -08001163 mAppOpsService.setUserRestrictions(effective, mUserRestriconToken, userId);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001164 } catch (RemoteException e) {
1165 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
1166 } finally {
1167 Binder.restoreCallingIdentity(token);
1168 }
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001169 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001170
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001171 propagateUserRestrictionsLR(userId, effective, prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001172
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001173 mAppliedUserRestrictions.put(userId, new Bundle(effective));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001174 }
1175
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001176 private void propagateUserRestrictionsLR(final int userId,
Makoto Onukid45a4a22015-11-02 17:17:38 -08001177 Bundle newRestrictions, Bundle prevRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001178 // Note this method doesn't touch any state, meaning it doesn't require mRestrictionsLock
1179 // actually, but we still need some kind of synchronization otherwise we might end up
1180 // calling listeners out-of-order, thus "LR".
1181
1182 if (UserRestrictionsUtils.areEqual(newRestrictions, prevRestrictions)) {
1183 return;
1184 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08001185
1186 final Bundle newRestrictionsFinal = new Bundle(newRestrictions);
1187 final Bundle prevRestrictionsFinal = new Bundle(prevRestrictions);
1188
1189 mHandler.post(new Runnable() {
1190 @Override
1191 public void run() {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07001192 UserRestrictionsUtils.applyUserRestrictions(
1193 mContext, userId, newRestrictionsFinal, prevRestrictionsFinal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001194
Makoto Onukid45a4a22015-11-02 17:17:38 -08001195 final UserRestrictionsListener[] listeners;
1196 synchronized (mUserRestrictionsListeners) {
1197 listeners = new UserRestrictionsListener[mUserRestrictionsListeners.size()];
1198 mUserRestrictionsListeners.toArray(listeners);
1199 }
1200 for (int i = 0; i < listeners.length; i++) {
1201 listeners[i].onUserRestrictionsChanged(userId,
1202 newRestrictionsFinal, prevRestrictionsFinal);
1203 }
1204 }
1205 });
1206 }
1207
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001208 // Package private for the inner class.
1209 void applyUserRestrictionsLR(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001210 updateUserRestrictionsInternalLR(null, userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001211 }
1212
1213 @GuardedBy("mRestrictionsLock")
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001214 // Package private for the inner class.
1215 void applyUserRestrictionsForAllUsersLR() {
1216 if (DBG) {
1217 debug("applyUserRestrictionsForAllUsersLR");
1218 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001219 // First, invalidate all cached values.
Makoto Onuki4f160732015-10-27 17:15:38 -07001220 mCachedEffectiveUserRestrictions.clear();
1221
Makoto Onuki068c54a2015-10-13 14:34:03 -07001222 // We don't want to call into ActivityManagerNative while taking a lock, so we'll call
1223 // it on a handler.
1224 final Runnable r = new Runnable() {
1225 @Override
1226 public void run() {
1227 // Then get the list of running users.
1228 final int[] runningUsers;
1229 try {
1230 runningUsers = ActivityManagerNative.getDefault().getRunningUserIds();
1231 } catch (RemoteException e) {
1232 Log.w(LOG_TAG, "Unable to access ActivityManagerNative");
1233 return;
1234 }
1235 // Then re-calculate the effective restrictions and apply, only for running users.
1236 // It's okay if a new user has started after the getRunningUserIds() call,
1237 // because we'll do the same thing (re-calculate the restrictions and apply)
1238 // when we start a user.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001239 synchronized (mRestrictionsLock) {
1240 for (int i = 0; i < runningUsers.length; i++) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001241 applyUserRestrictionsLR(runningUsers[i]);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001242 }
1243 }
1244 }
1245 };
1246 mHandler.post(r);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001247 }
1248
Amith Yamasani258848d2012-08-10 17:06:33 -07001249 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001250 * Check if we've hit the limit of how many users can be created.
1251 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001252 private boolean isUserLimitReached() {
1253 int count;
1254 synchronized (mUsersLock) {
1255 count = getAliveUsersExcludingGuestsCountLU();
1256 }
1257 return count >= UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001258 }
1259
1260 @Override
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001261 public boolean canAddMoreManagedProfiles(int userId, boolean allowedToRemoveOne) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001262 checkManageUsersPermission("check if more managed profiles can be added.");
1263 if (ActivityManager.isLowRamDeviceStatic()) {
1264 return false;
1265 }
Fyodor Kupolovb6157992015-06-05 15:32:28 -07001266 if (!mContext.getPackageManager().hasSystemFeature(
1267 PackageManager.FEATURE_MANAGED_USERS)) {
1268 return false;
1269 }
Nicolas Prevotb8186812015-08-06 15:00:03 +01001270 // Limit number of managed profiles that can be created
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001271 final int managedProfilesCount = getProfiles(userId, true).size() - 1;
1272 final int profilesRemovedCount = managedProfilesCount > 0 && allowedToRemoveOne ? 1 : 0;
1273 if (managedProfilesCount - profilesRemovedCount >= MAX_MANAGED_PROFILES) {
Nicolas Prevotb8186812015-08-06 15:00:03 +01001274 return false;
1275 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001276 synchronized(mUsersLock) {
1277 UserInfo userInfo = getUserInfoLU(userId);
Nicolas Prevotb8186812015-08-06 15:00:03 +01001278 if (!userInfo.canHaveProfile()) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001279 return false;
1280 }
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001281 int usersCountAfterRemoving = getAliveUsersExcludingGuestsCountLU()
1282 - profilesRemovedCount;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001283 // We allow creating a managed profile in the special case where there is only one user.
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001284 return usersCountAfterRemoving == 1
1285 || usersCountAfterRemoving < UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001286 }
1287 }
1288
Fyodor Kupolov82402752015-10-28 14:54:51 -07001289 private int getAliveUsersExcludingGuestsCountLU() {
Amith Yamasanif584f012014-05-19 17:57:25 -07001290 int aliveUserCount = 0;
1291 final int totalUserCount = mUsers.size();
1292 // Skip over users being removed
1293 for (int i = 0; i < totalUserCount; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001294 UserInfo user = mUsers.valueAt(i).info;
Amith Yamasani95ab7842014-08-11 17:09:26 -07001295 if (!mRemovingUserIds.get(user.id)
Amith Yamasani1df14732014-08-29 21:37:27 -07001296 && !user.isGuest() && !user.partial) {
Amith Yamasanif584f012014-05-19 17:57:25 -07001297 aliveUserCount++;
1298 }
1299 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001300 return aliveUserCount;
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001301 }
1302
1303 /**
Amith Yamasani195263742012-08-21 15:40:12 -07001304 * Enforces that only the system UID or root's UID or apps that have the
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001305 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} and
1306 * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL INTERACT_ACROSS_USERS_FULL}
1307 * permissions can make certain calls to the UserManager.
1308 *
1309 * @param message used as message if SecurityException is thrown
1310 * @throws SecurityException if the caller does not have enough privilege.
1311 */
1312 private static final void checkManageUserAndAcrossUsersFullPermission(String message) {
1313 final int uid = Binder.getCallingUid();
1314 if (uid != Process.SYSTEM_UID && uid != 0
1315 && ActivityManager.checkComponentPermission(
1316 Manifest.permission.MANAGE_USERS,
1317 uid, -1, true) != PackageManager.PERMISSION_GRANTED
1318 && ActivityManager.checkComponentPermission(
1319 Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1320 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
1321 throw new SecurityException(
1322 "You need MANAGE_USERS and INTERACT_ACROSS_USERS_FULL permission to: "
1323 + message);
1324 }
1325 }
1326
1327 /**
1328 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001329 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -07001330 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -07001331 *
1332 * @param message used as message if SecurityException is thrown
1333 * @throws SecurityException if the caller is not system or root
Tony Mak4dc008c2016-03-16 10:46:49 +00001334 * @see #hasManageUsersPermission()
Amith Yamasani258848d2012-08-10 17:06:33 -07001335 */
Amith Yamasanibe465322014-04-24 13:45:17 -07001336 private static final void checkManageUsersPermission(String message) {
Tony Mak4dc008c2016-03-16 10:46:49 +00001337 if (!hasManageUsersPermission()) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001338 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
1339 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -04001340 }
1341
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001342 /**
Tony Mak4dc008c2016-03-16 10:46:49 +00001343 * @return whether the calling UID is system UID or root's UID or the calling app has the
1344 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}.
1345 */
1346 private static final boolean hasManageUsersPermission() {
1347 final int callingUid = Binder.getCallingUid();
1348 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
1349 || callingUid == Process.ROOT_UID
1350 || ActivityManager.checkComponentPermission(
1351 android.Manifest.permission.MANAGE_USERS,
1352 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED;
1353 }
1354
1355 /**
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001356 * Enforces that only the system UID or root's UID (on any user) can make certain calls to the
1357 * UserManager.
1358 *
1359 * @param message used as message if SecurityException is thrown
1360 * @throws SecurityException if the caller is not system or root
1361 */
1362 private static void checkSystemOrRoot(String message) {
1363 final int uid = Binder.getCallingUid();
1364 if (!UserHandle.isSameApp(uid, Process.SYSTEM_UID) && uid != Process.ROOT_UID) {
1365 throw new SecurityException("Only system may: " + message);
1366 }
1367 }
1368
Fyodor Kupolov82402752015-10-28 14:54:51 -07001369 private void writeBitmapLP(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001370 try {
1371 File dir = new File(mUsersDir, Integer.toString(info.id));
1372 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +01001373 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001374 if (!dir.exists()) {
1375 dir.mkdir();
1376 FileUtils.setPermissions(
1377 dir.getPath(),
1378 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
1379 -1, -1);
1380 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001381 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +01001382 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001383 && tmp.renameTo(file) && SELinux.restorecon(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -07001384 info.iconPath = file.getAbsolutePath();
1385 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001386 try {
1387 os.close();
1388 } catch (IOException ioe) {
1389 // What the ... !
1390 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001391 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001392 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001393 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001394 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001395 }
1396
Amith Yamasani0b285492011-04-14 17:35:23 -07001397 /**
1398 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
1399 * cache it elsewhere.
1400 * @return the array of user ids.
1401 */
Dianne Hackborn1676c852012-09-10 14:52:30 -07001402 public int[] getUserIds() {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001403 synchronized (mUsersLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001404 return mUserIds;
1405 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001406 }
1407
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001408 private void readUserListLP() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001409 if (!mUserListFile.exists()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001410 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001411 return;
1412 }
1413 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001414 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001415 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001416 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001417 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001418 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001419 int type;
1420 while ((type = parser.next()) != XmlPullParser.START_TAG
1421 && type != XmlPullParser.END_DOCUMENT) {
Amith Yamasani12747872015-12-07 14:19:49 -08001422 // Skip
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001423 }
1424
1425 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001426 Slog.e(LOG_TAG, "Unable to read user list");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001427 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001428 return;
1429 }
1430
Amith Yamasani2a003292012-08-14 18:25:45 -07001431 mNextSerialNumber = -1;
1432 if (parser.getName().equals(TAG_USERS)) {
1433 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
1434 if (lastSerialNumber != null) {
1435 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
1436 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001437 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
1438 if (versionNumber != null) {
1439 mUserVersion = Integer.parseInt(versionNumber);
1440 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001441 }
1442
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001443 final Bundle newDevicePolicyGlobalUserRestrictions = new Bundle();
1444
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001445 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301446 if (type == XmlPullParser.START_TAG) {
1447 final String name = parser.getName();
1448 if (name.equals(TAG_USER)) {
1449 String id = parser.getAttributeValue(null, ATTR_ID);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001450
Amith Yamasani12747872015-12-07 14:19:49 -08001451 UserData userData = readUserLP(Integer.parseInt(id));
1452
1453 if (userData != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001454 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001455 mUsers.put(userData.info.id, userData);
1456 if (mNextSerialNumber < 0
1457 || mNextSerialNumber <= userData.info.id) {
1458 mNextSerialNumber = userData.info.id + 1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001459 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301460 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001461 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301462 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -08001463 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1464 && type != XmlPullParser.END_TAG) {
1465 if (type == XmlPullParser.START_TAG) {
1466 if (parser.getName().equals(TAG_RESTRICTIONS)) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001467 synchronized (mGuestRestrictions) {
1468 UserRestrictionsUtils
1469 .readRestrictions(parser, mGuestRestrictions);
1470 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001471 } else if (parser.getName().equals(TAG_DEVICE_POLICY_RESTRICTIONS)
1472 ) {
1473 UserRestrictionsUtils.readRestrictions(parser,
1474 newDevicePolicyGlobalUserRestrictions);
Amith Yamasanida0b1682014-11-21 12:58:17 -08001475 }
1476 break;
1477 }
1478 }
Amith Yamasani258848d2012-08-10 17:06:33 -07001479 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001480 }
1481 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001482 synchronized (mRestrictionsLock) {
1483 mDevicePolicyGlobalUserRestrictions = newDevicePolicyGlobalUserRestrictions;
1484 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001485 updateUserIds();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001486 upgradeIfNecessaryLP();
1487 } catch (IOException | XmlPullParserException e) {
1488 fallbackToSingleUserLP();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001489 } finally {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001490 IoUtils.closeQuietly(fis);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001491 }
1492 }
1493
Amith Yamasani6f34b412012-10-22 18:19:27 -07001494 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -08001495 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -07001496 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001497 private void upgradeIfNecessaryLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001498 final int originalVersion = mUserVersion;
Amith Yamasani6f34b412012-10-22 18:19:27 -07001499 int userVersion = mUserVersion;
1500 if (userVersion < 1) {
1501 // Assign a proper name for the owner, if not initialized correctly before
Amith Yamasani12747872015-12-07 14:19:49 -08001502 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
1503 if ("Primary".equals(userData.info.name)) {
1504 userData.info.name =
1505 mContext.getResources().getString(com.android.internal.R.string.owner_name);
1506 scheduleWriteUser(userData);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001507 }
1508 userVersion = 1;
1509 }
1510
Amith Yamasanibc9625052012-11-15 14:39:18 -08001511 if (userVersion < 2) {
1512 // Owner should be marked as initialized
Amith Yamasani12747872015-12-07 14:19:49 -08001513 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
1514 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1515 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
1516 scheduleWriteUser(userData);
Amith Yamasanibc9625052012-11-15 14:39:18 -08001517 }
1518 userVersion = 2;
1519 }
1520
Amith Yamasani350962c2013-08-06 11:18:53 -07001521
Amith Yamasani5e486f52013-08-07 11:06:44 -07001522 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -07001523 userVersion = 4;
1524 }
1525
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001526 if (userVersion < 5) {
1527 initDefaultGuestRestrictions();
1528 userVersion = 5;
1529 }
1530
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001531 if (userVersion < 6) {
1532 final boolean splitSystemUser = UserManager.isSplitSystemUser();
Fyodor Kupolov82402752015-10-28 14:54:51 -07001533 synchronized (mUsersLock) {
1534 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001535 UserData userData = mUsers.valueAt(i);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001536 // In non-split mode, only user 0 can have restricted profiles
Amith Yamasani12747872015-12-07 14:19:49 -08001537 if (!splitSystemUser && userData.info.isRestricted()
1538 && (userData.info.restrictedProfileParentId
1539 == UserInfo.NO_PROFILE_GROUP_ID)) {
1540 userData.info.restrictedProfileParentId = UserHandle.USER_SYSTEM;
1541 scheduleWriteUser(userData);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001542 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001543 }
1544 }
1545 userVersion = 6;
1546 }
1547
Amith Yamasani6f34b412012-10-22 18:19:27 -07001548 if (userVersion < USER_VERSION) {
1549 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
1550 + USER_VERSION);
1551 } else {
1552 mUserVersion = userVersion;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001553
1554 if (originalVersion < mUserVersion) {
1555 writeUserListLP();
1556 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001557 }
1558 }
1559
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001560 private void fallbackToSingleUserLP() {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001561 int flags = UserInfo.FLAG_INITIALIZED;
1562 // In split system user mode, the admin and primary flags are assigned to the first human
1563 // user.
1564 if (!UserManager.isSplitSystemUser()) {
1565 flags |= UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY;
1566 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001567 // Create the system user
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001568 UserInfo system = new UserInfo(UserHandle.USER_SYSTEM, null, null, flags);
Amith Yamasani12747872015-12-07 14:19:49 -08001569 UserData userData = new UserData();
1570 userData.info = system;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001571 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001572 mUsers.put(system.id, userData);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001573 }
Amith Yamasani634cf312012-10-04 17:34:21 -07001574 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -04001575 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -08001576
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001577 Bundle restrictions = new Bundle();
Makoto Onuki068c54a2015-10-13 14:34:03 -07001578 synchronized (mRestrictionsLock) {
1579 mBaseUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions);
1580 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001581
Fyodor Kupolov82402752015-10-28 14:54:51 -07001582 updateUserIds();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001583 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001584
Amith Yamasani12747872015-12-07 14:19:49 -08001585 writeUserLP(userData);
Jeff Sharkeycd575992016-03-29 14:12:49 -06001586 writeUserListLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001587 }
1588
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001589 private String getOwnerName() {
1590 return mContext.getResources().getString(com.android.internal.R.string.owner_name);
1591 }
1592
Amith Yamasani12747872015-12-07 14:19:49 -08001593 private void scheduleWriteUser(UserData UserData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001594 if (DBG) {
1595 debug("scheduleWriteUser");
1596 }
Makoto Onuki9e935a32015-11-06 14:24:24 -08001597 // No need to wrap it within a lock -- worst case, we'll just post the same message
1598 // twice.
Amith Yamasani12747872015-12-07 14:19:49 -08001599 if (!mHandler.hasMessages(WRITE_USER_MSG, UserData)) {
1600 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, UserData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001601 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
1602 }
1603 }
1604
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001605 /*
1606 * Writes the user file in this format:
1607 *
1608 * <user flags="20039023" id="0">
1609 * <name>Primary</name>
1610 * </user>
1611 */
Amith Yamasani12747872015-12-07 14:19:49 -08001612 private void writeUserLP(UserData userData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001613 if (DBG) {
Amith Yamasani12747872015-12-07 14:19:49 -08001614 debug("writeUserLP " + userData);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001615 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001616 FileOutputStream fos = null;
Amith Yamasani12747872015-12-07 14:19:49 -08001617 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userData.info.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001618 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001619 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001620 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1621
1622 // XmlSerializer serializer = XmlUtils.serializerInstance();
1623 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001624 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001625 serializer.startDocument(null, true);
1626 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1627
Amith Yamasani12747872015-12-07 14:19:49 -08001628 final UserInfo userInfo = userData.info;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001629 serializer.startTag(null, TAG_USER);
1630 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
Amith Yamasani2a003292012-08-14 18:25:45 -07001631 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001632 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Amith Yamasani920ace02012-09-20 22:15:37 -07001633 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
1634 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
1635 Long.toString(userInfo.lastLoggedInTime));
Jeff Sharkeycd575992016-03-29 14:12:49 -06001636 if (userInfo.lastLoggedInFingerprint != null) {
1637 serializer.attribute(null, ATTR_LAST_LOGGED_IN_FINGERPRINT,
1638 userInfo.lastLoggedInFingerprint);
1639 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001640 if (userInfo.iconPath != null) {
1641 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
1642 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001643 if (userInfo.partial) {
1644 serializer.attribute(null, ATTR_PARTIAL, "true");
1645 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001646 if (userInfo.guestToRemove) {
1647 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
1648 }
Kenny Guy2a764942014-04-02 13:29:20 +01001649 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
1650 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
1651 Integer.toString(userInfo.profileGroupId));
Kenny Guya52dc3e2014-02-11 15:33:14 +00001652 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001653 if (userInfo.restrictedProfileParentId != UserInfo.NO_PROFILE_GROUP_ID) {
1654 serializer.attribute(null, ATTR_RESTRICTED_PROFILE_PARENT_ID,
1655 Integer.toString(userInfo.restrictedProfileParentId));
1656 }
Amith Yamasani12747872015-12-07 14:19:49 -08001657 // Write seed data
1658 if (userData.persistSeedData) {
1659 if (userData.seedAccountName != null) {
1660 serializer.attribute(null, ATTR_SEED_ACCOUNT_NAME, userData.seedAccountName);
1661 }
1662 if (userData.seedAccountType != null) {
1663 serializer.attribute(null, ATTR_SEED_ACCOUNT_TYPE, userData.seedAccountType);
1664 }
1665 }
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001666 if (userInfo.name != null) {
1667 serializer.startTag(null, TAG_NAME);
1668 serializer.text(userInfo.name);
1669 serializer.endTag(null, TAG_NAME);
1670 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001671 synchronized (mRestrictionsLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001672 UserRestrictionsUtils.writeRestrictions(serializer,
1673 mBaseUserRestrictions.get(userInfo.id), TAG_RESTRICTIONS);
1674 UserRestrictionsUtils.writeRestrictions(serializer,
1675 mDevicePolicyLocalUserRestrictions.get(userInfo.id),
1676 TAG_DEVICE_POLICY_RESTRICTIONS);
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001677 }
Amith Yamasani12747872015-12-07 14:19:49 -08001678
1679 if (userData.account != null) {
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001680 serializer.startTag(null, TAG_ACCOUNT);
Amith Yamasani12747872015-12-07 14:19:49 -08001681 serializer.text(userData.account);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001682 serializer.endTag(null, TAG_ACCOUNT);
1683 }
1684
Amith Yamasani12747872015-12-07 14:19:49 -08001685 if (userData.persistSeedData && userData.seedAccountOptions != null) {
1686 serializer.startTag(null, TAG_SEED_ACCOUNT_OPTIONS);
1687 userData.seedAccountOptions.saveToXml(serializer);
1688 serializer.endTag(null, TAG_SEED_ACCOUNT_OPTIONS);
1689 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001690 serializer.endTag(null, TAG_USER);
1691
1692 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001693 userFile.finishWrite(fos);
1694 } catch (Exception ioe) {
Jeff Sharkeycd575992016-03-29 14:12:49 -06001695 Slog.e(LOG_TAG, "Error writing user info " + userData.info.id, ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -07001696 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001697 }
1698 }
1699
1700 /*
1701 * Writes the user list file in this format:
1702 *
Amith Yamasani2a003292012-08-14 18:25:45 -07001703 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001704 * <user id="0"></user>
1705 * <user id="2"></user>
1706 * </users>
1707 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001708 private void writeUserListLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001709 if (DBG) {
1710 debug("writeUserList");
1711 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001712 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001713 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001714 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001715 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001716 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1717
1718 // XmlSerializer serializer = XmlUtils.serializerInstance();
1719 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001720 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001721 serializer.startDocument(null, true);
1722 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1723
1724 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -07001725 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -07001726 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001727
Adam Lesinskieddeb492014-09-08 17:50:03 -07001728 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001729 synchronized (mGuestRestrictions) {
1730 UserRestrictionsUtils
1731 .writeRestrictions(serializer, mGuestRestrictions, TAG_RESTRICTIONS);
1732 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301733 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001734 synchronized (mRestrictionsLock) {
1735 UserRestrictionsUtils.writeRestrictions(serializer,
1736 mDevicePolicyGlobalUserRestrictions, TAG_DEVICE_POLICY_RESTRICTIONS);
1737 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001738 int[] userIdsToWrite;
1739 synchronized (mUsersLock) {
1740 userIdsToWrite = new int[mUsers.size()];
1741 for (int i = 0; i < userIdsToWrite.length; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001742 UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001743 userIdsToWrite[i] = user.id;
1744 }
1745 }
1746 for (int id : userIdsToWrite) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001747 serializer.startTag(null, TAG_USER);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001748 serializer.attribute(null, ATTR_ID, Integer.toString(id));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001749 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001750 }
1751
1752 serializer.endTag(null, TAG_USERS);
1753
1754 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001755 userListFile.finishWrite(fos);
1756 } catch (Exception e) {
1757 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -07001758 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001759 }
1760 }
1761
Amith Yamasani12747872015-12-07 14:19:49 -08001762 private UserData readUserLP(int id) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001763 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -07001764 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001765 String name = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001766 String account = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001767 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -07001768 long creationTime = 0L;
1769 long lastLoggedInTime = 0L;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06001770 String lastLoggedInFingerprint = null;
Kenny Guy2a764942014-04-02 13:29:20 +01001771 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001772 int restrictedProfileParentId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001773 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001774 boolean guestToRemove = false;
Amith Yamasani12747872015-12-07 14:19:49 -08001775 boolean persistSeedData = false;
1776 String seedAccountName = null;
1777 String seedAccountType = null;
1778 PersistableBundle seedAccountOptions = null;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001779 Bundle baseRestrictions = new Bundle();
1780 Bundle localRestrictions = new Bundle();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001781
1782 FileInputStream fis = null;
1783 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001784 AtomicFile userFile =
Amith Yamasanifc95e702013-09-26 13:20:17 -07001785 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
Amith Yamasani2a003292012-08-14 18:25:45 -07001786 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001787 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001788 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001789 int type;
1790 while ((type = parser.next()) != XmlPullParser.START_TAG
1791 && type != XmlPullParser.END_DOCUMENT) {
Amith Yamasani12747872015-12-07 14:19:49 -08001792 // Skip
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001793 }
1794
1795 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001796 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001797 return null;
1798 }
1799
1800 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001801 int storedId = readIntAttribute(parser, ATTR_ID, -1);
1802 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001803 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001804 return null;
1805 }
Amith Yamasani920ace02012-09-20 22:15:37 -07001806 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
1807 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001808 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -07001809 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
1810 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06001811 lastLoggedInFingerprint = parser.getAttributeValue(null,
1812 ATTR_LAST_LOGGED_IN_FINGERPRINT);
Kenny Guy2a764942014-04-02 13:29:20 +01001813 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
1814 UserInfo.NO_PROFILE_GROUP_ID);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001815 restrictedProfileParentId = readIntAttribute(parser,
1816 ATTR_RESTRICTED_PROFILE_PARENT_ID, UserInfo.NO_PROFILE_GROUP_ID);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001817 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
1818 if ("true".equals(valueString)) {
1819 partial = true;
1820 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001821 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
1822 if ("true".equals(valueString)) {
1823 guestToRemove = true;
1824 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001825
Amith Yamasani12747872015-12-07 14:19:49 -08001826 seedAccountName = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_NAME);
1827 seedAccountType = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_TYPE);
1828 if (seedAccountName != null || seedAccountType != null) {
1829 persistSeedData = true;
1830 }
1831
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001832 int outerDepth = parser.getDepth();
1833 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1834 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1835 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1836 continue;
1837 }
1838 String tag = parser.getName();
1839 if (TAG_NAME.equals(tag)) {
1840 type = parser.next();
1841 if (type == XmlPullParser.TEXT) {
1842 name = parser.getText();
1843 }
1844 } else if (TAG_RESTRICTIONS.equals(tag)) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001845 UserRestrictionsUtils.readRestrictions(parser, baseRestrictions);
1846 } else if (TAG_DEVICE_POLICY_RESTRICTIONS.equals(tag)) {
1847 UserRestrictionsUtils.readRestrictions(parser, localRestrictions);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001848 } else if (TAG_ACCOUNT.equals(tag)) {
1849 type = parser.next();
1850 if (type == XmlPullParser.TEXT) {
1851 account = parser.getText();
1852 }
Amith Yamasani12747872015-12-07 14:19:49 -08001853 } else if (TAG_SEED_ACCOUNT_OPTIONS.equals(tag)) {
1854 seedAccountOptions = PersistableBundle.restoreFromXml(parser);
1855 persistSeedData = true;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001856 }
1857 }
1858 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001859
Amith Yamasani12747872015-12-07 14:19:49 -08001860 // Create the UserInfo object that gets passed around
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001861 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -07001862 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -07001863 userInfo.creationTime = creationTime;
1864 userInfo.lastLoggedInTime = lastLoggedInTime;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06001865 userInfo.lastLoggedInFingerprint = lastLoggedInFingerprint;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001866 userInfo.partial = partial;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001867 userInfo.guestToRemove = guestToRemove;
Kenny Guy2a764942014-04-02 13:29:20 +01001868 userInfo.profileGroupId = profileGroupId;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001869 userInfo.restrictedProfileParentId = restrictedProfileParentId;
Amith Yamasani12747872015-12-07 14:19:49 -08001870
1871 // Create the UserData object that's internal to this class
1872 UserData userData = new UserData();
1873 userData.info = userInfo;
1874 userData.account = account;
1875 userData.seedAccountName = seedAccountName;
1876 userData.seedAccountType = seedAccountType;
1877 userData.persistSeedData = persistSeedData;
1878 userData.seedAccountOptions = seedAccountOptions;
1879
Makoto Onuki068c54a2015-10-13 14:34:03 -07001880 synchronized (mRestrictionsLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001881 mBaseUserRestrictions.put(id, baseRestrictions);
1882 mDevicePolicyLocalUserRestrictions.put(id, localRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001883 }
Amith Yamasani12747872015-12-07 14:19:49 -08001884 return userData;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001885 } catch (IOException ioe) {
1886 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001887 } finally {
1888 if (fis != null) {
1889 try {
1890 fis.close();
1891 } catch (IOException e) {
1892 }
1893 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001894 }
1895 return null;
1896 }
1897
Amith Yamasani920ace02012-09-20 22:15:37 -07001898 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
1899 String valueString = parser.getAttributeValue(null, attr);
1900 if (valueString == null) return defaultValue;
1901 try {
1902 return Integer.parseInt(valueString);
1903 } catch (NumberFormatException nfe) {
1904 return defaultValue;
1905 }
1906 }
1907
1908 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
1909 String valueString = parser.getAttributeValue(null, attr);
1910 if (valueString == null) return defaultValue;
1911 try {
1912 return Long.parseLong(valueString);
1913 } catch (NumberFormatException nfe) {
1914 return defaultValue;
1915 }
1916 }
1917
Amith Yamasanib82add22013-07-09 11:24:44 -07001918 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001919 * Removes the app restrictions file for a specific package and user id, if it exists.
1920 */
1921 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
1922 synchronized (mPackagesLock) {
1923 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07001924 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001925 if (resFile.exists()) {
1926 resFile.delete();
1927 }
1928 }
1929 }
1930
Kenny Guya52dc3e2014-02-11 15:33:14 +00001931 @Override
Kenny Guy2a764942014-04-02 13:29:20 +01001932 public UserInfo createProfileForUser(String name, int flags, int userId) {
Kenny Guya52dc3e2014-02-11 15:33:14 +00001933 checkManageUsersPermission("Only the system can create users");
Kenny Guy2a764942014-04-02 13:29:20 +01001934 return createUserInternal(name, flags, userId);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001935 }
1936
Amith Yamasani258848d2012-08-10 17:06:33 -07001937 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07001938 public UserInfo createUser(String name, int flags) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001939 checkManageUsersPermission("Only the system can create users");
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001940 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001941 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001942
Jessica Hummelbe81c802014-04-22 15:49:22 +01001943 private UserInfo createUserInternal(String name, int flags, int parentId) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001944 if (hasUserRestriction(UserManager.DISALLOW_ADD_USER, UserHandle.getCallingUserId())) {
Julia Reynolds75175022014-06-26 16:35:00 -04001945 Log.w(LOG_TAG, "Cannot add user. DISALLOW_ADD_USER is enabled.");
1946 return null;
1947 }
phweisse9c44062016-02-10 12:57:38 +01001948 return createUserInternalUnchecked(name, flags, parentId);
1949 }
1950
1951 private UserInfo createUserInternalUnchecked(String name, int flags, int parentId) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001952 if (ActivityManager.isLowRamDeviceStatic()) {
1953 return null;
1954 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07001955 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001956 final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001957 final boolean isRestricted = (flags & UserInfo.FLAG_RESTRICTED) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001958 final long ident = Binder.clearCallingIdentity();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001959 UserInfo userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08001960 UserData userData;
Amith Yamasanibb054c92015-07-09 14:16:27 -07001961 final int userId;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001962 try {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001963 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001964 UserData parent = null;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001965 if (parentId != UserHandle.USER_NULL) {
1966 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001967 parent = getUserDataLU(parentId);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001968 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001969 if (parent == null) return null;
1970 }
1971 if (isManagedProfile && !canAddMoreManagedProfiles(parentId, false)) {
1972 Log.e(LOG_TAG, "Cannot add more managed profiles for user " + parentId);
1973 return null;
1974 }
1975 if (!isGuest && !isManagedProfile && isUserLimitReached()) {
1976 // If we're not adding a guest user or a managed profile and the limit has
1977 // been reached, cannot add a user.
1978 return null;
1979 }
1980 // If we're adding a guest and there already exists one, bail.
1981 if (isGuest && findCurrentGuestUser() != null) {
1982 return null;
1983 }
1984 // In legacy mode, restricted profile's parent can only be the owner user
1985 if (isRestricted && !UserManager.isSplitSystemUser()
1986 && (parentId != UserHandle.USER_SYSTEM)) {
1987 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
1988 return null;
1989 }
1990 if (isRestricted && UserManager.isSplitSystemUser()) {
1991 if (parent == null) {
1992 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be "
1993 + "specified");
Nicolas Prevot12678a92015-05-13 12:15:03 -07001994 return null;
1995 }
Amith Yamasani12747872015-12-07 14:19:49 -08001996 if (!parent.info.canHaveProfile()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001997 Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be "
1998 + "created for the specified parent user id " + parentId);
Amith Yamasani95ab7842014-08-11 17:09:26 -07001999 return null;
2000 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002001 }
Lenka Trochtova024f9792016-02-17 13:55:17 +01002002 if (!UserManager.isSplitSystemUser() && (flags & UserInfo.FLAG_EPHEMERAL) != 0) {
2003 Log.e(LOG_TAG,
2004 "Ephemeral users are supported on split-system-user systems only.");
2005 return null;
2006 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002007 // In split system user mode, we assign the first human user the primary flag.
2008 // And if there is no device owner, we also assign the admin flag to primary user.
2009 if (UserManager.isSplitSystemUser()
2010 && !isGuest && !isManagedProfile && getPrimaryUser() == null) {
2011 flags |= UserInfo.FLAG_PRIMARY;
Makoto Onukie7927da2015-11-25 10:05:17 -08002012 synchronized (mUsersLock) {
2013 if (!mIsDeviceManaged) {
2014 flags |= UserInfo.FLAG_ADMIN;
2015 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07002016 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002017 }
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002018
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002019 userId = getNextAvailableId();
2020 Environment.getUserSystemDirectory(userId).mkdirs();
Lenka Trochtova02fee152015-12-22 14:26:18 +01002021 boolean ephemeralGuests = Resources.getSystem()
2022 .getBoolean(com.android.internal.R.bool.config_guestUserEphemeral);
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002023
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002024 synchronized (mUsersLock) {
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002025 // Add ephemeral flag to guests/users if required. Also inherit it from parent.
2026 if ((isGuest && ephemeralGuests) || mForceEphemeralUsers
2027 || (parent != null && parent.info.isEphemeral())) {
2028 flags |= UserInfo.FLAG_EPHEMERAL;
2029 }
2030
2031 userInfo = new UserInfo(userId, name, null, flags);
2032 userInfo.serialNumber = mNextSerialNumber++;
2033 long now = System.currentTimeMillis();
2034 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
2035 userInfo.partial = true;
Fyodor Kupolov83c24242016-03-31 13:30:42 -07002036 userInfo.lastLoggedInFingerprint = Build.FINGERPRINT;
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002037 userData = new UserData();
2038 userData.info = userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08002039 mUsers.put(userId, userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002040 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06002041 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002042 writeUserListLP();
2043 if (parent != null) {
2044 if (isManagedProfile) {
Amith Yamasani12747872015-12-07 14:19:49 -08002045 if (parent.info.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
2046 parent.info.profileGroupId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002047 writeUserLP(parent);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002048 }
Amith Yamasani12747872015-12-07 14:19:49 -08002049 userInfo.profileGroupId = parent.info.profileGroupId;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002050 } else if (isRestricted) {
Amith Yamasani12747872015-12-07 14:19:49 -08002051 if (parent.info.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) {
2052 parent.info.restrictedProfileParentId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002053 writeUserLP(parent);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002054 }
Amith Yamasani12747872015-12-07 14:19:49 -08002055 userInfo.restrictedProfileParentId = parent.info.restrictedProfileParentId;
Makoto Onuki068c54a2015-10-13 14:34:03 -07002056 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002057 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07002058 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002059 final StorageManager storage = mContext.getSystemService(StorageManager.class);
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002060 storage.createUserKey(userId, userInfo.serialNumber, userInfo.isEphemeral());
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002061 mPm.prepareUserData(userId, userInfo.serialNumber,
Jeff Sharkey47f71082016-02-01 17:03:54 -07002062 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002063 mPm.createNewUser(userId);
2064 userInfo.partial = false;
2065 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002066 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002067 }
2068 updateUserIds();
2069 Bundle restrictions = new Bundle();
Fyodor Kupolove04462c2015-11-30 15:02:53 -08002070 if (isGuest) {
2071 synchronized (mGuestRestrictions) {
2072 restrictions.putAll(mGuestRestrictions);
2073 }
2074 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002075 synchronized (mRestrictionsLock) {
2076 mBaseUserRestrictions.append(userId, restrictions);
2077 }
2078 mPm.newUserCreated(userId);
2079 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
2080 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
2081 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
2082 android.Manifest.permission.MANAGE_USERS);
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -08002083 MetricsLogger.count(mContext, isGuest ? TRON_GUEST_CREATED : TRON_USER_CREATED, 1);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002084 } finally {
2085 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07002086 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002087 return userInfo;
2088 }
2089
Amith Yamasani0b285492011-04-14 17:35:23 -07002090 /**
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002091 * @hide
2092 */
Amith Yamasani12747872015-12-07 14:19:49 -08002093 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002094 public UserInfo createRestrictedProfile(String name, int parentUserId) {
2095 checkManageUsersPermission("setupRestrictedProfile");
2096 final UserInfo user = createProfileForUser(name, UserInfo.FLAG_RESTRICTED, parentUserId);
2097 if (user == null) {
2098 return null;
2099 }
Fyodor Kupolov9e912ba2016-02-09 18:29:43 -08002100 long identity = Binder.clearCallingIdentity();
2101 try {
2102 setUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, true, user.id);
2103 // Change the setting before applying the DISALLOW_SHARE_LOCATION restriction, otherwise
2104 // the putIntForUser() will fail.
2105 android.provider.Settings.Secure.putIntForUser(mContext.getContentResolver(),
2106 android.provider.Settings.Secure.LOCATION_MODE,
2107 android.provider.Settings.Secure.LOCATION_MODE_OFF, user.id);
2108 setUserRestriction(UserManager.DISALLOW_SHARE_LOCATION, true, user.id);
2109 } finally {
2110 Binder.restoreCallingIdentity(identity);
2111 }
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002112 return user;
2113 }
2114
2115 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07002116 * Find the current guest user. If the Guest user is partial,
2117 * then do not include it in the results as it is about to die.
Adam Lesinskieddeb492014-09-08 17:50:03 -07002118 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002119 private UserInfo findCurrentGuestUser() {
2120 synchronized (mUsersLock) {
2121 final int size = mUsers.size();
2122 for (int i = 0; i < size; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002123 final UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002124 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
2125 return user;
2126 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002127 }
2128 }
2129 return null;
2130 }
2131
2132 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07002133 * Mark this guest user for deletion to allow us to create another guest
2134 * and switch to that user before actually removing this guest.
2135 * @param userHandle the userid of the current guest
2136 * @return whether the user could be marked for deletion
2137 */
Amith Yamasani12747872015-12-07 14:19:49 -08002138 @Override
Amith Yamasani1df14732014-08-29 21:37:27 -07002139 public boolean markGuestForDeletion(int userHandle) {
2140 checkManageUsersPermission("Only the system can remove users");
2141 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
2142 UserManager.DISALLOW_REMOVE_USER, false)) {
2143 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
2144 return false;
2145 }
2146
2147 long ident = Binder.clearCallingIdentity();
2148 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002149 final UserData userData;
Amith Yamasani1df14732014-08-29 21:37:27 -07002150 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002151 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002152 userData = mUsers.get(userHandle);
2153 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002154 return false;
2155 }
Amith Yamasani1df14732014-08-29 21:37:27 -07002156 }
Amith Yamasani12747872015-12-07 14:19:49 -08002157 if (!userData.info.isGuest()) {
Amith Yamasani1df14732014-08-29 21:37:27 -07002158 return false;
2159 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002160 // We set this to a guest user that is to be removed. This is a temporary state
2161 // where we are allowed to add new Guest users, even if this one is still not
2162 // removed. This user will still show up in getUserInfo() calls.
2163 // If we don't get around to removing this Guest user, it will be purged on next
2164 // startup.
Amith Yamasani12747872015-12-07 14:19:49 -08002165 userData.info.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07002166 // Mark it as disabled, so that it isn't returned any more when
2167 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002168 userData.info.flags |= UserInfo.FLAG_DISABLED;
2169 writeUserLP(userData);
Amith Yamasani1df14732014-08-29 21:37:27 -07002170 }
2171 } finally {
2172 Binder.restoreCallingIdentity(ident);
2173 }
2174 return true;
2175 }
2176
2177 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002178 * Removes a user and all data directories created for that user. This method should be called
2179 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07002180 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07002181 */
Amith Yamasani12747872015-12-07 14:19:49 -08002182 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -07002183 public boolean removeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002184 checkManageUsersPermission("Only the system can remove users");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04002185 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
2186 UserManager.DISALLOW_REMOVE_USER, false)) {
2187 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
2188 return false;
2189 }
2190
Kenny Guyee58b4f2014-05-23 15:19:53 +01002191 long ident = Binder.clearCallingIdentity();
2192 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002193 final UserData userData;
Fyodor Kupolov0df68cd2015-10-01 13:54:22 -07002194 int currentUser = ActivityManager.getCurrentUser();
2195 if (currentUser == userHandle) {
2196 Log.w(LOG_TAG, "Current user cannot be removed");
2197 return false;
2198 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002199 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002200 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002201 userData = mUsers.get(userHandle);
2202 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002203 return false;
2204 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002205
Fyodor Kupolov82402752015-10-28 14:54:51 -07002206 // We remember deleted user IDs to prevent them from being
2207 // reused during the current boot; they can still be reused
2208 // after a reboot.
2209 mRemovingUserIds.put(userHandle, true);
2210 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002211
Kenny Guyee58b4f2014-05-23 15:19:53 +01002212 try {
2213 mAppOpsService.removeUser(userHandle);
2214 } catch (RemoteException e) {
2215 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
2216 }
2217 // Set this to a partially created user, so that the user will be purged
2218 // on next startup, in case the runtime stops now before stopping and
2219 // removing the user completely.
Amith Yamasani12747872015-12-07 14:19:49 -08002220 userData.info.partial = true;
Kenny Guyee58b4f2014-05-23 15:19:53 +01002221 // Mark it as disabled, so that it isn't returned any more when
2222 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002223 userData.info.flags |= UserInfo.FLAG_DISABLED;
2224 writeUserLP(userData);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002225 }
2226
Amith Yamasani12747872015-12-07 14:19:49 -08002227 if (userData.info.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
2228 && userData.info.isManagedProfile()) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002229 // Send broadcast to notify system that the user removed was a
2230 // managed user.
Amith Yamasani12747872015-12-07 14:19:49 -08002231 sendProfileRemovedBroadcast(userData.info.profileGroupId, userData.info.id);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002232 }
2233
2234 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
2235 int res;
2236 try {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07002237 res = ActivityManagerNative.getDefault().stopUser(userHandle, /* force= */ true,
2238 new IStopUserCallback.Stub() {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002239 @Override
2240 public void userStopped(int userId) {
2241 finishRemoveUser(userId);
2242 }
2243 @Override
2244 public void userStopAborted(int userId) {
2245 }
2246 });
2247 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002248 return false;
2249 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002250 return res == ActivityManager.USER_OP_SUCCESS;
2251 } finally {
2252 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002253 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002254 }
2255
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002256 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07002257 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002258 // Let other services shutdown any activity and clean up their state before completely
2259 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002260 long ident = Binder.clearCallingIdentity();
2261 try {
2262 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
2263 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002264 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
2265 android.Manifest.permission.MANAGE_USERS,
2266
2267 new BroadcastReceiver() {
2268 @Override
2269 public void onReceive(Context context, Intent intent) {
2270 if (DBG) {
2271 Slog.i(LOG_TAG,
2272 "USER_REMOVED broadcast sent, cleaning up user data "
2273 + userHandle);
2274 }
2275 new Thread() {
Amith Yamasani12747872015-12-07 14:19:49 -08002276 @Override
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002277 public void run() {
Amith Yamasani515d4062015-09-28 11:30:06 -07002278 // Clean up any ActivityManager state
2279 LocalServices.getService(ActivityManagerInternal.class)
2280 .onUserRemoved(userHandle);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002281 removeUserState(userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002282 }
2283 }.start();
2284 }
2285 },
2286
2287 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002288 } finally {
2289 Binder.restoreCallingIdentity(ident);
2290 }
Amith Yamasani2a003292012-08-14 18:25:45 -07002291 }
2292
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002293 private void removeUserState(final int userHandle) {
Paul Crowley91293792016-03-25 15:23:07 -07002294 try {
2295 mContext.getSystemService(StorageManager.class).destroyUserKey(userHandle);
2296 } catch (IllegalStateException e) {
2297 // This may be simply because the user was partially created.
2298 Slog.i(LOG_TAG,
2299 "Destroying key for user " + userHandle + " failed, continuing anyway", e);
2300 }
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002301
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002302 // Cleanup package manager settings
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002303 mPm.cleanUpUser(this, userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002304 // Remove this user from the list
Fyodor Kupolov82402752015-10-28 14:54:51 -07002305 synchronized (mUsersLock) {
2306 mUsers.remove(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08002307 mIsUserManaged.delete(userHandle);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07002308 mUnlockingOrUnlockedUsers.delete(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08002309 }
2310 synchronized (mRestrictionsLock) {
2311 mBaseUserRestrictions.remove(userHandle);
2312 mAppliedUserRestrictions.remove(userHandle);
2313 mCachedEffectiveUserRestrictions.remove(userHandle);
2314 mDevicePolicyLocalUserRestrictions.remove(userHandle);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002315 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002316 // Update the user list
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002317 synchronized (mPackagesLock) {
2318 writeUserListLP();
2319 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06002320 // Remove user file
2321 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
2322 userFile.delete();
Fyodor Kupolov82402752015-10-28 14:54:51 -07002323 updateUserIds();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002324
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002325 // Now that we've purged all the metadata above, destroy the actual data
2326 // on disk; if we battery pull in here we'll finish cleaning up when
2327 // reconciling after reboot.
2328 mPm.destroyUserData(userHandle,
2329 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
Amith Yamasani61f57372012-08-31 12:12:28 -07002330 }
2331
Kenny Guyf8d3a232014-05-15 16:09:52 +01002332 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01002333 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01002334 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
2335 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002336 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
Jeff Sharkeyaf6ec292015-12-17 11:19:00 -07002337 managedProfileIntent.putExtra(Intent.EXTRA_USER_HANDLE, removedUserId);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002338 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01002339 }
2340
Amith Yamasani2a003292012-08-14 18:25:45 -07002341 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002342 public Bundle getApplicationRestrictions(String packageName) {
2343 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
2344 }
2345
2346 @Override
2347 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002348 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07002349 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00002350 checkSystemOrRoot("get application restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002351 }
2352 synchronized (mPackagesLock) {
2353 // Read the restrictions from XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07002354 return readApplicationRestrictionsLP(packageName, userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002355 }
2356 }
2357
2358 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002359 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002360 int userId) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00002361 checkSystemOrRoot("set application restrictions");
Fyodor Kupolov0d88d542016-04-19 11:37:22 -07002362 if (restrictions != null) {
2363 restrictions.setDefusable(true);
2364 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002365 synchronized (mPackagesLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01002366 if (restrictions == null || restrictions.isEmpty()) {
2367 cleanAppRestrictionsForPackage(packageName, userId);
2368 } else {
2369 // Write the restrictions to XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07002370 writeApplicationRestrictionsLP(packageName, restrictions, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01002371 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002372 }
Robin Lee66e5d962014-04-09 16:44:21 +01002373
Fyodor Kupolovd2846122016-02-11 18:06:34 -08002374 // Notify package of changes via an intent - only sent to explicitly registered receivers.
2375 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
2376 changeIntent.setPackage(packageName);
2377 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
2378 mContext.sendBroadcastAsUser(changeIntent, UserHandle.of(userId));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002379 }
2380
2381 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07002382 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002383 try {
2384 return mContext.getPackageManager().getApplicationInfo(packageName,
Fyodor Kupolovd2846122016-02-11 18:06:34 -08002385 PackageManager.MATCH_UNINSTALLED_PACKAGES).uid;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002386 } catch (NameNotFoundException nnfe) {
2387 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07002388 } finally {
2389 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002390 }
2391 }
2392
Fyodor Kupolov82402752015-10-28 14:54:51 -07002393 private Bundle readApplicationRestrictionsLP(String packageName, int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002394 AtomicFile restrictionsFile =
2395 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
2396 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002397 return readApplicationRestrictionsLP(restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002398 }
2399
2400 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002401 static Bundle readApplicationRestrictionsLP(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002402 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002403 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002404 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07002405 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002406 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002407
2408 FileInputStream fis = null;
2409 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002410 fis = restrictionsFile.openRead();
2411 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002412 parser.setInput(fis, StandardCharsets.UTF_8.name());
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002413 XmlUtils.nextElement(parser);
2414 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002415 Slog.e(LOG_TAG, "Unable to read restrictions file "
2416 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002417 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002418 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002419 while (parser.next() != XmlPullParser.END_DOCUMENT) {
2420 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002421 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002422 } catch (IOException|XmlPullParserException e) {
2423 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002424 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002425 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002426 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002427 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002428 }
2429
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002430 private static void readEntry(Bundle restrictions, ArrayList<String> values,
2431 XmlPullParser parser) throws XmlPullParserException, IOException {
2432 int type = parser.getEventType();
2433 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
2434 String key = parser.getAttributeValue(null, ATTR_KEY);
2435 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
2436 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
2437 if (multiple != null) {
2438 values.clear();
2439 int count = Integer.parseInt(multiple);
2440 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
2441 if (type == XmlPullParser.START_TAG
2442 && parser.getName().equals(TAG_VALUE)) {
2443 values.add(parser.nextText().trim());
2444 count--;
2445 }
2446 }
2447 String [] valueStrings = new String[values.size()];
2448 values.toArray(valueStrings);
2449 restrictions.putStringArray(key, valueStrings);
2450 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
2451 restrictions.putBundle(key, readBundleEntry(parser, values));
2452 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
2453 final int outerDepth = parser.getDepth();
2454 ArrayList<Bundle> bundleList = new ArrayList<>();
2455 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2456 Bundle childBundle = readBundleEntry(parser, values);
2457 bundleList.add(childBundle);
2458 }
2459 restrictions.putParcelableArray(key,
2460 bundleList.toArray(new Bundle[bundleList.size()]));
2461 } else {
2462 String value = parser.nextText().trim();
2463 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
2464 restrictions.putBoolean(key, Boolean.parseBoolean(value));
2465 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
2466 restrictions.putInt(key, Integer.parseInt(value));
2467 } else {
2468 restrictions.putString(key, value);
2469 }
2470 }
2471 }
2472 }
2473
2474 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
2475 throws IOException, XmlPullParserException {
2476 Bundle childBundle = new Bundle();
2477 final int outerDepth = parser.getDepth();
2478 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2479 readEntry(childBundle, values, parser);
2480 }
2481 return childBundle;
2482 }
2483
Fyodor Kupolov82402752015-10-28 14:54:51 -07002484 private void writeApplicationRestrictionsLP(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002485 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002486 AtomicFile restrictionsFile = new AtomicFile(
2487 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07002488 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002489 writeApplicationRestrictionsLP(restrictions, restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002490 }
2491
2492 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002493 static void writeApplicationRestrictionsLP(Bundle restrictions, AtomicFile restrictionsFile) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002494 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002495 try {
2496 fos = restrictionsFile.startWrite();
2497 final BufferedOutputStream bos = new BufferedOutputStream(fos);
2498
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002499 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002500 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002501 serializer.startDocument(null, true);
2502 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2503
2504 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002505 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002506 serializer.endTag(null, TAG_RESTRICTIONS);
2507
2508 serializer.endDocument();
2509 restrictionsFile.finishWrite(fos);
2510 } catch (Exception e) {
2511 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002512 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
2513 }
2514 }
2515
2516 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
2517 throws IOException {
2518 for (String key : restrictions.keySet()) {
2519 Object value = restrictions.get(key);
2520 serializer.startTag(null, TAG_ENTRY);
2521 serializer.attribute(null, ATTR_KEY, key);
2522
2523 if (value instanceof Boolean) {
2524 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
2525 serializer.text(value.toString());
2526 } else if (value instanceof Integer) {
2527 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
2528 serializer.text(value.toString());
2529 } else if (value == null || value instanceof String) {
2530 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
2531 serializer.text(value != null ? (String) value : "");
2532 } else if (value instanceof Bundle) {
2533 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2534 writeBundle((Bundle) value, serializer);
2535 } else if (value instanceof Parcelable[]) {
2536 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
2537 Parcelable[] array = (Parcelable[]) value;
2538 for (Parcelable parcelable : array) {
2539 if (!(parcelable instanceof Bundle)) {
2540 throw new IllegalArgumentException("bundle-array can only hold Bundles");
2541 }
2542 serializer.startTag(null, TAG_ENTRY);
2543 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2544 writeBundle((Bundle) parcelable, serializer);
2545 serializer.endTag(null, TAG_ENTRY);
2546 }
2547 } else {
2548 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
2549 String[] values = (String[]) value;
2550 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
2551 for (String choice : values) {
2552 serializer.startTag(null, TAG_VALUE);
2553 serializer.text(choice != null ? choice : "");
2554 serializer.endTag(null, TAG_VALUE);
2555 }
2556 }
2557 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002558 }
2559 }
2560
2561 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07002562 public int getUserSerialNumber(int userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002563 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002564 if (!exists(userHandle)) return -1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002565 return getUserInfoLU(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07002566 }
2567 }
2568
2569 @Override
2570 public int getUserHandle(int userSerialNumber) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002571 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002572 for (int userId : mUserIds) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002573 UserInfo info = getUserInfoLU(userId);
Kenny Guy945f8832015-02-10 15:17:26 +00002574 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07002575 }
2576 // Not found
2577 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07002578 }
2579 }
2580
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002581 @Override
2582 public long getUserCreationTime(int userHandle) {
2583 int callingUserId = UserHandle.getCallingUserId();
2584 UserInfo userInfo = null;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002585 synchronized (mUsersLock) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002586 if (callingUserId == userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002587 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002588 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002589 UserInfo parent = getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002590 if (parent != null && parent.id == callingUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002591 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002592 }
2593 }
2594 }
2595 if (userInfo == null) {
2596 throw new SecurityException("userHandle can only be the calling user or a managed "
2597 + "profile associated with this user");
2598 }
2599 return userInfo.creationTime;
2600 }
2601
Amith Yamasani0b285492011-04-14 17:35:23 -07002602 /**
2603 * Caches the list of user ids in an array, adjusting the array size when necessary.
2604 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002605 private void updateUserIds() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002606 int num = 0;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002607 synchronized (mUsersLock) {
2608 final int userSize = mUsers.size();
2609 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002610 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002611 num++;
2612 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002613 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002614 final int[] newUsers = new int[num];
2615 int n = 0;
2616 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002617 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002618 newUsers[n++] = mUsers.keyAt(i);
2619 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002620 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002621 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07002622 }
2623 }
2624
2625 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002626 * Called right before a user is started. This gives us a chance to prepare
2627 * app storage and apply any user restrictions.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002628 */
2629 public void onBeforeStartUser(int userId) {
Jeff Sharkey47f71082016-02-01 17:03:54 -07002630 final int userSerial = getUserSerialNumber(userId);
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002631 mPm.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_DE);
Jeff Sharkey47f71082016-02-01 17:03:54 -07002632 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_DE);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002633
2634 if (userId != UserHandle.USER_SYSTEM) {
2635 synchronized (mRestrictionsLock) {
2636 applyUserRestrictionsLR(userId);
2637 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002638 }
2639 }
2640
2641 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002642 * Called right before a user is unlocked. This gives us a chance to prepare
2643 * app storage.
2644 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002645 public void onBeforeUnlockUser(@UserIdInt int userId) {
Jeff Sharkey47f71082016-02-01 17:03:54 -07002646 final int userSerial = getUserSerialNumber(userId);
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002647 mPm.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_CE);
Jeff Sharkey47f71082016-02-01 17:03:54 -07002648 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_CE);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002649 }
2650
2651 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002652 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasani920ace02012-09-20 22:15:37 -07002653 * @param userId the user that was just foregrounded
2654 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002655 public void onUserLoggedIn(@UserIdInt int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -08002656 UserData userData = getUserDataNoChecks(userId);
2657 if (userData == null || userData.info.partial) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002658 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
2659 return;
2660 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002661
2662 final long now = System.currentTimeMillis();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002663 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani12747872015-12-07 14:19:49 -08002664 userData.info.lastLoggedInTime = now;
Amith Yamasani920ace02012-09-20 22:15:37 -07002665 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002666 userData.info.lastLoggedInFingerprint = Build.FINGERPRINT;
2667 scheduleWriteUser(userData);
Amith Yamasani920ace02012-09-20 22:15:37 -07002668 }
2669
2670 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002671 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani742a6712011-05-04 14:49:28 -07002672 * TODO: May not be a good idea to recycle ids, in case it results in confusion
2673 * for data and battery stats collection, or unexpected cross-talk.
Amith Yamasani0b285492011-04-14 17:35:23 -07002674 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002675 private int getNextAvailableId() {
2676 synchronized (mUsersLock) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002677 int i = MIN_USER_ID;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002678 while (i < MAX_USER_ID) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002679 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002680 return i;
Amith Yamasani195263742012-08-21 15:40:12 -07002681 }
2682 i++;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002683 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002684 }
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002685 throw new IllegalStateException("No user id available!");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002686 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002687
Amith Yamasanifc95e702013-09-26 13:20:17 -07002688 private String packageToRestrictionsFileName(String packageName) {
2689 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
2690 }
2691
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002692 /**
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002693 * Enforce that serial number stored in user directory inode matches the
2694 * given expected value. Gracefully sets the serial number if currently
2695 * undefined.
2696 *
2697 * @throws IOException when problem extracting serial number, or serial
2698 * number is mismatched.
2699 */
2700 public static void enforceSerialNumber(File file, int serialNumber) throws IOException {
2701 final int foundSerial = getSerialNumber(file);
2702 Slog.v(LOG_TAG, "Found " + file + " with serial number " + foundSerial);
2703
2704 if (foundSerial == -1) {
2705 Slog.d(LOG_TAG, "Serial number missing on " + file + "; assuming current is valid");
2706 try {
2707 setSerialNumber(file, serialNumber);
2708 } catch (IOException e) {
2709 Slog.w(LOG_TAG, "Failed to set serial number on " + file, e);
2710 }
2711
2712 } else if (foundSerial != serialNumber) {
2713 throw new IOException("Found serial number " + foundSerial
2714 + " doesn't match expected " + serialNumber);
2715 }
2716 }
2717
2718 /**
2719 * Set serial number stored in user directory inode.
2720 *
2721 * @throws IOException if serial number was already set
2722 */
2723 private static void setSerialNumber(File file, int serialNumber)
2724 throws IOException {
2725 try {
2726 final byte[] buf = Integer.toString(serialNumber).getBytes(StandardCharsets.UTF_8);
2727 Os.setxattr(file.getAbsolutePath(), XATTR_SERIAL, buf, OsConstants.XATTR_CREATE);
2728 } catch (ErrnoException e) {
2729 throw e.rethrowAsIOException();
2730 }
2731 }
2732
2733 /**
2734 * Return serial number stored in user directory inode.
2735 *
2736 * @return parsed serial number, or -1 if not set
2737 */
2738 private static int getSerialNumber(File file) throws IOException {
2739 try {
2740 final byte[] buf = new byte[256];
2741 final int len = Os.getxattr(file.getAbsolutePath(), XATTR_SERIAL, buf);
2742 final String serial = new String(buf, 0, len);
2743 try {
2744 return Integer.parseInt(serial);
2745 } catch (NumberFormatException e) {
2746 throw new IOException("Bad serial number: " + serial);
2747 }
2748 } catch (ErrnoException e) {
2749 if (e.errno == OsConstants.ENODATA) {
2750 return -1;
2751 } else {
2752 throw e.rethrowAsIOException();
2753 }
2754 }
2755 }
2756
Amith Yamasani920ace02012-09-20 22:15:37 -07002757 @Override
Amith Yamasani12747872015-12-07 14:19:49 -08002758 public void setSeedAccountData(int userId, String accountName, String accountType,
2759 PersistableBundle accountOptions, boolean persist) {
2760 checkManageUsersPermission("Require MANAGE_USERS permission to set user seed data");
2761 synchronized (mPackagesLock) {
2762 final UserData userData;
2763 synchronized (mUsersLock) {
2764 userData = getUserDataLU(userId);
2765 if (userData == null) {
2766 Slog.e(LOG_TAG, "No such user for settings seed data u=" + userId);
2767 return;
2768 }
2769 userData.seedAccountName = accountName;
2770 userData.seedAccountType = accountType;
2771 userData.seedAccountOptions = accountOptions;
2772 userData.persistSeedData = persist;
2773 }
2774 if (persist) {
2775 writeUserLP(userData);
2776 }
2777 }
2778 }
2779
2780 @Override
2781 public String getSeedAccountName() throws RemoteException {
2782 checkManageUsersPermission("Cannot get seed account information");
2783 synchronized (mUsersLock) {
2784 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
2785 return userData.seedAccountName;
2786 }
2787 }
2788
2789 @Override
2790 public String getSeedAccountType() throws RemoteException {
2791 checkManageUsersPermission("Cannot get seed account information");
2792 synchronized (mUsersLock) {
2793 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
2794 return userData.seedAccountType;
2795 }
2796 }
2797
2798 @Override
2799 public PersistableBundle getSeedAccountOptions() throws RemoteException {
2800 checkManageUsersPermission("Cannot get seed account information");
2801 synchronized (mUsersLock) {
2802 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
2803 return userData.seedAccountOptions;
2804 }
2805 }
2806
2807 @Override
2808 public void clearSeedAccountData() throws RemoteException {
2809 checkManageUsersPermission("Cannot clear seed account information");
2810 synchronized (mPackagesLock) {
2811 UserData userData;
2812 synchronized (mUsersLock) {
2813 userData = getUserDataLU(UserHandle.getCallingUserId());
2814 if (userData == null) return;
2815 userData.clearSeedAccountData();
2816 }
2817 writeUserLP(userData);
2818 }
2819 }
2820
2821 @Override
2822 public boolean someUserHasSeedAccount(String accountName, String accountType)
2823 throws RemoteException {
2824 checkManageUsersPermission("Cannot check seed account information");
2825 synchronized (mUsersLock) {
2826 final int userSize = mUsers.size();
2827 for (int i = 0; i < userSize; i++) {
2828 final UserData data = mUsers.valueAt(i);
2829 if (data.info.isInitialized()) continue;
2830 if (data.seedAccountName == null || !data.seedAccountName.equals(accountName)) {
2831 continue;
2832 }
2833 if (data.seedAccountType == null || !data.seedAccountType.equals(accountType)) {
2834 continue;
2835 }
2836 return true;
2837 }
2838 }
2839 return false;
2840 }
2841
2842 @Override
Todd Kennedy60459ab2015-10-30 11:32:16 -07002843 public void onShellCommand(FileDescriptor in, FileDescriptor out,
2844 FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
2845 (new Shell()).exec(this, in, out, err, args, resultReceiver);
2846 }
2847
2848 int onShellCommand(Shell shell, String cmd) {
2849 if (cmd == null) {
2850 return shell.handleDefaultCommands(cmd);
2851 }
2852
2853 final PrintWriter pw = shell.getOutPrintWriter();
2854 try {
2855 switch(cmd) {
2856 case "list":
2857 return runList(pw);
2858 }
2859 } catch (RemoteException e) {
2860 pw.println("Remote exception: " + e);
2861 }
2862 return -1;
2863 }
2864
2865 private int runList(PrintWriter pw) throws RemoteException {
2866 final IActivityManager am = ActivityManagerNative.getDefault();
2867 final List<UserInfo> users = getUsers(false);
2868 if (users == null) {
2869 pw.println("Error: couldn't get users");
2870 return 1;
2871 } else {
2872 pw.println("Users:");
2873 for (int i = 0; i < users.size(); i++) {
Jeff Sharkeye17ac152015-11-06 22:40:29 -08002874 String running = am.isUserRunning(users.get(i).id, 0) ? " running" : "";
Todd Kennedy60459ab2015-10-30 11:32:16 -07002875 pw.println("\t" + users.get(i).toString() + running);
2876 }
2877 return 0;
2878 }
2879 }
2880
2881 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -07002882 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2883 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2884 != PackageManager.PERMISSION_GRANTED) {
2885 pw.println("Permission Denial: can't dump UserManager from from pid="
2886 + Binder.getCallingPid()
2887 + ", uid=" + Binder.getCallingUid()
2888 + " without permission "
2889 + android.Manifest.permission.DUMP);
2890 return;
2891 }
2892
2893 long now = System.currentTimeMillis();
2894 StringBuilder sb = new StringBuilder();
2895 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002896 synchronized (mUsersLock) {
2897 pw.println("Users:");
2898 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002899 UserData userData = mUsers.valueAt(i);
2900 if (userData == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002901 continue;
2902 }
Amith Yamasani12747872015-12-07 14:19:49 -08002903 UserInfo userInfo = userData.info;
2904 final int userId = userInfo.id;
2905 pw.print(" "); pw.print(userInfo);
2906 pw.print(" serialNo="); pw.print(userInfo.serialNumber);
Makoto Onukie7927da2015-11-25 10:05:17 -08002907 if (mRemovingUserIds.get(userId)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002908 pw.print(" <removing> ");
2909 }
Amith Yamasani12747872015-12-07 14:19:49 -08002910 if (userInfo.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002911 pw.print(" <partial>");
2912 }
2913 pw.println();
2914 pw.print(" Created: ");
Amith Yamasani12747872015-12-07 14:19:49 -08002915 if (userInfo.creationTime == 0) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002916 pw.println("<unknown>");
2917 } else {
2918 sb.setLength(0);
Amith Yamasani12747872015-12-07 14:19:49 -08002919 TimeUtils.formatDuration(now - userInfo.creationTime, sb);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002920 sb.append(" ago");
2921 pw.println(sb);
2922 }
2923 pw.print(" Last logged in: ");
Amith Yamasani12747872015-12-07 14:19:49 -08002924 if (userInfo.lastLoggedInTime == 0) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002925 pw.println("<unknown>");
2926 } else {
2927 sb.setLength(0);
Amith Yamasani12747872015-12-07 14:19:49 -08002928 TimeUtils.formatDuration(now - userInfo.lastLoggedInTime, sb);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002929 sb.append(" ago");
2930 pw.println(sb);
2931 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002932 pw.print(" Last logged in fingerprint: ");
2933 pw.println(userInfo.lastLoggedInFingerprint);
Makoto Onukie7927da2015-11-25 10:05:17 -08002934 pw.print(" Has profile owner: ");
2935 pw.println(mIsUserManaged.get(userId));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002936 pw.println(" Restrictions:");
2937 synchronized (mRestrictionsLock) {
2938 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08002939 pw, " ", mBaseUserRestrictions.get(userInfo.id));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002940 pw.println(" Device policy local restrictions:");
2941 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08002942 pw, " ", mDevicePolicyLocalUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002943 pw.println(" Effective restrictions:");
2944 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08002945 pw, " ", mCachedEffectiveUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002946 }
Amith Yamasani12747872015-12-07 14:19:49 -08002947
2948 if (userData.account != null) {
2949 pw.print(" Account name: " + userData.account);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08002950 pw.println();
2951 }
Amith Yamasani12747872015-12-07 14:19:49 -08002952
2953 if (userData.seedAccountName != null) {
2954 pw.print(" Seed account name: " + userData.seedAccountName);
2955 pw.println();
2956 if (userData.seedAccountType != null) {
2957 pw.print(" account type: " + userData.seedAccountType);
2958 pw.println();
2959 }
2960 if (userData.seedAccountOptions != null) {
2961 pw.print(" account options exist");
2962 pw.println();
2963 }
2964 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002965 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002966 }
Amith Yamasani12747872015-12-07 14:19:49 -08002967 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002968 pw.println(" Device policy global restrictions:");
2969 synchronized (mRestrictionsLock) {
2970 UserRestrictionsUtils
2971 .dumpRestrictions(pw, " ", mDevicePolicyGlobalUserRestrictions);
2972 }
Makoto Onukia4f11972015-10-01 13:19:58 -07002973 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002974 pw.println(" Guest restrictions:");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002975 synchronized (mGuestRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002976 UserRestrictionsUtils.dumpRestrictions(pw, " ", mGuestRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002977 }
Makoto Onukie7927da2015-11-25 10:05:17 -08002978 synchronized (mUsersLock) {
2979 pw.println();
2980 pw.println(" Device managed: " + mIsDeviceManaged);
2981 }
Amith Yamasani12747872015-12-07 14:19:49 -08002982 // Dump some capabilities
2983 pw.println();
2984 pw.println(" Max users: " + UserManager.getMaxSupportedUsers());
2985 pw.println(" Supports switchable users: " + UserManager.supportsMultipleUsers());
Lenka Trochtova02fee152015-12-22 14:26:18 +01002986 pw.println(" All guests ephemeral: " + Resources.getSystem().getBoolean(
2987 com.android.internal.R.bool.config_guestUserEphemeral));
Amith Yamasani920ace02012-09-20 22:15:37 -07002988 }
2989 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002990
2991 final class MainHandler extends Handler {
2992
2993 @Override
2994 public void handleMessage(Message msg) {
2995 switch (msg.what) {
2996 case WRITE_USER_MSG:
2997 removeMessages(WRITE_USER_MSG, msg.obj);
2998 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002999 int userId = ((UserData) msg.obj).info.id;
3000 UserData userData = getUserDataNoChecks(userId);
3001 if (userData != null) {
3002 writeUserLP(userData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08003003 }
3004 }
3005 }
3006 }
3007 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07003008
3009 /**
3010 * @param userId
3011 * @return whether the user has been initialized yet
3012 */
3013 boolean isInitialized(int userId) {
3014 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
3015 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003016
3017 private class LocalService extends UserManagerInternal {
Makoto Onuki068c54a2015-10-13 14:34:03 -07003018 @Override
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003019 public void setDevicePolicyUserRestrictions(int userId, @NonNull Bundle localRestrictions,
3020 @Nullable Bundle globalRestrictions) {
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08003021 UserManagerService.this.setDevicePolicyUserRestrictionsInner(userId, localRestrictions,
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003022 globalRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003023 }
3024
3025 @Override
3026 public Bundle getBaseUserRestrictions(int userId) {
3027 synchronized (mRestrictionsLock) {
3028 return mBaseUserRestrictions.get(userId);
3029 }
3030 }
3031
3032 @Override
3033 public void setBaseUserRestrictionsByDpmsForMigration(
3034 int userId, Bundle baseRestrictions) {
3035 synchronized (mRestrictionsLock) {
3036 mBaseUserRestrictions.put(userId, new Bundle(baseRestrictions));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003037 invalidateEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003038 }
3039
Amith Yamasani12747872015-12-07 14:19:49 -08003040 final UserData userData = getUserDataNoChecks(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003041 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08003042 if (userData != null) {
3043 writeUserLP(userData);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003044 } else {
3045 Slog.w(LOG_TAG, "UserInfo not found for " + userId);
3046 }
3047 }
3048 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08003049
3050 @Override
3051 public boolean getUserRestriction(int userId, String key) {
3052 return getUserRestrictions(userId).getBoolean(key);
3053 }
3054
3055 @Override
3056 public void addUserRestrictionsListener(UserRestrictionsListener listener) {
3057 synchronized (mUserRestrictionsListeners) {
3058 mUserRestrictionsListeners.add(listener);
3059 }
3060 }
3061
3062 @Override
3063 public void removeUserRestrictionsListener(UserRestrictionsListener listener) {
3064 synchronized (mUserRestrictionsListeners) {
3065 mUserRestrictionsListeners.remove(listener);
3066 }
3067 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003068
3069 @Override
3070 public void setDeviceManaged(boolean isManaged) {
3071 synchronized (mUsersLock) {
3072 mIsDeviceManaged = isManaged;
3073 }
3074 }
3075
3076 @Override
3077 public void setUserManaged(int userId, boolean isManaged) {
3078 synchronized (mUsersLock) {
3079 mIsUserManaged.put(userId, isManaged);
3080 }
3081 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01003082
3083 @Override
3084 public void setUserIcon(int userId, Bitmap bitmap) {
3085 long ident = Binder.clearCallingIdentity();
3086 try {
3087 synchronized (mPackagesLock) {
3088 UserData userData = getUserDataNoChecks(userId);
3089 if (userData == null || userData.info.partial) {
3090 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
3091 return;
3092 }
3093 writeBitmapLP(userData.info, bitmap);
3094 writeUserLP(userData);
3095 }
3096 sendUserInfoChangedBroadcast(userId);
3097 } finally {
3098 Binder.restoreCallingIdentity(ident);
3099 }
3100 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01003101
3102 @Override
3103 public void setForceEphemeralUsers(boolean forceEphemeralUsers) {
3104 synchronized (mUsersLock) {
3105 mForceEphemeralUsers = forceEphemeralUsers;
3106 }
3107 }
3108
3109 @Override
3110 public void removeAllUsers() {
3111 if (UserHandle.USER_SYSTEM == ActivityManager.getCurrentUser()) {
3112 // Remove the non-system users straight away.
3113 removeNonSystemUsers();
3114 } else {
3115 // Switch to the system user first and then remove the other users.
3116 BroadcastReceiver userSwitchedReceiver = new BroadcastReceiver() {
3117 @Override
3118 public void onReceive(Context context, Intent intent) {
3119 int userId =
3120 intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3121 if (userId != UserHandle.USER_SYSTEM) {
3122 return;
3123 }
3124 mContext.unregisterReceiver(this);
3125 removeNonSystemUsers();
3126 }
3127 };
3128 IntentFilter userSwitchedFilter = new IntentFilter();
3129 userSwitchedFilter.addAction(Intent.ACTION_USER_SWITCHED);
3130 mContext.registerReceiver(
3131 userSwitchedReceiver, userSwitchedFilter, null, mHandler);
3132
3133 // Switch to the system user.
3134 ActivityManager am =
3135 (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
3136 am.switchUser(UserHandle.USER_SYSTEM);
3137 }
3138 }
phweisse9c44062016-02-10 12:57:38 +01003139
3140 @Override
Lenka Trochtova1ddda472016-02-12 10:42:12 +01003141 public void onEphemeralUserStop(int userId) {
3142 synchronized (mUsersLock) {
3143 UserInfo userInfo = getUserInfoLU(userId);
3144 if (userInfo != null && userInfo.isEphemeral()) {
3145 // Do not allow switching back to the ephemeral user again as the user is going
3146 // to be deleted.
3147 userInfo.flags |= UserInfo.FLAG_DISABLED;
3148 if (userInfo.isGuest()) {
3149 // Indicate that the guest will be deleted after it stops.
3150 userInfo.guestToRemove = true;
3151 }
3152 }
3153 }
3154 }
3155
3156 @Override
phweisse9c44062016-02-10 12:57:38 +01003157 public UserInfo createUserEvenWhenDisallowed(String name, int flags) {
3158 UserInfo user = createUserInternalUnchecked(name, flags, UserHandle.USER_NULL);
3159 // Keep this in sync with UserManager.createUser
3160 if (user != null && !user.isAdmin()) {
3161 setUserRestriction(UserManager.DISALLOW_SMS, true, user.id);
3162 setUserRestriction(UserManager.DISALLOW_OUTGOING_CALLS, true, user.id);
3163 }
3164 return user;
3165 }
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003166
3167 @Override
3168 public void setUserUnlockingOrUnlocked(int userId, boolean unlockingOrUnlocked) {
3169 synchronized (mUsersLock) {
3170 mUnlockingOrUnlockedUsers.put(userId, unlockingOrUnlocked);
3171 }
3172 }
3173
3174 @Override
3175 public boolean isUserUnlockingOrUnlocked(int userId) {
3176 synchronized (mUsersLock) {
3177 return mUnlockingOrUnlockedUsers.get(userId);
3178 }
3179 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01003180 }
3181
3182 /* Remove all the users except of the system one. */
3183 private void removeNonSystemUsers() {
3184 ArrayList<UserInfo> usersToRemove = new ArrayList<>();
3185 synchronized (mUsersLock) {
3186 final int userSize = mUsers.size();
3187 for (int i = 0; i < userSize; i++) {
3188 UserInfo ui = mUsers.valueAt(i).info;
3189 if (ui.id != UserHandle.USER_SYSTEM) {
3190 usersToRemove.add(ui);
3191 }
3192 }
3193 }
3194 for (UserInfo ui: usersToRemove) {
3195 removeUser(ui.id);
3196 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003197 }
Todd Kennedy60459ab2015-10-30 11:32:16 -07003198
3199 private class Shell extends ShellCommand {
3200 @Override
3201 public int onCommand(String cmd) {
3202 return onShellCommand(this, cmd);
3203 }
3204
3205 @Override
3206 public void onHelp() {
3207 final PrintWriter pw = getOutPrintWriter();
3208 pw.println("User manager (user) commands:");
3209 pw.println(" help");
3210 pw.println(" Print this help text.");
3211 pw.println("");
3212 pw.println(" list");
3213 pw.println(" Prints all users on the system.");
3214 }
3215 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003216
3217 private static void debug(String message) {
3218 Log.d(LOG_TAG, message +
3219 (DBG_WITH_STACKTRACE ? " called at\n" + Debug.getCallers(10, " ") : ""));
3220 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003221}