blob: f9ef0781bbdce31e2d1f0dee6fd0153cb87e6381 [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
Xiaohui Chenb3b92582015-12-07 11:22:13 -080020import android.Manifest;
Xiaohui Chen594f2082015-08-18 11:04:20 -070021import android.annotation.NonNull;
Makoto Onuki068c54a2015-10-13 14:34:03 -070022import android.annotation.Nullable;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -060023import android.annotation.UserIdInt;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070024import android.app.Activity;
Amith Yamasani2a003292012-08-14 18:25:45 -070025import android.app.ActivityManager;
Amith Yamasani515d4062015-09-28 11:30:06 -070026import android.app.ActivityManagerInternal;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070027import android.app.ActivityManagerNative;
Todd Kennedy60459ab2015-10-30 11:32:16 -070028import android.app.IActivityManager;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070029import android.app.IStopUserCallback;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070030import android.content.BroadcastReceiver;
Amith Yamasani258848d2012-08-10 17:06:33 -070031import android.content.Context;
32import android.content.Intent;
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +010033import android.content.IntentFilter;
Amith Yamasani0b285492011-04-14 17:35:23 -070034import android.content.pm.PackageManager;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -080035import android.content.pm.PackageManager.NameNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070036import android.content.pm.UserInfo;
Lenka Trochtova02fee152015-12-22 14:26:18 +010037import android.content.res.Resources;
Amith Yamasanie928d7d2012-09-17 21:46:51 -070038import android.graphics.Bitmap;
Amith Yamasani258848d2012-08-10 17:06:33 -070039import android.os.Binder;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -060040import android.os.Build;
Amith Yamasanie4cf7342012-12-17 11:12:09 -080041import android.os.Bundle;
Makoto Onuki1a2cd742015-11-16 13:51:27 -080042import android.os.Debug;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070043import android.os.Environment;
44import android.os.FileUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080045import android.os.Handler;
Svet Ganov9cea80cd2016-02-16 11:47:00 -080046import android.os.IBinder;
Amith Yamasani258848d2012-08-10 17:06:33 -070047import android.os.IUserManager;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -080048import android.os.Message;
Adrian Roos1bdff912015-02-17 15:51:35 +010049import android.os.ParcelFileDescriptor;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070050import android.os.Parcelable;
Amith Yamasani12747872015-12-07 14:19:49 -080051import android.os.PersistableBundle;
Amith Yamasani258848d2012-08-10 17:06:33 -070052import android.os.Process;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070053import android.os.RemoteException;
Todd Kennedy60459ab2015-10-30 11:32:16 -070054import android.os.ResultReceiver;
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +010055import android.os.SELinux;
Jason Monk62062992014-05-06 09:55:28 -040056import android.os.ServiceManager;
Todd Kennedy60459ab2015-10-30 11:32:16 -070057import android.os.ShellCommand;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070058import android.os.UserHandle;
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070059import android.os.UserManager;
Makoto Onuki068c54a2015-10-13 14:34:03 -070060import android.os.UserManagerInternal;
Makoto Onukid45a4a22015-11-02 17:17:38 -080061import android.os.UserManagerInternal.UserRestrictionsListener;
Paul Crowley85e4e812015-05-19 12:42:00 +010062import android.os.storage.StorageManager;
Jeff Sharkey6dce4962015-07-03 18:08:41 -070063import android.system.ErrnoException;
64import android.system.Os;
65import android.system.OsConstants;
Amith Yamasani2a003292012-08-14 18:25:45 -070066import android.util.AtomicFile;
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -070067import android.util.IntArray;
Amith Yamasani655d0e22013-06-12 14:19:10 -070068import android.util.Log;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070069import android.util.Slog;
70import android.util.SparseArray;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080071import android.util.SparseBooleanArray;
Amith Yamasani920ace02012-09-20 22:15:37 -070072import android.util.TimeUtils;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070073import android.util.Xml;
74
Makoto Onuki068c54a2015-10-13 14:34:03 -070075import com.android.internal.annotations.GuardedBy;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070076import com.android.internal.annotations.VisibleForTesting;
Jason Monk62062992014-05-06 09:55:28 -040077import com.android.internal.app.IAppOpsService;
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -080078import com.android.internal.logging.MetricsLogger;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080079import com.android.internal.util.FastXmlSerializer;
Makoto Onuki068c54a2015-10-13 14:34:03 -070080import com.android.internal.util.Preconditions;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070081import com.android.internal.util.XmlUtils;
Clara Bayarri10ad84a2015-12-01 17:38:05 +000082import com.android.internal.widget.LockPatternUtils;
Amith Yamasani515d4062015-09-28 11:30:06 -070083import com.android.server.LocalServices;
Jeff Sharkey47f71082016-02-01 17:03:54 -070084
85import libcore.io.IoUtils;
86import libcore.util.Objects;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080087
88import org.xmlpull.v1.XmlPullParser;
89import org.xmlpull.v1.XmlPullParserException;
90import org.xmlpull.v1.XmlSerializer;
91
Amith Yamasani4b2e9342011-03-31 12:38:53 -070092import java.io.BufferedOutputStream;
93import java.io.File;
Amith Yamasani920ace02012-09-20 22:15:37 -070094import java.io.FileDescriptor;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070095import java.io.FileInputStream;
Amith Yamasanib8151ec2012-04-18 18:02:48 -070096import java.io.FileNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070097import java.io.FileOutputStream;
98import java.io.IOException;
Amith Yamasani920ace02012-09-20 22:15:37 -070099import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100100import java.nio.charset.StandardCharsets;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700101import java.util.ArrayList;
102import java.util.List;
103
Makoto Onuki068c54a2015-10-13 14:34:03 -0700104/**
105 * Service for {@link UserManager}.
106 *
107 * Method naming convention:
Fyodor Kupolov82402752015-10-28 14:54:51 -0700108 * <ul>
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800109 * <li> Methods suffixed with "LP" should be called within the {@link #mPackagesLock} lock.
Fyodor Kupolov82402752015-10-28 14:54:51 -0700110 * <li> Methods suffixed with "LR" should be called within the {@link #mRestrictionsLock} lock.
111 * <li> Methods suffixed with "LU" should be called within the {@link #mUsersLock} lock.
112 * </ul>
Makoto Onuki068c54a2015-10-13 14:34:03 -0700113 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700114public class UserManagerService extends IUserManager.Stub {
Amith Yamasani2a003292012-08-14 18:25:45 -0700115 private static final String LOG_TAG = "UserManagerService";
Makoto Onuki81c61ea2016-01-22 11:22:26 -0800116 static final boolean DBG = false; // DO NOT SUBMIT WITH TRUE
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800117 private static final boolean DBG_WITH_STACKTRACE = false; // DO NOT SUBMIT WITH TRUE
Amith Yamasani16389312012-10-17 21:20:14 -0700118
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700119 private static final String TAG_NAME = "name";
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800120 private static final String TAG_ACCOUNT = "account";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700121 private static final String ATTR_FLAGS = "flags";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700122 private static final String ATTR_ICON_PATH = "icon";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700123 private static final String ATTR_ID = "id";
Amith Yamasani920ace02012-09-20 22:15:37 -0700124 private static final String ATTR_CREATION_TIME = "created";
125 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -0600126 private static final String ATTR_LAST_LOGGED_IN_FINGERPRINT = "lastLoggedInFingerprint";
Amith Yamasani2a003292012-08-14 18:25:45 -0700127 private static final String ATTR_SERIAL_NO = "serialNumber";
128 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700129 private static final String ATTR_PARTIAL = "partial";
Adam Lesinskieddeb492014-09-08 17:50:03 -0700130 private static final String ATTR_GUEST_TO_REMOVE = "guestToRemove";
Amith Yamasani6f34b412012-10-22 18:19:27 -0700131 private static final String ATTR_USER_VERSION = "version";
Kenny Guy2a764942014-04-02 13:29:20 +0100132 private static final String ATTR_PROFILE_GROUP_ID = "profileGroupId";
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700133 private static final String ATTR_RESTRICTED_PROFILE_PARENT_ID = "restrictedProfileParentId";
Amith Yamasani12747872015-12-07 14:19:49 -0800134 private static final String ATTR_SEED_ACCOUNT_NAME = "seedAccountName";
135 private static final String ATTR_SEED_ACCOUNT_TYPE = "seedAccountType";
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530136 private static final String TAG_GUEST_RESTRICTIONS = "guestRestrictions";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700137 private static final String TAG_USERS = "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700138 private static final String TAG_USER = "user";
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800139 private static final String TAG_RESTRICTIONS = "restrictions";
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800140 private static final String TAG_DEVICE_POLICY_RESTRICTIONS = "device_policy_restrictions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800141 private static final String TAG_ENTRY = "entry";
142 private static final String TAG_VALUE = "value";
Amith Yamasani12747872015-12-07 14:19:49 -0800143 private static final String TAG_SEED_ACCOUNT_OPTIONS = "seedAccountOptions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800144 private static final String ATTR_KEY = "key";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700145 private static final String ATTR_VALUE_TYPE = "type";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800146 private static final String ATTR_MULTIPLE = "m";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700147
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700148 private static final String ATTR_TYPE_STRING_ARRAY = "sa";
149 private static final String ATTR_TYPE_STRING = "s";
150 private static final String ATTR_TYPE_BOOLEAN = "b";
Amith Yamasani5b5aa402014-06-01 20:10:14 -0700151 private static final String ATTR_TYPE_INTEGER = "i";
Fyodor Kupolov262f9952015-03-23 18:55:11 -0700152 private static final String ATTR_TYPE_BUNDLE = "B";
153 private static final String ATTR_TYPE_BUNDLE_ARRAY = "BA";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700154
Amith Yamasani0b285492011-04-14 17:35:23 -0700155 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700156 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700157 private static final String USER_PHOTO_FILENAME = "photo.png";
Adrian Roos1bdff912015-02-17 15:51:35 +0100158 private static final String USER_PHOTO_FILENAME_TMP = USER_PHOTO_FILENAME + ".tmp";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700159
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800160 private static final String RESTRICTIONS_FILE_PREFIX = "res_";
Amith Yamasanifc95e702013-09-26 13:20:17 -0700161 private static final String XML_SUFFIX = ".xml";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800162
Amith Yamasani634cf312012-10-04 17:34:21 -0700163 private static final int MIN_USER_ID = 10;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700164 // We need to keep process uid within Integer.MAX_VALUE.
165 private static final int MAX_USER_ID = Integer.MAX_VALUE / UserHandle.PER_USER_RANGE;
Amith Yamasani634cf312012-10-04 17:34:21 -0700166
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700167 private static final int USER_VERSION = 6;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700168
Amith Yamasani920ace02012-09-20 22:15:37 -0700169 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
170
Nicolas Prevotb8186812015-08-06 15:00:03 +0100171 // Maximum number of managed profiles permitted per user is 1. This cannot be increased
Amith Yamasani95ab7842014-08-11 17:09:26 -0700172 // without first making sure that the rest of the framework is prepared for it.
173 private static final int MAX_MANAGED_PROFILES = 1;
174
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800175 static final int WRITE_USER_MSG = 1;
176 static final int WRITE_USER_DELAY = 2*1000; // 2 seconds
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530177
Jeff Sharkey6dce4962015-07-03 18:08:41 -0700178 private static final String XATTR_SERIAL = "user.serial";
179
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -0800180 // Tron counters
181 private static final String TRON_GUEST_CREATED = "users_guest_created";
182 private static final String TRON_USER_CREATED = "users_user_created";
183
Dianne Hackborn4428e172012-08-24 17:43:05 -0700184 private final Context mContext;
185 private final PackageManagerService mPm;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700186 private final Object mPackagesLock;
Fyodor Kupolov82402752015-10-28 14:54:51 -0700187 // Short-term lock for internal state, when interaction/sync with PM is not required
188 private final Object mUsersLock = new Object();
189 private final Object mRestrictionsLock = new Object();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700190
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800191 private final Handler mHandler;
192
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700193 private final File mUsersDir;
194 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700195
Svet Ganov9cea80cd2016-02-16 11:47:00 -0800196 private static final IBinder mUserRestriconToken = new Binder();
197
Makoto Onuki068c54a2015-10-13 14:34:03 -0700198 /**
Amith Yamasani12747872015-12-07 14:19:49 -0800199 * User-related information that is used for persisting to flash. Only UserInfo is
200 * directly exposed to other system apps.
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800201 */
Amith Yamasani12747872015-12-07 14:19:49 -0800202 private static class UserData {
203 // Basic user information and properties
204 UserInfo info;
205 // Account name used when there is a strong association between a user and an account
206 String account;
207 // Account information for seeding into a newly created user. This could also be
208 // used for login validation for an existing user, for updating their credentials.
209 // In the latter case, data may not need to be persisted as it is only valid for the
210 // current login session.
211 String seedAccountName;
212 String seedAccountType;
213 PersistableBundle seedAccountOptions;
214 // Whether to perist the seed account information to be available after a boot
215 boolean persistSeedData;
216
217 void clearSeedAccountData() {
218 seedAccountName = null;
219 seedAccountType = null;
220 seedAccountOptions = null;
221 persistSeedData = false;
222 }
223 }
224
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800225 @GuardedBy("mUsersLock")
Amith Yamasani12747872015-12-07 14:19:49 -0800226 private final SparseArray<UserData> mUsers = new SparseArray<>();
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800227
228 /**
Makoto Onuki068c54a2015-10-13 14:34:03 -0700229 * User restrictions set via UserManager. This doesn't include restrictions set by
230 * device owner / profile owners.
231 *
232 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
233 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
234 * maybe shared between {@link #mBaseUserRestrictions} and
235 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
236 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700237 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700238 */
239 @GuardedBy("mRestrictionsLock")
240 private final SparseArray<Bundle> mBaseUserRestrictions = new SparseArray<>();
241
242 /**
243 * Cached user restrictions that are in effect -- i.e. {@link #mBaseUserRestrictions} combined
244 * with device / profile owner restrictions. We'll initialize it lazily; use
245 * {@link #getEffectiveUserRestrictions} to access it.
246 *
247 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
248 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
249 * maybe shared between {@link #mBaseUserRestrictions} and
250 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
251 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700252 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700253 */
254 @GuardedBy("mRestrictionsLock")
255 private final SparseArray<Bundle> mCachedEffectiveUserRestrictions = new SparseArray<>();
256
Makoto Onuki4f160732015-10-27 17:15:38 -0700257 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800258 * User restrictions that have already been applied in
259 * {@link #updateUserRestrictionsInternalLR(Bundle, int)}. We use it to detect restrictions
260 * that have changed since the last
261 * {@link #updateUserRestrictionsInternalLR(Bundle, int)} call.
Makoto Onuki4f160732015-10-27 17:15:38 -0700262 */
263 @GuardedBy("mRestrictionsLock")
264 private final SparseArray<Bundle> mAppliedUserRestrictions = new SparseArray<>();
265
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800266 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800267 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
268 * that should be applied to all users, including guests.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800269 */
270 @GuardedBy("mRestrictionsLock")
271 private Bundle mDevicePolicyGlobalUserRestrictions;
272
273 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800274 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
275 * for each user.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800276 */
277 @GuardedBy("mRestrictionsLock")
278 private final SparseArray<Bundle> mDevicePolicyLocalUserRestrictions = new SparseArray<>();
279
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800280 @GuardedBy("mGuestRestrictions")
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530281 private final Bundle mGuestRestrictions = new Bundle();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800282
283 /**
284 * Set of user IDs being actively removed. Removed IDs linger in this set
285 * for several seconds to work around a VFS caching issue.
286 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700287 @GuardedBy("mUsersLock")
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800288 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700289
Fyodor Kupolov82402752015-10-28 14:54:51 -0700290 @GuardedBy("mUsersLock")
Amith Yamasani0b285492011-04-14 17:35:23 -0700291 private int[] mUserIds;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800292 @GuardedBy("mPackagesLock")
Amith Yamasani2a003292012-08-14 18:25:45 -0700293 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700294 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700295
Jason Monk62062992014-05-06 09:55:28 -0400296 private IAppOpsService mAppOpsService;
297
Makoto Onuki068c54a2015-10-13 14:34:03 -0700298 private final LocalService mLocalService;
299
Makoto Onukie7927da2015-11-25 10:05:17 -0800300 @GuardedBy("mUsersLock")
301 private boolean mIsDeviceManaged;
302
303 @GuardedBy("mUsersLock")
304 private final SparseBooleanArray mIsUserManaged = new SparseBooleanArray();
305
Makoto Onukid45a4a22015-11-02 17:17:38 -0800306 @GuardedBy("mUserRestrictionsListeners")
307 private final ArrayList<UserRestrictionsListener> mUserRestrictionsListeners =
308 new ArrayList<>();
309
Clara Bayarria1771112015-12-18 16:29:18 +0000310 private final LockPatternUtils mLockPatternUtils;
311
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +0100312 /**
313 * Whether all users should be created ephemeral.
314 */
315 @GuardedBy("mUsersLock")
316 private boolean mForceEphemeralUsers;
317
Amith Yamasani258848d2012-08-10 17:06:33 -0700318 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700319
Dianne Hackborn4428e172012-08-24 17:43:05 -0700320 public static UserManagerService getInstance() {
321 synchronized (UserManagerService.class) {
322 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700323 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700324 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700325
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800326 @VisibleForTesting
327 UserManagerService(File dataDir) {
328 this(null, null, new Object(), dataDir);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700329 }
330
Dianne Hackborn4428e172012-08-24 17:43:05 -0700331 /**
332 * Called by package manager to create the service. This is closely
333 * associated with the package manager, and the given lock is the
334 * package manager's own lock.
335 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800336 UserManagerService(Context context, PackageManagerService pm, Object packagesLock) {
337 this(context, pm, packagesLock, Environment.getDataDirectory());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700338 }
339
Dianne Hackborn4428e172012-08-24 17:43:05 -0700340 private UserManagerService(Context context, PackageManagerService pm,
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800341 Object packagesLock, File dataDir) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700342 mContext = context;
343 mPm = pm;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700344 mPackagesLock = packagesLock;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800345 mHandler = new MainHandler();
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800346 synchronized (mPackagesLock) {
347 mUsersDir = new File(dataDir, USER_INFO_DIR);
348 mUsersDir.mkdirs();
349 // Make zeroth user directory, for services to migrate their files to that location
350 File userZeroDir = new File(mUsersDir, String.valueOf(UserHandle.USER_SYSTEM));
351 userZeroDir.mkdirs();
352 FileUtils.setPermissions(mUsersDir.toString(),
353 FileUtils.S_IRWXU | FileUtils.S_IRWXG | FileUtils.S_IROTH | FileUtils.S_IXOTH,
354 -1, -1);
355 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
356 initDefaultGuestRestrictions();
357 readUserListLP();
358 sInstance = this;
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700359 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700360 mLocalService = new LocalService();
361 LocalServices.addService(UserManagerInternal.class, mLocalService);
Clara Bayarria1771112015-12-18 16:29:18 +0000362 mLockPatternUtils = new LockPatternUtils(mContext);
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700363 }
364
365 void systemReady() {
Lenka Trochtovac4dd0212015-11-18 12:22:06 +0100366 // Prune out any partially created, partially removed and ephemeral users.
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800367 ArrayList<UserInfo> partials = new ArrayList<>();
368 synchronized (mUsersLock) {
369 final int userSize = mUsers.size();
370 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800371 UserInfo ui = mUsers.valueAt(i).info;
Lenka Trochtovac4dd0212015-11-18 12:22:06 +0100372 if ((ui.partial || ui.guestToRemove || ui.isEphemeral()) && i != 0) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800373 partials.add(ui);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700374 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700375 }
Dianne Hackborn4428e172012-08-24 17:43:05 -0700376 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800377 final int partialsSize = partials.size();
378 for (int i = 0; i < partialsSize; i++) {
379 UserInfo ui = partials.get(i);
380 Slog.w(LOG_TAG, "Removing partially created user " + ui.id
381 + " (name=" + ui.name + ")");
382 removeUserState(ui.id);
383 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800384
Jason Monk62062992014-05-06 09:55:28 -0400385 mAppOpsService = IAppOpsService.Stub.asInterface(
386 ServiceManager.getService(Context.APP_OPS_SERVICE));
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800387
388 synchronized (mRestrictionsLock) {
389 applyUserRestrictionsLR(UserHandle.USER_SYSTEM);
Jason Monk62062992014-05-06 09:55:28 -0400390 }
Samuel Tand9453b82016-03-14 15:57:02 -0700391
392 UserInfo currentGuestUser = findCurrentGuestUser();
393 if (currentGuestUser != null && !hasUserRestriction(
394 UserManager.DISALLOW_CONFIG_WIFI, currentGuestUser.id)) {
395 // If a guest user currently exists, apply the DISALLOW_CONFIG_WIFI option
396 // to it, in case this guest was created in a previous version where this
397 // user restriction was not a default guest restriction.
398 setUserRestriction(UserManager.DISALLOW_CONFIG_WIFI, true, currentGuestUser.id);
399 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700400 }
401
402 @Override
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800403 public String getUserAccount(int userId) {
404 checkManageUserAndAcrossUsersFullPermission("get user account");
405 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800406 return mUsers.get(userId).account;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800407 }
408 }
409
410 @Override
411 public void setUserAccount(int userId, String accountName) {
412 checkManageUserAndAcrossUsersFullPermission("set user account");
Amith Yamasani12747872015-12-07 14:19:49 -0800413 UserData userToUpdate = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800414 synchronized (mPackagesLock) {
415 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800416 final UserData userData = mUsers.get(userId);
417 if (userData == null) {
418 Slog.e(LOG_TAG, "User not found for setting user account: u" + userId);
419 return;
420 }
421 String currentAccount = userData.account;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800422 if (!Objects.equal(currentAccount, accountName)) {
Amith Yamasani12747872015-12-07 14:19:49 -0800423 userData.account = accountName;
424 userToUpdate = userData;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800425 }
426 }
427
428 if (userToUpdate != null) {
429 writeUserLP(userToUpdate);
430 }
431 }
432 }
433
434 @Override
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700435 public UserInfo getPrimaryUser() {
436 checkManageUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700437 synchronized (mUsersLock) {
Amith Yamasani515d4062015-09-28 11:30:06 -0700438 final int userSize = mUsers.size();
439 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800440 UserInfo ui = mUsers.valueAt(i).info;
Xiaohui Chend3e9e182015-11-18 13:37:32 -0800441 if (ui.isPrimary() && !mRemovingUserIds.get(ui.id)) {
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700442 return ui;
443 }
444 }
445 }
446 return null;
447 }
448
449 @Override
Xiaohui Chen594f2082015-08-18 11:04:20 -0700450 public @NonNull List<UserInfo> getUsers(boolean excludeDying) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700451 checkManageUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700452 synchronized (mUsersLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700453 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasani515d4062015-09-28 11:30:06 -0700454 final int userSize = mUsers.size();
455 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800456 UserInfo ui = mUsers.valueAt(i).info;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700457 if (ui.partial) {
458 continue;
459 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800460 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Amith Yamasani6f48d6e2016-03-23 14:28:25 -0700461 users.add(userWithName(ui));
Amith Yamasani920ace02012-09-20 22:15:37 -0700462 }
Amith Yamasani13593602012-03-22 16:16:17 -0700463 }
464 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700465 }
Amith Yamasani13593602012-03-22 16:16:17 -0700466 }
467
Amith Yamasani258848d2012-08-10 17:06:33 -0700468 @Override
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100469 public List<UserInfo> getProfiles(int userId, boolean enabledOnly) {
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700470 boolean returnFullInfo = true;
Amith Yamasani4f582632014-02-19 14:31:52 -0800471 if (userId != UserHandle.getCallingUserId()) {
472 checkManageUsersPermission("getting profiles related to user " + userId);
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700473 } else {
474 returnFullInfo = hasManageUsersPermission();
Amith Yamasani4f582632014-02-19 14:31:52 -0800475 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700476 final long ident = Binder.clearCallingIdentity();
477 try {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700478 synchronized (mUsersLock) {
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700479 return getProfilesLU(userId, enabledOnly, returnFullInfo);
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100480 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700481 } finally {
482 Binder.restoreCallingIdentity(ident);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000483 }
484 }
485
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700486 @Override
487 public int[] getProfileIds(int userId, boolean enabledOnly) {
488 if (userId != UserHandle.getCallingUserId()) {
489 checkManageUsersPermission("getting profiles related to user " + userId);
490 }
491 final long ident = Binder.clearCallingIdentity();
492 try {
493 synchronized (mUsersLock) {
494 return getProfileIdsLU(userId, enabledOnly).toArray();
495 }
496 } finally {
497 Binder.restoreCallingIdentity(ident);
498 }
499 }
500
Amith Yamasanibe465322014-04-24 13:45:17 -0700501 /** Assume permissions already checked and caller's identity cleared */
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700502 private List<UserInfo> getProfilesLU(int userId, boolean enabledOnly, boolean fullInfo) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700503 IntArray profileIds = getProfileIdsLU(userId, enabledOnly);
504 ArrayList<UserInfo> users = new ArrayList<>(profileIds.size());
505 for (int i = 0; i < profileIds.size(); i++) {
506 int profileId = profileIds.get(i);
507 UserInfo userInfo = mUsers.get(profileId).info;
508 // If full info is not required - clear PII data to prevent 3P apps from reading it
509 if (!fullInfo) {
510 userInfo = new UserInfo(userInfo);
511 userInfo.name = null;
512 userInfo.iconPath = null;
513 } else {
514 userInfo = userWithName(userInfo);
515 }
516 users.add(userInfo);
517 }
518 return users;
519 }
520
521 /**
522 * Assume permissions already checked and caller's identity cleared
523 */
524 private IntArray getProfileIdsLU(int userId, boolean enabledOnly) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700525 UserInfo user = getUserInfoLU(userId);
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700526 IntArray result = new IntArray(mUsers.size());
Amith Yamasanidda003f2014-08-28 18:06:51 -0700527 if (user == null) {
528 // Probably a dying user
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700529 return result;
Amith Yamasanidda003f2014-08-28 18:06:51 -0700530 }
Amith Yamasani515d4062015-09-28 11:30:06 -0700531 final int userSize = mUsers.size();
532 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800533 UserInfo profile = mUsers.valueAt(i).info;
Amith Yamasanibe465322014-04-24 13:45:17 -0700534 if (!isProfileOf(user, profile)) {
535 continue;
536 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100537 if (enabledOnly && !profile.isEnabled()) {
538 continue;
Amith Yamasanibe465322014-04-24 13:45:17 -0700539 }
Amith Yamasani70fcf0c2014-07-11 08:40:19 -0700540 if (mRemovingUserIds.get(profile.id)) {
541 continue;
542 }
Tony Mak80189cd2016-04-05 17:21:42 +0100543 if (profile.partial) {
544 continue;
545 }
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700546 result.add(profile.id);
Amith Yamasanibe465322014-04-24 13:45:17 -0700547 }
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700548 return result;
Amith Yamasanibe465322014-04-24 13:45:17 -0700549 }
550
Jessica Hummelbe81c802014-04-22 15:49:22 +0100551 @Override
Andres Moralesc5548c02015-08-05 10:23:12 -0700552 public int getCredentialOwnerProfile(int userHandle) {
553 checkManageUsersPermission("get the credential owner");
Clara Bayarria1771112015-12-18 16:29:18 +0000554 if (!mLockPatternUtils.isSeparateProfileChallengeEnabled(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700555 synchronized (mUsersLock) {
556 UserInfo profileParent = getProfileParentLU(userHandle);
Andres Moralesc5548c02015-08-05 10:23:12 -0700557 if (profileParent != null) {
558 return profileParent.id;
559 }
560 }
561 }
562
563 return userHandle;
564 }
565
566 @Override
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700567 public boolean isSameProfileGroup(int userId, int otherUserId) {
568 if (userId == otherUserId) return true;
569 checkManageUsersPermission("check if in the same profile group");
570 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700571 return isSameProfileGroupLP(userId, otherUserId);
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700572 }
573 }
574
Fyodor Kupolov82402752015-10-28 14:54:51 -0700575 private boolean isSameProfileGroupLP(int userId, int otherUserId) {
576 synchronized (mUsersLock) {
577 UserInfo userInfo = getUserInfoLU(userId);
578 if (userInfo == null || userInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
579 return false;
580 }
581 UserInfo otherUserInfo = getUserInfoLU(otherUserId);
582 if (otherUserInfo == null
583 || otherUserInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
584 return false;
585 }
586 return userInfo.profileGroupId == otherUserInfo.profileGroupId;
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700587 }
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700588 }
589
590 @Override
Jessica Hummelbe81c802014-04-22 15:49:22 +0100591 public UserInfo getProfileParent(int userHandle) {
592 checkManageUsersPermission("get the profile parent");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700593 synchronized (mUsersLock) {
594 return getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700595 }
596 }
597
Fyodor Kupolov82402752015-10-28 14:54:51 -0700598 private UserInfo getProfileParentLU(int userHandle) {
599 UserInfo profile = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700600 if (profile == null) {
601 return null;
602 }
603 int parentUserId = profile.profileGroupId;
604 if (parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
605 return null;
606 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700607 return getUserInfoLU(parentUserId);
Jessica Hummelbe81c802014-04-22 15:49:22 +0100608 }
609 }
610
Fyodor Kupolov82402752015-10-28 14:54:51 -0700611 private static boolean isProfileOf(UserInfo user, UserInfo profile) {
Kenny Guy2a764942014-04-02 13:29:20 +0100612 return user.id == profile.id ||
613 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
614 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000615 }
616
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000617 private void broadcastProfileAvailabilityChanges(UserHandle profileHandle,
Rubin Xuf13c9802016-01-21 18:06:00 +0000618 UserHandle parentHandle, boolean inQuietMode) {
Rubin Xue95057a2016-04-01 16:49:25 +0100619 Intent intent = new Intent();
620 if (inQuietMode) {
621 intent.setAction(Intent.ACTION_MANAGED_PROFILE_UNAVAILABLE);
622 } else {
623 intent.setAction(Intent.ACTION_MANAGED_PROFILE_AVAILABLE);
624 }
Rubin Xuf13c9802016-01-21 18:06:00 +0000625 intent.putExtra(Intent.EXTRA_QUIET_MODE, inQuietMode);
626 intent.putExtra(Intent.EXTRA_USER, profileHandle);
627 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileHandle.getIdentifier());
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000628 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Rubin Xuf13c9802016-01-21 18:06:00 +0000629 mContext.sendBroadcastAsUser(intent, parentHandle);
Rubin Xue95057a2016-04-01 16:49:25 +0100630
631 //TODO: remove once Launcher3 is updated.
632 Intent oldIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_AVAILABILITY_CHANGED);
633 oldIntent.putExtra(Intent.EXTRA_QUIET_MODE, inQuietMode);
634 oldIntent.putExtra(Intent.EXTRA_USER, profileHandle);
635 oldIntent.putExtra(Intent.EXTRA_USER_HANDLE, profileHandle.getIdentifier());
636 oldIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
637 mContext.sendBroadcastAsUser(oldIntent, parentHandle);
638
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000639 }
640
641 @Override
642 public void setQuietModeEnabled(int userHandle, boolean enableQuietMode) {
643 checkManageUsersPermission("silence profile");
644 boolean changed = false;
645 UserInfo profile, parent;
646 synchronized (mPackagesLock) {
647 synchronized (mUsersLock) {
648 profile = getUserInfoLU(userHandle);
649 parent = getProfileParentLU(userHandle);
650
651 }
652 if (profile == null || !profile.isManagedProfile()) {
653 throw new IllegalArgumentException("User " + userHandle + " is not a profile");
654 }
655 if (profile.isQuietModeEnabled() != enableQuietMode) {
656 profile.flags ^= UserInfo.FLAG_QUIET_MODE;
Amith Yamasani12747872015-12-07 14:19:49 -0800657 writeUserLP(getUserDataLU(profile.id));
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000658 changed = true;
659 }
660 }
661 if (changed) {
Rubin Xuf13c9802016-01-21 18:06:00 +0000662 long identity = Binder.clearCallingIdentity();
663 try {
664 if (enableQuietMode) {
665 ActivityManagerNative.getDefault().stopUser(userHandle, /* force */true, null);
666 } else {
667 ActivityManagerNative.getDefault().startUserInBackground(userHandle);
668 }
669 } catch (RemoteException e) {
670 Slog.e(LOG_TAG, "fail to start/stop user for quiet mode", e);
671 } finally {
672 Binder.restoreCallingIdentity(identity);
673 }
674
675 broadcastProfileAvailabilityChanges(profile.getUserHandle(), parent.getUserHandle(),
676 enableQuietMode);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000677 }
678 }
679
680 @Override
681 public boolean isQuietModeEnabled(int userHandle) {
682 synchronized (mPackagesLock) {
683 UserInfo info;
684 synchronized (mUsersLock) {
685 info = getUserInfoLU(userHandle);
686 }
687 if (info == null || !info.isManagedProfile()) {
Rubin Xuf13c9802016-01-21 18:06:00 +0000688 return false;
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000689 }
690 return info.isQuietModeEnabled();
691 }
692 }
693
Kenny Guya52dc3e2014-02-11 15:33:14 +0000694 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100695 public void setUserEnabled(int userId) {
696 checkManageUsersPermission("enable user");
697 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700698 UserInfo info;
699 synchronized (mUsersLock) {
700 info = getUserInfoLU(userId);
701 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100702 if (info != null && !info.isEnabled()) {
703 info.flags ^= UserInfo.FLAG_DISABLED;
Amith Yamasani12747872015-12-07 14:19:49 -0800704 writeUserLP(getUserDataLU(info.id));
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100705 }
706 }
707 }
708
709 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700710 public UserInfo getUserInfo(int userId) {
Tony Mak8673b282016-03-21 21:10:59 +0000711 checkManageUsersPermission("query user");
712 synchronized (mUsersLock) {
Amith Yamasani6f48d6e2016-03-23 14:28:25 -0700713 return userWithName(getUserInfoLU(userId));
714 }
715 }
716
717 /**
718 * Returns a UserInfo object with the name filled in, for Owner, or the original
719 * if the name is already set.
720 */
721 private UserInfo userWithName(UserInfo orig) {
722 if (orig != null && orig.name == null && orig.id == UserHandle.USER_SYSTEM) {
723 UserInfo withName = new UserInfo(orig);
724 withName.name = getOwnerName();
725 return withName;
726 } else {
727 return orig;
Tony Mak8673b282016-03-21 21:10:59 +0000728 }
729 }
730
731 @Override
732 public boolean isManagedProfile(int userId) {
Tony Makb531d082016-03-16 14:49:52 +0000733 int callingUserId = UserHandle.getCallingUserId();
734 if (callingUserId != userId && !hasManageUsersPermission()) {
735 synchronized (mPackagesLock) {
736 if (!isSameProfileGroupLP(callingUserId, userId)) {
737 throw new SecurityException(
Tony Mak8673b282016-03-21 21:10:59 +0000738 "You need MANAGE_USERS permission to: check if specified user a " +
739 "managed profile outside your profile group");
Tony Makb531d082016-03-16 14:49:52 +0000740 }
741 }
Tony Mak4dc008c2016-03-16 10:46:49 +0000742 }
Fyodor Kupolov82402752015-10-28 14:54:51 -0700743 synchronized (mUsersLock) {
Tony Mak8673b282016-03-21 21:10:59 +0000744 UserInfo userInfo = getUserInfoLU(userId);
745 return userInfo != null && userInfo.isManagedProfile();
Amith Yamasani13593602012-03-22 16:16:17 -0700746 }
747 }
748
Amith Yamasani71e6c692013-03-24 17:39:28 -0700749 @Override
750 public boolean isRestricted() {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700751 synchronized (mUsersLock) {
752 return getUserInfoLU(UserHandle.getCallingUserId()).isRestricted();
Amith Yamasani71e6c692013-03-24 17:39:28 -0700753 }
754 }
755
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700756 @Override
757 public boolean canHaveRestrictedProfile(int userId) {
758 checkManageUsersPermission("canHaveRestrictedProfile");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700759 synchronized (mUsersLock) {
760 final UserInfo userInfo = getUserInfoLU(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700761 if (userInfo == null || !userInfo.canHaveProfile()) {
762 return false;
763 }
764 if (!userInfo.isAdmin()) {
765 return false;
766 }
Makoto Onukie7927da2015-11-25 10:05:17 -0800767 // restricted profile can be created if there is no DO set and the admin user has no PO;
768 return !mIsDeviceManaged && !mIsUserManaged.get(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700769 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700770 }
771
Amith Yamasani195263742012-08-21 15:40:12 -0700772 /*
773 * Should be locked on mUsers before calling this.
774 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700775 private UserInfo getUserInfoLU(int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -0800776 final UserData userData = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -0700777 // If it is partial and not in the process of being removed, return as unknown user.
Amith Yamasani12747872015-12-07 14:19:49 -0800778 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700779 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
780 return null;
781 }
Amith Yamasani12747872015-12-07 14:19:49 -0800782 return userData != null ? userData.info : null;
783 }
784
785 private UserData getUserDataLU(int userId) {
786 final UserData userData = mUsers.get(userId);
787 // If it is partial and not in the process of being removed, return as unknown user.
788 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
789 return null;
790 }
791 return userData;
Amith Yamasani195263742012-08-21 15:40:12 -0700792 }
793
Fyodor Kupolov82402752015-10-28 14:54:51 -0700794 /**
795 * Obtains {@link #mUsersLock} and return UserInfo from mUsers.
796 * <p>No permissions checking or any addition checks are made</p>
797 */
798 private UserInfo getUserInfoNoChecks(int userId) {
799 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800800 final UserData userData = mUsers.get(userId);
801 return userData != null ? userData.info : null;
802 }
803 }
804
805 /**
806 * Obtains {@link #mUsersLock} and return UserData from mUsers.
807 * <p>No permissions checking or any addition checks are made</p>
808 */
809 private UserData getUserDataNoChecks(int userId) {
810 synchronized (mUsersLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700811 return mUsers.get(userId);
812 }
813 }
814
Amith Yamasani236b2b52015-08-18 14:32:14 -0700815 /** Called by PackageManagerService */
Amith Yamasani13593602012-03-22 16:16:17 -0700816 public boolean exists(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700817 return getUserInfoNoChecks(userId) != null;
Amith Yamasani13593602012-03-22 16:16:17 -0700818 }
819
Amith Yamasani258848d2012-08-10 17:06:33 -0700820 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700821 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700822 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700823 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700824 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800825 UserData userData = getUserDataNoChecks(userId);
826 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700827 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
828 return;
829 }
Amith Yamasani12747872015-12-07 14:19:49 -0800830 if (name != null && !name.equals(userData.info.name)) {
831 userData.info.name = name;
832 writeUserLP(userData);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700833 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -0700834 }
835 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700836 if (changed) {
837 sendUserInfoChangedBroadcast(userId);
838 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700839 }
840
Amith Yamasani258848d2012-08-10 17:06:33 -0700841 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700842 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700843 checkManageUsersPermission("update users");
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +0100844 if (hasUserRestriction(UserManager.DISALLOW_SET_USER_ICON, userId)) {
845 Log.w(LOG_TAG, "Cannot set user icon. DISALLOW_SET_USER_ICON is enabled.");
846 return;
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700847 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +0100848 mLocalService.setUserIcon(userId, bitmap);
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700849 }
850
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +0100851
852
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700853 private void sendUserInfoChangedBroadcast(int userId) {
854 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
855 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
856 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -0700857 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700858 }
859
Amith Yamasani258848d2012-08-10 17:06:33 -0700860 @Override
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +0100861 public ParcelFileDescriptor getUserIcon(int targetUserId) {
Adrian Roos1bdff912015-02-17 15:51:35 +0100862 String iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700863 synchronized (mPackagesLock) {
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +0100864 UserInfo targetUserInfo = getUserInfoNoChecks(targetUserId);
865 if (targetUserInfo == null || targetUserInfo.partial) {
866 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + targetUserId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700867 return null;
868 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +0100869
870 final int callingUserId = UserHandle.getCallingUserId();
871 final int callingGroupId = getUserInfoNoChecks(callingUserId).profileGroupId;
872 final int targetGroupId = targetUserInfo.profileGroupId;
873 final boolean sameGroup = (callingGroupId != UserInfo.NO_PROFILE_GROUP_ID
874 && callingGroupId == targetGroupId);
875 if ((callingUserId != targetUserId) && !sameGroup) {
Nicolas Prevot88cc3462014-05-14 14:51:48 +0100876 checkManageUsersPermission("get the icon of a user who is not related");
877 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +0100878
879 if (targetUserInfo.iconPath == null) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700880 return null;
881 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +0100882 iconPath = targetUserInfo.iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700883 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100884
885 try {
886 return ParcelFileDescriptor.open(
887 new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
888 } catch (FileNotFoundException e) {
889 Log.e(LOG_TAG, "Couldn't find icon file", e);
890 }
891 return null;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700892 }
893
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700894 public void makeInitialized(int userId) {
895 checkManageUsersPermission("makeInitialized");
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800896 boolean scheduleWriteUser = false;
Amith Yamasani12747872015-12-07 14:19:49 -0800897 UserData userData;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800898 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800899 userData = mUsers.get(userId);
900 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700901 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800902 return;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700903 }
Amith Yamasani12747872015-12-07 14:19:49 -0800904 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
905 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800906 scheduleWriteUser = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700907 }
908 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800909 if (scheduleWriteUser) {
Amith Yamasani12747872015-12-07 14:19:49 -0800910 scheduleWriteUser(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800911 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700912 }
913
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700914 /**
915 * If default guest restrictions haven't been initialized yet, add the basic
916 * restrictions.
917 */
918 private void initDefaultGuestRestrictions() {
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800919 synchronized (mGuestRestrictions) {
920 if (mGuestRestrictions.isEmpty()) {
Samuel Tand9453b82016-03-14 15:57:02 -0700921 mGuestRestrictions.putBoolean(UserManager.DISALLOW_CONFIG_WIFI, true);
Fyodor Kupolove04462c2015-11-30 15:02:53 -0800922 mGuestRestrictions.putBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, true);
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800923 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
924 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
925 }
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700926 }
927 }
928
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800929 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530930 public Bundle getDefaultGuestRestrictions() {
931 checkManageUsersPermission("getDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800932 synchronized (mGuestRestrictions) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530933 return new Bundle(mGuestRestrictions);
934 }
935 }
936
937 @Override
938 public void setDefaultGuestRestrictions(Bundle restrictions) {
939 checkManageUsersPermission("setDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800940 synchronized (mGuestRestrictions) {
941 mGuestRestrictions.clear();
942 mGuestRestrictions.putAll(restrictions);
943 }
944 synchronized (mPackagesLock) {
945 writeUserListLP();
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530946 }
947 }
948
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800949 /**
950 * See {@link UserManagerInternal#setDevicePolicyUserRestrictions(int, Bundle, Bundle)}
951 */
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800952 void setDevicePolicyUserRestrictionsInner(int userId, @NonNull Bundle local,
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800953 @Nullable Bundle global) {
954 Preconditions.checkNotNull(local);
955 boolean globalChanged = false;
956 boolean localChanged;
957 synchronized (mRestrictionsLock) {
958 if (global != null) {
959 // Update global.
960 globalChanged = !UserRestrictionsUtils.areEqual(
961 mDevicePolicyGlobalUserRestrictions, global);
962 if (globalChanged) {
963 mDevicePolicyGlobalUserRestrictions = global;
964 }
965 }
966 {
967 // Update local.
968 final Bundle prev = mDevicePolicyLocalUserRestrictions.get(userId);
969 localChanged = !UserRestrictionsUtils.areEqual(prev, local);
970 if (localChanged) {
971 mDevicePolicyLocalUserRestrictions.put(userId, local);
972 }
973 }
974 }
975 if (DBG) {
976 Log.d(LOG_TAG, "setDevicePolicyUserRestrictions: userId=" + userId
977 + " global=" + global + (globalChanged ? " (changed)" : "")
978 + " local=" + local + (localChanged ? " (changed)" : "")
979 );
980 }
981 // Don't call them within the mRestrictionsLock.
982 synchronized (mPackagesLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800983 if (localChanged) {
Amith Yamasani12747872015-12-07 14:19:49 -0800984 writeUserLP(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800985 }
Jeff Sharkeycd575992016-03-29 14:12:49 -0600986 if (globalChanged) {
987 writeUserListLP();
988 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800989 }
990
991 synchronized (mRestrictionsLock) {
992 if (globalChanged) {
993 applyUserRestrictionsForAllUsersLR();
994 } else if (localChanged) {
995 applyUserRestrictionsLR(userId);
996 }
997 }
998 }
999
Makoto Onuki068c54a2015-10-13 14:34:03 -07001000 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001001 private Bundle computeEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001002 final Bundle baseRestrictions =
1003 UserRestrictionsUtils.nonNull(mBaseUserRestrictions.get(userId));
1004 final Bundle global = mDevicePolicyGlobalUserRestrictions;
1005 final Bundle local = mDevicePolicyLocalUserRestrictions.get(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001006
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001007 if (UserRestrictionsUtils.isEmpty(global) && UserRestrictionsUtils.isEmpty(local)) {
1008 // Common case first.
1009 return baseRestrictions;
Makoto Onuki068c54a2015-10-13 14:34:03 -07001010 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001011 final Bundle effective = UserRestrictionsUtils.clone(baseRestrictions);
1012 UserRestrictionsUtils.merge(effective, global);
1013 UserRestrictionsUtils.merge(effective, local);
1014
Makoto Onuki068c54a2015-10-13 14:34:03 -07001015 return effective;
1016 }
1017
1018 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001019 private void invalidateEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki068c54a2015-10-13 14:34:03 -07001020 if (DBG) {
1021 Log.d(LOG_TAG, "invalidateEffectiveUserRestrictions userId=" + userId);
1022 }
1023 mCachedEffectiveUserRestrictions.remove(userId);
1024 }
1025
1026 private Bundle getEffectiveUserRestrictions(int userId) {
1027 synchronized (mRestrictionsLock) {
1028 Bundle restrictions = mCachedEffectiveUserRestrictions.get(userId);
1029 if (restrictions == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001030 restrictions = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001031 mCachedEffectiveUserRestrictions.put(userId, restrictions);
1032 }
1033 return restrictions;
Amith Yamasani8cd28b52014-06-08 17:54:27 -07001034 }
1035 }
1036
Makoto Onuki068c54a2015-10-13 14:34:03 -07001037 /** @return a specific user restriction that's in effect currently. */
1038 @Override
1039 public boolean hasUserRestriction(String restrictionKey, int userId) {
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001040 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1041 return false;
1042 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001043 Bundle restrictions = getEffectiveUserRestrictions(userId);
1044 return restrictions != null && restrictions.getBoolean(restrictionKey);
1045 }
1046
1047 /**
1048 * @return UserRestrictions that are in effect currently. This always returns a new
1049 * {@link Bundle}.
1050 */
Amith Yamasani8cd28b52014-06-08 17:54:27 -07001051 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001052 public Bundle getUserRestrictions(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001053 return UserRestrictionsUtils.clone(getEffectiveUserRestrictions(userId));
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001054 }
1055
1056 @Override
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +00001057 public boolean hasBaseUserRestriction(String restrictionKey, int userId) {
1058 checkManageUsersPermission("hasBaseUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001059 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1060 return false;
1061 }
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +00001062 synchronized (mRestrictionsLock) {
1063 Bundle bundle = mBaseUserRestrictions.get(userId);
1064 return (bundle != null && bundle.getBoolean(restrictionKey, false));
1065 }
1066 }
1067
1068 @Override
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001069 public void setUserRestriction(String key, boolean value, int userId) {
Fyodor Kupolovd4b26042015-07-27 14:30:59 -07001070 checkManageUsersPermission("setUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001071 if (!UserRestrictionsUtils.isValidRestriction(key)) {
1072 return;
1073 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001074 synchronized (mRestrictionsLock) {
1075 // Note we can't modify Bundles stored in mBaseUserRestrictions directly, so create
1076 // a copy.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001077 final Bundle newRestrictions = UserRestrictionsUtils.clone(
1078 mBaseUserRestrictions.get(userId));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001079 newRestrictions.putBoolean(key, value);
1080
Fyodor Kupolov82402752015-10-28 14:54:51 -07001081 updateUserRestrictionsInternalLR(newRestrictions, userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001082 }
1083 }
1084
Makoto Onuki068c54a2015-10-13 14:34:03 -07001085 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001086 * Optionally updating user restrictions, calculate the effective user restrictions and also
1087 * propagate to other services and system settings.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001088 *
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001089 * @param newRestrictions User restrictions to set.
1090 * If null, will not update user restrictions and only does the propagation.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001091 * @param userId target user ID.
1092 */
1093 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001094 private void updateUserRestrictionsInternalLR(
Makoto Onuki068c54a2015-10-13 14:34:03 -07001095 @Nullable Bundle newRestrictions, int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001096
1097 final Bundle prevAppliedRestrictions = UserRestrictionsUtils.nonNull(
1098 mAppliedUserRestrictions.get(userId));
1099
1100 // Update base restrictions.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001101 if (newRestrictions != null) {
1102 // If newRestrictions == the current one, it's probably a bug.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001103 final Bundle prevBaseRestrictions = mBaseUserRestrictions.get(userId);
1104
1105 Preconditions.checkState(prevBaseRestrictions != newRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001106 Preconditions.checkState(mCachedEffectiveUserRestrictions.get(userId)
1107 != newRestrictions);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001108
1109 if (!UserRestrictionsUtils.areEqual(prevBaseRestrictions, newRestrictions)) {
1110 mBaseUserRestrictions.put(userId, newRestrictions);
Amith Yamasani12747872015-12-07 14:19:49 -08001111 scheduleWriteUser(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001112 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001113 }
1114
Fyodor Kupolov82402752015-10-28 14:54:51 -07001115 final Bundle effective = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001116
Makoto Onuki759a7632015-10-28 16:43:10 -07001117 mCachedEffectiveUserRestrictions.put(userId, effective);
1118
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001119 // Apply the new restrictions.
Makoto Onuki4f160732015-10-27 17:15:38 -07001120 if (DBG) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001121 debug("Applying user restrictions: userId=" + userId
1122 + " new=" + effective + " prev=" + prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001123 }
1124
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001125 if (mAppOpsService != null) { // We skip it until system-ready.
1126 final long token = Binder.clearCallingIdentity();
1127 try {
Svet Ganov9cea80cd2016-02-16 11:47:00 -08001128 mAppOpsService.setUserRestrictions(effective, mUserRestriconToken, userId);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001129 } catch (RemoteException e) {
1130 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
1131 } finally {
1132 Binder.restoreCallingIdentity(token);
1133 }
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001134 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001135
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001136 propagateUserRestrictionsLR(userId, effective, prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001137
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001138 mAppliedUserRestrictions.put(userId, new Bundle(effective));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001139 }
1140
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001141 private void propagateUserRestrictionsLR(final int userId,
Makoto Onukid45a4a22015-11-02 17:17:38 -08001142 Bundle newRestrictions, Bundle prevRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001143 // Note this method doesn't touch any state, meaning it doesn't require mRestrictionsLock
1144 // actually, but we still need some kind of synchronization otherwise we might end up
1145 // calling listeners out-of-order, thus "LR".
1146
1147 if (UserRestrictionsUtils.areEqual(newRestrictions, prevRestrictions)) {
1148 return;
1149 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08001150
1151 final Bundle newRestrictionsFinal = new Bundle(newRestrictions);
1152 final Bundle prevRestrictionsFinal = new Bundle(prevRestrictions);
1153
1154 mHandler.post(new Runnable() {
1155 @Override
1156 public void run() {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07001157 UserRestrictionsUtils.applyUserRestrictions(
1158 mContext, userId, newRestrictionsFinal, prevRestrictionsFinal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001159
Makoto Onukid45a4a22015-11-02 17:17:38 -08001160 final UserRestrictionsListener[] listeners;
1161 synchronized (mUserRestrictionsListeners) {
1162 listeners = new UserRestrictionsListener[mUserRestrictionsListeners.size()];
1163 mUserRestrictionsListeners.toArray(listeners);
1164 }
1165 for (int i = 0; i < listeners.length; i++) {
1166 listeners[i].onUserRestrictionsChanged(userId,
1167 newRestrictionsFinal, prevRestrictionsFinal);
1168 }
1169 }
1170 });
1171 }
1172
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001173 // Package private for the inner class.
1174 void applyUserRestrictionsLR(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001175 updateUserRestrictionsInternalLR(null, userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001176 }
1177
1178 @GuardedBy("mRestrictionsLock")
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001179 // Package private for the inner class.
1180 void applyUserRestrictionsForAllUsersLR() {
1181 if (DBG) {
1182 debug("applyUserRestrictionsForAllUsersLR");
1183 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001184 // First, invalidate all cached values.
Makoto Onuki4f160732015-10-27 17:15:38 -07001185 mCachedEffectiveUserRestrictions.clear();
1186
Makoto Onuki068c54a2015-10-13 14:34:03 -07001187 // We don't want to call into ActivityManagerNative while taking a lock, so we'll call
1188 // it on a handler.
1189 final Runnable r = new Runnable() {
1190 @Override
1191 public void run() {
1192 // Then get the list of running users.
1193 final int[] runningUsers;
1194 try {
1195 runningUsers = ActivityManagerNative.getDefault().getRunningUserIds();
1196 } catch (RemoteException e) {
1197 Log.w(LOG_TAG, "Unable to access ActivityManagerNative");
1198 return;
1199 }
1200 // Then re-calculate the effective restrictions and apply, only for running users.
1201 // It's okay if a new user has started after the getRunningUserIds() call,
1202 // because we'll do the same thing (re-calculate the restrictions and apply)
1203 // when we start a user.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001204 synchronized (mRestrictionsLock) {
1205 for (int i = 0; i < runningUsers.length; i++) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001206 applyUserRestrictionsLR(runningUsers[i]);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001207 }
1208 }
1209 }
1210 };
1211 mHandler.post(r);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001212 }
1213
Amith Yamasani258848d2012-08-10 17:06:33 -07001214 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001215 * Check if we've hit the limit of how many users can be created.
1216 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001217 private boolean isUserLimitReached() {
1218 int count;
1219 synchronized (mUsersLock) {
1220 count = getAliveUsersExcludingGuestsCountLU();
1221 }
1222 return count >= UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001223 }
1224
1225 @Override
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001226 public boolean canAddMoreManagedProfiles(int userId, boolean allowedToRemoveOne) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001227 checkManageUsersPermission("check if more managed profiles can be added.");
1228 if (ActivityManager.isLowRamDeviceStatic()) {
1229 return false;
1230 }
Fyodor Kupolovb6157992015-06-05 15:32:28 -07001231 if (!mContext.getPackageManager().hasSystemFeature(
1232 PackageManager.FEATURE_MANAGED_USERS)) {
1233 return false;
1234 }
Nicolas Prevotb8186812015-08-06 15:00:03 +01001235 // Limit number of managed profiles that can be created
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001236 final int managedProfilesCount = getProfiles(userId, true).size() - 1;
1237 final int profilesRemovedCount = managedProfilesCount > 0 && allowedToRemoveOne ? 1 : 0;
1238 if (managedProfilesCount - profilesRemovedCount >= MAX_MANAGED_PROFILES) {
Nicolas Prevotb8186812015-08-06 15:00:03 +01001239 return false;
1240 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001241 synchronized(mUsersLock) {
1242 UserInfo userInfo = getUserInfoLU(userId);
Nicolas Prevotb8186812015-08-06 15:00:03 +01001243 if (!userInfo.canHaveProfile()) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001244 return false;
1245 }
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001246 int usersCountAfterRemoving = getAliveUsersExcludingGuestsCountLU()
1247 - profilesRemovedCount;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001248 // We allow creating a managed profile in the special case where there is only one user.
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001249 return usersCountAfterRemoving == 1
1250 || usersCountAfterRemoving < UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001251 }
1252 }
1253
Fyodor Kupolov82402752015-10-28 14:54:51 -07001254 private int getAliveUsersExcludingGuestsCountLU() {
Amith Yamasanif584f012014-05-19 17:57:25 -07001255 int aliveUserCount = 0;
1256 final int totalUserCount = mUsers.size();
1257 // Skip over users being removed
1258 for (int i = 0; i < totalUserCount; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001259 UserInfo user = mUsers.valueAt(i).info;
Amith Yamasani95ab7842014-08-11 17:09:26 -07001260 if (!mRemovingUserIds.get(user.id)
Amith Yamasani1df14732014-08-29 21:37:27 -07001261 && !user.isGuest() && !user.partial) {
Amith Yamasanif584f012014-05-19 17:57:25 -07001262 aliveUserCount++;
1263 }
1264 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001265 return aliveUserCount;
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001266 }
1267
1268 /**
Amith Yamasani195263742012-08-21 15:40:12 -07001269 * Enforces that only the system UID or root's UID or apps that have the
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001270 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} and
1271 * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL INTERACT_ACROSS_USERS_FULL}
1272 * permissions can make certain calls to the UserManager.
1273 *
1274 * @param message used as message if SecurityException is thrown
1275 * @throws SecurityException if the caller does not have enough privilege.
1276 */
1277 private static final void checkManageUserAndAcrossUsersFullPermission(String message) {
1278 final int uid = Binder.getCallingUid();
1279 if (uid != Process.SYSTEM_UID && uid != 0
1280 && ActivityManager.checkComponentPermission(
1281 Manifest.permission.MANAGE_USERS,
1282 uid, -1, true) != PackageManager.PERMISSION_GRANTED
1283 && ActivityManager.checkComponentPermission(
1284 Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1285 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
1286 throw new SecurityException(
1287 "You need MANAGE_USERS and INTERACT_ACROSS_USERS_FULL permission to: "
1288 + message);
1289 }
1290 }
1291
1292 /**
1293 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001294 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -07001295 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -07001296 *
1297 * @param message used as message if SecurityException is thrown
1298 * @throws SecurityException if the caller is not system or root
Tony Mak4dc008c2016-03-16 10:46:49 +00001299 * @see #hasManageUsersPermission()
Amith Yamasani258848d2012-08-10 17:06:33 -07001300 */
Amith Yamasanibe465322014-04-24 13:45:17 -07001301 private static final void checkManageUsersPermission(String message) {
Tony Mak4dc008c2016-03-16 10:46:49 +00001302 if (!hasManageUsersPermission()) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001303 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
1304 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -04001305 }
1306
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001307 /**
Tony Mak4dc008c2016-03-16 10:46:49 +00001308 * @return whether the calling UID is system UID or root's UID or the calling app has the
1309 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}.
1310 */
1311 private static final boolean hasManageUsersPermission() {
1312 final int callingUid = Binder.getCallingUid();
1313 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
1314 || callingUid == Process.ROOT_UID
1315 || ActivityManager.checkComponentPermission(
1316 android.Manifest.permission.MANAGE_USERS,
1317 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED;
1318 }
1319
1320 /**
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001321 * Enforces that only the system UID or root's UID (on any user) can make certain calls to the
1322 * UserManager.
1323 *
1324 * @param message used as message if SecurityException is thrown
1325 * @throws SecurityException if the caller is not system or root
1326 */
1327 private static void checkSystemOrRoot(String message) {
1328 final int uid = Binder.getCallingUid();
1329 if (!UserHandle.isSameApp(uid, Process.SYSTEM_UID) && uid != Process.ROOT_UID) {
1330 throw new SecurityException("Only system may: " + message);
1331 }
1332 }
1333
Fyodor Kupolov82402752015-10-28 14:54:51 -07001334 private void writeBitmapLP(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001335 try {
1336 File dir = new File(mUsersDir, Integer.toString(info.id));
1337 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +01001338 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001339 if (!dir.exists()) {
1340 dir.mkdir();
1341 FileUtils.setPermissions(
1342 dir.getPath(),
1343 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
1344 -1, -1);
1345 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001346 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +01001347 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001348 && tmp.renameTo(file) && SELinux.restorecon(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -07001349 info.iconPath = file.getAbsolutePath();
1350 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001351 try {
1352 os.close();
1353 } catch (IOException ioe) {
1354 // What the ... !
1355 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001356 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001357 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001358 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001359 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001360 }
1361
Amith Yamasani0b285492011-04-14 17:35:23 -07001362 /**
1363 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
1364 * cache it elsewhere.
1365 * @return the array of user ids.
1366 */
Dianne Hackborn1676c852012-09-10 14:52:30 -07001367 public int[] getUserIds() {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001368 synchronized (mUsersLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001369 return mUserIds;
1370 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001371 }
1372
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001373 private void readUserListLP() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001374 if (!mUserListFile.exists()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001375 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001376 return;
1377 }
1378 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001379 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001380 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001381 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001382 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001383 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001384 int type;
1385 while ((type = parser.next()) != XmlPullParser.START_TAG
1386 && type != XmlPullParser.END_DOCUMENT) {
Amith Yamasani12747872015-12-07 14:19:49 -08001387 // Skip
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001388 }
1389
1390 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001391 Slog.e(LOG_TAG, "Unable to read user list");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001392 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001393 return;
1394 }
1395
Amith Yamasani2a003292012-08-14 18:25:45 -07001396 mNextSerialNumber = -1;
1397 if (parser.getName().equals(TAG_USERS)) {
1398 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
1399 if (lastSerialNumber != null) {
1400 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
1401 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001402 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
1403 if (versionNumber != null) {
1404 mUserVersion = Integer.parseInt(versionNumber);
1405 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001406 }
1407
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001408 final Bundle newDevicePolicyGlobalUserRestrictions = new Bundle();
1409
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001410 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301411 if (type == XmlPullParser.START_TAG) {
1412 final String name = parser.getName();
1413 if (name.equals(TAG_USER)) {
1414 String id = parser.getAttributeValue(null, ATTR_ID);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001415
Amith Yamasani12747872015-12-07 14:19:49 -08001416 UserData userData = readUserLP(Integer.parseInt(id));
1417
1418 if (userData != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001419 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001420 mUsers.put(userData.info.id, userData);
1421 if (mNextSerialNumber < 0
1422 || mNextSerialNumber <= userData.info.id) {
1423 mNextSerialNumber = userData.info.id + 1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001424 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301425 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001426 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301427 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -08001428 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1429 && type != XmlPullParser.END_TAG) {
1430 if (type == XmlPullParser.START_TAG) {
1431 if (parser.getName().equals(TAG_RESTRICTIONS)) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001432 synchronized (mGuestRestrictions) {
1433 UserRestrictionsUtils
1434 .readRestrictions(parser, mGuestRestrictions);
1435 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001436 } else if (parser.getName().equals(TAG_DEVICE_POLICY_RESTRICTIONS)
1437 ) {
1438 UserRestrictionsUtils.readRestrictions(parser,
1439 newDevicePolicyGlobalUserRestrictions);
Amith Yamasanida0b1682014-11-21 12:58:17 -08001440 }
1441 break;
1442 }
1443 }
Amith Yamasani258848d2012-08-10 17:06:33 -07001444 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001445 }
1446 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001447 synchronized (mRestrictionsLock) {
1448 mDevicePolicyGlobalUserRestrictions = newDevicePolicyGlobalUserRestrictions;
1449 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001450 updateUserIds();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001451 upgradeIfNecessaryLP();
1452 } catch (IOException | XmlPullParserException e) {
1453 fallbackToSingleUserLP();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001454 } finally {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001455 IoUtils.closeQuietly(fis);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001456 }
1457 }
1458
Amith Yamasani6f34b412012-10-22 18:19:27 -07001459 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -08001460 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -07001461 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001462 private void upgradeIfNecessaryLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001463 final int originalVersion = mUserVersion;
Amith Yamasani6f34b412012-10-22 18:19:27 -07001464 int userVersion = mUserVersion;
1465 if (userVersion < 1) {
1466 // Assign a proper name for the owner, if not initialized correctly before
Amith Yamasani12747872015-12-07 14:19:49 -08001467 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
1468 if ("Primary".equals(userData.info.name)) {
1469 userData.info.name =
1470 mContext.getResources().getString(com.android.internal.R.string.owner_name);
1471 scheduleWriteUser(userData);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001472 }
1473 userVersion = 1;
1474 }
1475
Amith Yamasanibc9625052012-11-15 14:39:18 -08001476 if (userVersion < 2) {
1477 // Owner should be marked as initialized
Amith Yamasani12747872015-12-07 14:19:49 -08001478 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
1479 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1480 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
1481 scheduleWriteUser(userData);
Amith Yamasanibc9625052012-11-15 14:39:18 -08001482 }
1483 userVersion = 2;
1484 }
1485
Amith Yamasani350962c2013-08-06 11:18:53 -07001486
Amith Yamasani5e486f52013-08-07 11:06:44 -07001487 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -07001488 userVersion = 4;
1489 }
1490
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001491 if (userVersion < 5) {
1492 initDefaultGuestRestrictions();
1493 userVersion = 5;
1494 }
1495
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001496 if (userVersion < 6) {
1497 final boolean splitSystemUser = UserManager.isSplitSystemUser();
Fyodor Kupolov82402752015-10-28 14:54:51 -07001498 synchronized (mUsersLock) {
1499 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001500 UserData userData = mUsers.valueAt(i);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001501 // In non-split mode, only user 0 can have restricted profiles
Amith Yamasani12747872015-12-07 14:19:49 -08001502 if (!splitSystemUser && userData.info.isRestricted()
1503 && (userData.info.restrictedProfileParentId
1504 == UserInfo.NO_PROFILE_GROUP_ID)) {
1505 userData.info.restrictedProfileParentId = UserHandle.USER_SYSTEM;
1506 scheduleWriteUser(userData);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001507 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001508 }
1509 }
1510 userVersion = 6;
1511 }
1512
Amith Yamasani6f34b412012-10-22 18:19:27 -07001513 if (userVersion < USER_VERSION) {
1514 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
1515 + USER_VERSION);
1516 } else {
1517 mUserVersion = userVersion;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001518
1519 if (originalVersion < mUserVersion) {
1520 writeUserListLP();
1521 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001522 }
1523 }
1524
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001525 private void fallbackToSingleUserLP() {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001526 int flags = UserInfo.FLAG_INITIALIZED;
1527 // In split system user mode, the admin and primary flags are assigned to the first human
1528 // user.
1529 if (!UserManager.isSplitSystemUser()) {
1530 flags |= UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY;
1531 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001532 // Create the system user
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001533 UserInfo system = new UserInfo(UserHandle.USER_SYSTEM, null, null, flags);
Amith Yamasani12747872015-12-07 14:19:49 -08001534 UserData userData = new UserData();
1535 userData.info = system;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001536 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001537 mUsers.put(system.id, userData);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001538 }
Amith Yamasani634cf312012-10-04 17:34:21 -07001539 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -04001540 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -08001541
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001542 Bundle restrictions = new Bundle();
Makoto Onuki068c54a2015-10-13 14:34:03 -07001543 synchronized (mRestrictionsLock) {
1544 mBaseUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions);
1545 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001546
Fyodor Kupolov82402752015-10-28 14:54:51 -07001547 updateUserIds();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001548 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001549
Amith Yamasani12747872015-12-07 14:19:49 -08001550 writeUserLP(userData);
Jeff Sharkeycd575992016-03-29 14:12:49 -06001551 writeUserListLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001552 }
1553
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001554 private String getOwnerName() {
1555 return mContext.getResources().getString(com.android.internal.R.string.owner_name);
1556 }
1557
Amith Yamasani12747872015-12-07 14:19:49 -08001558 private void scheduleWriteUser(UserData UserData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001559 if (DBG) {
1560 debug("scheduleWriteUser");
1561 }
Makoto Onuki9e935a32015-11-06 14:24:24 -08001562 // No need to wrap it within a lock -- worst case, we'll just post the same message
1563 // twice.
Amith Yamasani12747872015-12-07 14:19:49 -08001564 if (!mHandler.hasMessages(WRITE_USER_MSG, UserData)) {
1565 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, UserData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001566 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
1567 }
1568 }
1569
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001570 /*
1571 * Writes the user file in this format:
1572 *
1573 * <user flags="20039023" id="0">
1574 * <name>Primary</name>
1575 * </user>
1576 */
Amith Yamasani12747872015-12-07 14:19:49 -08001577 private void writeUserLP(UserData userData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001578 if (DBG) {
Amith Yamasani12747872015-12-07 14:19:49 -08001579 debug("writeUserLP " + userData);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001580 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001581 FileOutputStream fos = null;
Amith Yamasani12747872015-12-07 14:19:49 -08001582 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userData.info.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001583 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001584 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001585 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1586
1587 // XmlSerializer serializer = XmlUtils.serializerInstance();
1588 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001589 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001590 serializer.startDocument(null, true);
1591 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1592
Amith Yamasani12747872015-12-07 14:19:49 -08001593 final UserInfo userInfo = userData.info;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001594 serializer.startTag(null, TAG_USER);
1595 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
Amith Yamasani2a003292012-08-14 18:25:45 -07001596 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001597 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Amith Yamasani920ace02012-09-20 22:15:37 -07001598 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
1599 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
1600 Long.toString(userInfo.lastLoggedInTime));
Jeff Sharkeycd575992016-03-29 14:12:49 -06001601 if (userInfo.lastLoggedInFingerprint != null) {
1602 serializer.attribute(null, ATTR_LAST_LOGGED_IN_FINGERPRINT,
1603 userInfo.lastLoggedInFingerprint);
1604 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001605 if (userInfo.iconPath != null) {
1606 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
1607 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001608 if (userInfo.partial) {
1609 serializer.attribute(null, ATTR_PARTIAL, "true");
1610 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001611 if (userInfo.guestToRemove) {
1612 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
1613 }
Kenny Guy2a764942014-04-02 13:29:20 +01001614 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
1615 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
1616 Integer.toString(userInfo.profileGroupId));
Kenny Guya52dc3e2014-02-11 15:33:14 +00001617 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001618 if (userInfo.restrictedProfileParentId != UserInfo.NO_PROFILE_GROUP_ID) {
1619 serializer.attribute(null, ATTR_RESTRICTED_PROFILE_PARENT_ID,
1620 Integer.toString(userInfo.restrictedProfileParentId));
1621 }
Amith Yamasani12747872015-12-07 14:19:49 -08001622 // Write seed data
1623 if (userData.persistSeedData) {
1624 if (userData.seedAccountName != null) {
1625 serializer.attribute(null, ATTR_SEED_ACCOUNT_NAME, userData.seedAccountName);
1626 }
1627 if (userData.seedAccountType != null) {
1628 serializer.attribute(null, ATTR_SEED_ACCOUNT_TYPE, userData.seedAccountType);
1629 }
1630 }
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001631 if (userInfo.name != null) {
1632 serializer.startTag(null, TAG_NAME);
1633 serializer.text(userInfo.name);
1634 serializer.endTag(null, TAG_NAME);
1635 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001636 synchronized (mRestrictionsLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001637 UserRestrictionsUtils.writeRestrictions(serializer,
1638 mBaseUserRestrictions.get(userInfo.id), TAG_RESTRICTIONS);
1639 UserRestrictionsUtils.writeRestrictions(serializer,
1640 mDevicePolicyLocalUserRestrictions.get(userInfo.id),
1641 TAG_DEVICE_POLICY_RESTRICTIONS);
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001642 }
Amith Yamasani12747872015-12-07 14:19:49 -08001643
1644 if (userData.account != null) {
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001645 serializer.startTag(null, TAG_ACCOUNT);
Amith Yamasani12747872015-12-07 14:19:49 -08001646 serializer.text(userData.account);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001647 serializer.endTag(null, TAG_ACCOUNT);
1648 }
1649
Amith Yamasani12747872015-12-07 14:19:49 -08001650 if (userData.persistSeedData && userData.seedAccountOptions != null) {
1651 serializer.startTag(null, TAG_SEED_ACCOUNT_OPTIONS);
1652 userData.seedAccountOptions.saveToXml(serializer);
1653 serializer.endTag(null, TAG_SEED_ACCOUNT_OPTIONS);
1654 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001655 serializer.endTag(null, TAG_USER);
1656
1657 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001658 userFile.finishWrite(fos);
1659 } catch (Exception ioe) {
Jeff Sharkeycd575992016-03-29 14:12:49 -06001660 Slog.e(LOG_TAG, "Error writing user info " + userData.info.id, ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -07001661 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001662 }
1663 }
1664
1665 /*
1666 * Writes the user list file in this format:
1667 *
Amith Yamasani2a003292012-08-14 18:25:45 -07001668 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001669 * <user id="0"></user>
1670 * <user id="2"></user>
1671 * </users>
1672 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001673 private void writeUserListLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001674 if (DBG) {
1675 debug("writeUserList");
1676 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001677 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001678 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001679 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001680 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001681 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1682
1683 // XmlSerializer serializer = XmlUtils.serializerInstance();
1684 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001685 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001686 serializer.startDocument(null, true);
1687 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1688
1689 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -07001690 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -07001691 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001692
Adam Lesinskieddeb492014-09-08 17:50:03 -07001693 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001694 synchronized (mGuestRestrictions) {
1695 UserRestrictionsUtils
1696 .writeRestrictions(serializer, mGuestRestrictions, TAG_RESTRICTIONS);
1697 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301698 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001699 synchronized (mRestrictionsLock) {
1700 UserRestrictionsUtils.writeRestrictions(serializer,
1701 mDevicePolicyGlobalUserRestrictions, TAG_DEVICE_POLICY_RESTRICTIONS);
1702 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001703 int[] userIdsToWrite;
1704 synchronized (mUsersLock) {
1705 userIdsToWrite = new int[mUsers.size()];
1706 for (int i = 0; i < userIdsToWrite.length; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001707 UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001708 userIdsToWrite[i] = user.id;
1709 }
1710 }
1711 for (int id : userIdsToWrite) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001712 serializer.startTag(null, TAG_USER);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001713 serializer.attribute(null, ATTR_ID, Integer.toString(id));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001714 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001715 }
1716
1717 serializer.endTag(null, TAG_USERS);
1718
1719 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001720 userListFile.finishWrite(fos);
1721 } catch (Exception e) {
1722 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -07001723 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001724 }
1725 }
1726
Amith Yamasani12747872015-12-07 14:19:49 -08001727 private UserData readUserLP(int id) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001728 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -07001729 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001730 String name = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001731 String account = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001732 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -07001733 long creationTime = 0L;
1734 long lastLoggedInTime = 0L;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06001735 String lastLoggedInFingerprint = null;
Kenny Guy2a764942014-04-02 13:29:20 +01001736 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001737 int restrictedProfileParentId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001738 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001739 boolean guestToRemove = false;
Amith Yamasani12747872015-12-07 14:19:49 -08001740 boolean persistSeedData = false;
1741 String seedAccountName = null;
1742 String seedAccountType = null;
1743 PersistableBundle seedAccountOptions = null;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001744 Bundle baseRestrictions = new Bundle();
1745 Bundle localRestrictions = new Bundle();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001746
1747 FileInputStream fis = null;
1748 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001749 AtomicFile userFile =
Amith Yamasanifc95e702013-09-26 13:20:17 -07001750 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
Amith Yamasani2a003292012-08-14 18:25:45 -07001751 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001752 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001753 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001754 int type;
1755 while ((type = parser.next()) != XmlPullParser.START_TAG
1756 && type != XmlPullParser.END_DOCUMENT) {
Amith Yamasani12747872015-12-07 14:19:49 -08001757 // Skip
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001758 }
1759
1760 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001761 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001762 return null;
1763 }
1764
1765 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001766 int storedId = readIntAttribute(parser, ATTR_ID, -1);
1767 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001768 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001769 return null;
1770 }
Amith Yamasani920ace02012-09-20 22:15:37 -07001771 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
1772 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001773 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -07001774 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
1775 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06001776 lastLoggedInFingerprint = parser.getAttributeValue(null,
1777 ATTR_LAST_LOGGED_IN_FINGERPRINT);
Kenny Guy2a764942014-04-02 13:29:20 +01001778 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
1779 UserInfo.NO_PROFILE_GROUP_ID);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001780 restrictedProfileParentId = readIntAttribute(parser,
1781 ATTR_RESTRICTED_PROFILE_PARENT_ID, UserInfo.NO_PROFILE_GROUP_ID);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001782 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
1783 if ("true".equals(valueString)) {
1784 partial = true;
1785 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001786 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
1787 if ("true".equals(valueString)) {
1788 guestToRemove = true;
1789 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001790
Amith Yamasani12747872015-12-07 14:19:49 -08001791 seedAccountName = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_NAME);
1792 seedAccountType = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_TYPE);
1793 if (seedAccountName != null || seedAccountType != null) {
1794 persistSeedData = true;
1795 }
1796
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001797 int outerDepth = parser.getDepth();
1798 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1799 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1800 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1801 continue;
1802 }
1803 String tag = parser.getName();
1804 if (TAG_NAME.equals(tag)) {
1805 type = parser.next();
1806 if (type == XmlPullParser.TEXT) {
1807 name = parser.getText();
1808 }
1809 } else if (TAG_RESTRICTIONS.equals(tag)) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001810 UserRestrictionsUtils.readRestrictions(parser, baseRestrictions);
1811 } else if (TAG_DEVICE_POLICY_RESTRICTIONS.equals(tag)) {
1812 UserRestrictionsUtils.readRestrictions(parser, localRestrictions);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001813 } else if (TAG_ACCOUNT.equals(tag)) {
1814 type = parser.next();
1815 if (type == XmlPullParser.TEXT) {
1816 account = parser.getText();
1817 }
Amith Yamasani12747872015-12-07 14:19:49 -08001818 } else if (TAG_SEED_ACCOUNT_OPTIONS.equals(tag)) {
1819 seedAccountOptions = PersistableBundle.restoreFromXml(parser);
1820 persistSeedData = true;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001821 }
1822 }
1823 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001824
Amith Yamasani12747872015-12-07 14:19:49 -08001825 // Create the UserInfo object that gets passed around
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001826 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -07001827 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -07001828 userInfo.creationTime = creationTime;
1829 userInfo.lastLoggedInTime = lastLoggedInTime;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06001830 userInfo.lastLoggedInFingerprint = lastLoggedInFingerprint;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001831 userInfo.partial = partial;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001832 userInfo.guestToRemove = guestToRemove;
Kenny Guy2a764942014-04-02 13:29:20 +01001833 userInfo.profileGroupId = profileGroupId;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001834 userInfo.restrictedProfileParentId = restrictedProfileParentId;
Amith Yamasani12747872015-12-07 14:19:49 -08001835
1836 // Create the UserData object that's internal to this class
1837 UserData userData = new UserData();
1838 userData.info = userInfo;
1839 userData.account = account;
1840 userData.seedAccountName = seedAccountName;
1841 userData.seedAccountType = seedAccountType;
1842 userData.persistSeedData = persistSeedData;
1843 userData.seedAccountOptions = seedAccountOptions;
1844
Makoto Onuki068c54a2015-10-13 14:34:03 -07001845 synchronized (mRestrictionsLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001846 mBaseUserRestrictions.put(id, baseRestrictions);
1847 mDevicePolicyLocalUserRestrictions.put(id, localRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001848 }
Amith Yamasani12747872015-12-07 14:19:49 -08001849 return userData;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001850 } catch (IOException ioe) {
1851 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001852 } finally {
1853 if (fis != null) {
1854 try {
1855 fis.close();
1856 } catch (IOException e) {
1857 }
1858 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001859 }
1860 return null;
1861 }
1862
Amith Yamasani920ace02012-09-20 22:15:37 -07001863 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
1864 String valueString = parser.getAttributeValue(null, attr);
1865 if (valueString == null) return defaultValue;
1866 try {
1867 return Integer.parseInt(valueString);
1868 } catch (NumberFormatException nfe) {
1869 return defaultValue;
1870 }
1871 }
1872
1873 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
1874 String valueString = parser.getAttributeValue(null, attr);
1875 if (valueString == null) return defaultValue;
1876 try {
1877 return Long.parseLong(valueString);
1878 } catch (NumberFormatException nfe) {
1879 return defaultValue;
1880 }
1881 }
1882
Amith Yamasanib82add22013-07-09 11:24:44 -07001883 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001884 * Removes the app restrictions file for a specific package and user id, if it exists.
1885 */
1886 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
1887 synchronized (mPackagesLock) {
1888 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07001889 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001890 if (resFile.exists()) {
1891 resFile.delete();
1892 }
1893 }
1894 }
1895
Kenny Guya52dc3e2014-02-11 15:33:14 +00001896 @Override
Kenny Guy2a764942014-04-02 13:29:20 +01001897 public UserInfo createProfileForUser(String name, int flags, int userId) {
Kenny Guya52dc3e2014-02-11 15:33:14 +00001898 checkManageUsersPermission("Only the system can create users");
Kenny Guy2a764942014-04-02 13:29:20 +01001899 return createUserInternal(name, flags, userId);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001900 }
1901
Amith Yamasani258848d2012-08-10 17:06:33 -07001902 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07001903 public UserInfo createUser(String name, int flags) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001904 checkManageUsersPermission("Only the system can create users");
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001905 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001906 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001907
Jessica Hummelbe81c802014-04-22 15:49:22 +01001908 private UserInfo createUserInternal(String name, int flags, int parentId) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001909 if (hasUserRestriction(UserManager.DISALLOW_ADD_USER, UserHandle.getCallingUserId())) {
Julia Reynolds75175022014-06-26 16:35:00 -04001910 Log.w(LOG_TAG, "Cannot add user. DISALLOW_ADD_USER is enabled.");
1911 return null;
1912 }
phweisse9c44062016-02-10 12:57:38 +01001913 return createUserInternalUnchecked(name, flags, parentId);
1914 }
1915
1916 private UserInfo createUserInternalUnchecked(String name, int flags, int parentId) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001917 if (ActivityManager.isLowRamDeviceStatic()) {
1918 return null;
1919 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07001920 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001921 final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001922 final boolean isRestricted = (flags & UserInfo.FLAG_RESTRICTED) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001923 final long ident = Binder.clearCallingIdentity();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001924 UserInfo userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08001925 UserData userData;
Amith Yamasanibb054c92015-07-09 14:16:27 -07001926 final int userId;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001927 try {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001928 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001929 UserData parent = null;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001930 if (parentId != UserHandle.USER_NULL) {
1931 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001932 parent = getUserDataLU(parentId);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001933 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001934 if (parent == null) return null;
1935 }
1936 if (isManagedProfile && !canAddMoreManagedProfiles(parentId, false)) {
1937 Log.e(LOG_TAG, "Cannot add more managed profiles for user " + parentId);
1938 return null;
1939 }
1940 if (!isGuest && !isManagedProfile && isUserLimitReached()) {
1941 // If we're not adding a guest user or a managed profile and the limit has
1942 // been reached, cannot add a user.
1943 return null;
1944 }
1945 // If we're adding a guest and there already exists one, bail.
1946 if (isGuest && findCurrentGuestUser() != null) {
1947 return null;
1948 }
1949 // In legacy mode, restricted profile's parent can only be the owner user
1950 if (isRestricted && !UserManager.isSplitSystemUser()
1951 && (parentId != UserHandle.USER_SYSTEM)) {
1952 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
1953 return null;
1954 }
1955 if (isRestricted && UserManager.isSplitSystemUser()) {
1956 if (parent == null) {
1957 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be "
1958 + "specified");
Nicolas Prevot12678a92015-05-13 12:15:03 -07001959 return null;
1960 }
Amith Yamasani12747872015-12-07 14:19:49 -08001961 if (!parent.info.canHaveProfile()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001962 Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be "
1963 + "created for the specified parent user id " + parentId);
Amith Yamasani95ab7842014-08-11 17:09:26 -07001964 return null;
1965 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001966 }
Lenka Trochtova024f9792016-02-17 13:55:17 +01001967 if (!UserManager.isSplitSystemUser() && (flags & UserInfo.FLAG_EPHEMERAL) != 0) {
1968 Log.e(LOG_TAG,
1969 "Ephemeral users are supported on split-system-user systems only.");
1970 return null;
1971 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001972 // In split system user mode, we assign the first human user the primary flag.
1973 // And if there is no device owner, we also assign the admin flag to primary user.
1974 if (UserManager.isSplitSystemUser()
1975 && !isGuest && !isManagedProfile && getPrimaryUser() == null) {
1976 flags |= UserInfo.FLAG_PRIMARY;
Makoto Onukie7927da2015-11-25 10:05:17 -08001977 synchronized (mUsersLock) {
1978 if (!mIsDeviceManaged) {
1979 flags |= UserInfo.FLAG_ADMIN;
1980 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07001981 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001982 }
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01001983
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01001984 userId = getNextAvailableId();
1985 Environment.getUserSystemDirectory(userId).mkdirs();
Lenka Trochtova02fee152015-12-22 14:26:18 +01001986 boolean ephemeralGuests = Resources.getSystem()
1987 .getBoolean(com.android.internal.R.bool.config_guestUserEphemeral);
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01001988
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001989 synchronized (mUsersLock) {
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01001990 // Add ephemeral flag to guests/users if required. Also inherit it from parent.
1991 if ((isGuest && ephemeralGuests) || mForceEphemeralUsers
1992 || (parent != null && parent.info.isEphemeral())) {
1993 flags |= UserInfo.FLAG_EPHEMERAL;
1994 }
1995
1996 userInfo = new UserInfo(userId, name, null, flags);
1997 userInfo.serialNumber = mNextSerialNumber++;
1998 long now = System.currentTimeMillis();
1999 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
2000 userInfo.partial = true;
Fyodor Kupolov83c24242016-03-31 13:30:42 -07002001 userInfo.lastLoggedInFingerprint = Build.FINGERPRINT;
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002002 userData = new UserData();
2003 userData.info = userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08002004 mUsers.put(userId, userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002005 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06002006 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002007 writeUserListLP();
2008 if (parent != null) {
2009 if (isManagedProfile) {
Amith Yamasani12747872015-12-07 14:19:49 -08002010 if (parent.info.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
2011 parent.info.profileGroupId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002012 writeUserLP(parent);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002013 }
Amith Yamasani12747872015-12-07 14:19:49 -08002014 userInfo.profileGroupId = parent.info.profileGroupId;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002015 } else if (isRestricted) {
Amith Yamasani12747872015-12-07 14:19:49 -08002016 if (parent.info.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) {
2017 parent.info.restrictedProfileParentId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002018 writeUserLP(parent);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002019 }
Amith Yamasani12747872015-12-07 14:19:49 -08002020 userInfo.restrictedProfileParentId = parent.info.restrictedProfileParentId;
Makoto Onuki068c54a2015-10-13 14:34:03 -07002021 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002022 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07002023 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002024 final StorageManager storage = mContext.getSystemService(StorageManager.class);
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002025 storage.createUserKey(userId, userInfo.serialNumber, userInfo.isEphemeral());
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002026 mPm.prepareUserData(userId, userInfo.serialNumber,
Jeff Sharkey47f71082016-02-01 17:03:54 -07002027 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002028 mPm.createNewUser(userId);
2029 userInfo.partial = false;
2030 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002031 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002032 }
2033 updateUserIds();
2034 Bundle restrictions = new Bundle();
Fyodor Kupolove04462c2015-11-30 15:02:53 -08002035 if (isGuest) {
2036 synchronized (mGuestRestrictions) {
2037 restrictions.putAll(mGuestRestrictions);
2038 }
2039 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002040 synchronized (mRestrictionsLock) {
2041 mBaseUserRestrictions.append(userId, restrictions);
2042 }
2043 mPm.newUserCreated(userId);
2044 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
2045 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
2046 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
2047 android.Manifest.permission.MANAGE_USERS);
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -08002048 MetricsLogger.count(mContext, isGuest ? TRON_GUEST_CREATED : TRON_USER_CREATED, 1);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002049 } finally {
2050 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07002051 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002052 return userInfo;
2053 }
2054
Amith Yamasani0b285492011-04-14 17:35:23 -07002055 /**
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002056 * @hide
2057 */
Amith Yamasani12747872015-12-07 14:19:49 -08002058 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002059 public UserInfo createRestrictedProfile(String name, int parentUserId) {
2060 checkManageUsersPermission("setupRestrictedProfile");
2061 final UserInfo user = createProfileForUser(name, UserInfo.FLAG_RESTRICTED, parentUserId);
2062 if (user == null) {
2063 return null;
2064 }
Fyodor Kupolov9e912ba2016-02-09 18:29:43 -08002065 long identity = Binder.clearCallingIdentity();
2066 try {
2067 setUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, true, user.id);
2068 // Change the setting before applying the DISALLOW_SHARE_LOCATION restriction, otherwise
2069 // the putIntForUser() will fail.
2070 android.provider.Settings.Secure.putIntForUser(mContext.getContentResolver(),
2071 android.provider.Settings.Secure.LOCATION_MODE,
2072 android.provider.Settings.Secure.LOCATION_MODE_OFF, user.id);
2073 setUserRestriction(UserManager.DISALLOW_SHARE_LOCATION, true, user.id);
2074 } finally {
2075 Binder.restoreCallingIdentity(identity);
2076 }
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002077 return user;
2078 }
2079
2080 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07002081 * Find the current guest user. If the Guest user is partial,
2082 * then do not include it in the results as it is about to die.
Adam Lesinskieddeb492014-09-08 17:50:03 -07002083 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002084 private UserInfo findCurrentGuestUser() {
2085 synchronized (mUsersLock) {
2086 final int size = mUsers.size();
2087 for (int i = 0; i < size; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002088 final UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002089 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
2090 return user;
2091 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002092 }
2093 }
2094 return null;
2095 }
2096
2097 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07002098 * Mark this guest user for deletion to allow us to create another guest
2099 * and switch to that user before actually removing this guest.
2100 * @param userHandle the userid of the current guest
2101 * @return whether the user could be marked for deletion
2102 */
Amith Yamasani12747872015-12-07 14:19:49 -08002103 @Override
Amith Yamasani1df14732014-08-29 21:37:27 -07002104 public boolean markGuestForDeletion(int userHandle) {
2105 checkManageUsersPermission("Only the system can remove users");
2106 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
2107 UserManager.DISALLOW_REMOVE_USER, false)) {
2108 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
2109 return false;
2110 }
2111
2112 long ident = Binder.clearCallingIdentity();
2113 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002114 final UserData userData;
Amith Yamasani1df14732014-08-29 21:37:27 -07002115 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002116 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002117 userData = mUsers.get(userHandle);
2118 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002119 return false;
2120 }
Amith Yamasani1df14732014-08-29 21:37:27 -07002121 }
Amith Yamasani12747872015-12-07 14:19:49 -08002122 if (!userData.info.isGuest()) {
Amith Yamasani1df14732014-08-29 21:37:27 -07002123 return false;
2124 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002125 // We set this to a guest user that is to be removed. This is a temporary state
2126 // where we are allowed to add new Guest users, even if this one is still not
2127 // removed. This user will still show up in getUserInfo() calls.
2128 // If we don't get around to removing this Guest user, it will be purged on next
2129 // startup.
Amith Yamasani12747872015-12-07 14:19:49 -08002130 userData.info.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07002131 // Mark it as disabled, so that it isn't returned any more when
2132 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002133 userData.info.flags |= UserInfo.FLAG_DISABLED;
2134 writeUserLP(userData);
Amith Yamasani1df14732014-08-29 21:37:27 -07002135 }
2136 } finally {
2137 Binder.restoreCallingIdentity(ident);
2138 }
2139 return true;
2140 }
2141
2142 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002143 * Removes a user and all data directories created for that user. This method should be called
2144 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07002145 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07002146 */
Amith Yamasani12747872015-12-07 14:19:49 -08002147 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -07002148 public boolean removeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002149 checkManageUsersPermission("Only the system can remove users");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04002150 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
2151 UserManager.DISALLOW_REMOVE_USER, false)) {
2152 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
2153 return false;
2154 }
2155
Kenny Guyee58b4f2014-05-23 15:19:53 +01002156 long ident = Binder.clearCallingIdentity();
2157 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002158 final UserData userData;
Fyodor Kupolov0df68cd2015-10-01 13:54:22 -07002159 int currentUser = ActivityManager.getCurrentUser();
2160 if (currentUser == userHandle) {
2161 Log.w(LOG_TAG, "Current user cannot be removed");
2162 return false;
2163 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002164 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002165 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002166 userData = mUsers.get(userHandle);
2167 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002168 return false;
2169 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002170
Fyodor Kupolov82402752015-10-28 14:54:51 -07002171 // We remember deleted user IDs to prevent them from being
2172 // reused during the current boot; they can still be reused
2173 // after a reboot.
2174 mRemovingUserIds.put(userHandle, true);
2175 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002176
Kenny Guyee58b4f2014-05-23 15:19:53 +01002177 try {
2178 mAppOpsService.removeUser(userHandle);
2179 } catch (RemoteException e) {
2180 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
2181 }
2182 // Set this to a partially created user, so that the user will be purged
2183 // on next startup, in case the runtime stops now before stopping and
2184 // removing the user completely.
Amith Yamasani12747872015-12-07 14:19:49 -08002185 userData.info.partial = true;
Kenny Guyee58b4f2014-05-23 15:19:53 +01002186 // Mark it as disabled, so that it isn't returned any more when
2187 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002188 userData.info.flags |= UserInfo.FLAG_DISABLED;
2189 writeUserLP(userData);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002190 }
2191
Amith Yamasani12747872015-12-07 14:19:49 -08002192 if (userData.info.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
2193 && userData.info.isManagedProfile()) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002194 // Send broadcast to notify system that the user removed was a
2195 // managed user.
Amith Yamasani12747872015-12-07 14:19:49 -08002196 sendProfileRemovedBroadcast(userData.info.profileGroupId, userData.info.id);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002197 }
2198
2199 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
2200 int res;
2201 try {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07002202 res = ActivityManagerNative.getDefault().stopUser(userHandle, /* force= */ true,
2203 new IStopUserCallback.Stub() {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002204 @Override
2205 public void userStopped(int userId) {
2206 finishRemoveUser(userId);
2207 }
2208 @Override
2209 public void userStopAborted(int userId) {
2210 }
2211 });
2212 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002213 return false;
2214 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002215 return res == ActivityManager.USER_OP_SUCCESS;
2216 } finally {
2217 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002218 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002219 }
2220
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002221 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07002222 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002223 // Let other services shutdown any activity and clean up their state before completely
2224 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002225 long ident = Binder.clearCallingIdentity();
2226 try {
2227 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
2228 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002229 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
2230 android.Manifest.permission.MANAGE_USERS,
2231
2232 new BroadcastReceiver() {
2233 @Override
2234 public void onReceive(Context context, Intent intent) {
2235 if (DBG) {
2236 Slog.i(LOG_TAG,
2237 "USER_REMOVED broadcast sent, cleaning up user data "
2238 + userHandle);
2239 }
2240 new Thread() {
Amith Yamasani12747872015-12-07 14:19:49 -08002241 @Override
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002242 public void run() {
Amith Yamasani515d4062015-09-28 11:30:06 -07002243 // Clean up any ActivityManager state
2244 LocalServices.getService(ActivityManagerInternal.class)
2245 .onUserRemoved(userHandle);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002246 removeUserState(userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002247 }
2248 }.start();
2249 }
2250 },
2251
2252 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002253 } finally {
2254 Binder.restoreCallingIdentity(ident);
2255 }
Amith Yamasani2a003292012-08-14 18:25:45 -07002256 }
2257
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002258 private void removeUserState(final int userHandle) {
Paul Crowley91293792016-03-25 15:23:07 -07002259 try {
2260 mContext.getSystemService(StorageManager.class).destroyUserKey(userHandle);
2261 } catch (IllegalStateException e) {
2262 // This may be simply because the user was partially created.
2263 Slog.i(LOG_TAG,
2264 "Destroying key for user " + userHandle + " failed, continuing anyway", e);
2265 }
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002266
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002267 // Cleanup package manager settings
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002268 mPm.cleanUpUser(this, userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002269 // Remove this user from the list
Fyodor Kupolov82402752015-10-28 14:54:51 -07002270 synchronized (mUsersLock) {
2271 mUsers.remove(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08002272 mIsUserManaged.delete(userHandle);
2273 }
2274 synchronized (mRestrictionsLock) {
2275 mBaseUserRestrictions.remove(userHandle);
2276 mAppliedUserRestrictions.remove(userHandle);
2277 mCachedEffectiveUserRestrictions.remove(userHandle);
2278 mDevicePolicyLocalUserRestrictions.remove(userHandle);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002279 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002280 // Update the user list
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002281 synchronized (mPackagesLock) {
2282 writeUserListLP();
2283 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06002284 // Remove user file
2285 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
2286 userFile.delete();
Fyodor Kupolov82402752015-10-28 14:54:51 -07002287 updateUserIds();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002288
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002289 // Now that we've purged all the metadata above, destroy the actual data
2290 // on disk; if we battery pull in here we'll finish cleaning up when
2291 // reconciling after reboot.
2292 mPm.destroyUserData(userHandle,
2293 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
Amith Yamasani61f57372012-08-31 12:12:28 -07002294 }
2295
Kenny Guyf8d3a232014-05-15 16:09:52 +01002296 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01002297 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01002298 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
2299 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002300 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
Jeff Sharkeyaf6ec292015-12-17 11:19:00 -07002301 managedProfileIntent.putExtra(Intent.EXTRA_USER_HANDLE, removedUserId);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002302 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01002303 }
2304
Amith Yamasani2a003292012-08-14 18:25:45 -07002305 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002306 public Bundle getApplicationRestrictions(String packageName) {
2307 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
2308 }
2309
2310 @Override
2311 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002312 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07002313 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00002314 checkSystemOrRoot("get application restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002315 }
2316 synchronized (mPackagesLock) {
2317 // Read the restrictions from XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07002318 return readApplicationRestrictionsLP(packageName, userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002319 }
2320 }
2321
2322 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002323 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002324 int userId) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00002325 checkSystemOrRoot("set application restrictions");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002326 synchronized (mPackagesLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01002327 if (restrictions == null || restrictions.isEmpty()) {
2328 cleanAppRestrictionsForPackage(packageName, userId);
2329 } else {
Amith Yamasani23879322016-03-30 16:51:26 -07002330 restrictions.setDefusable(true);
Kenny Guyd21b2182014-07-17 16:38:55 +01002331 // Write the restrictions to XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07002332 writeApplicationRestrictionsLP(packageName, restrictions, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01002333 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002334 }
Robin Lee66e5d962014-04-09 16:44:21 +01002335
Fyodor Kupolovd2846122016-02-11 18:06:34 -08002336 // Notify package of changes via an intent - only sent to explicitly registered receivers.
2337 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
2338 changeIntent.setPackage(packageName);
2339 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
2340 mContext.sendBroadcastAsUser(changeIntent, UserHandle.of(userId));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002341 }
2342
2343 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07002344 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002345 try {
2346 return mContext.getPackageManager().getApplicationInfo(packageName,
Fyodor Kupolovd2846122016-02-11 18:06:34 -08002347 PackageManager.MATCH_UNINSTALLED_PACKAGES).uid;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002348 } catch (NameNotFoundException nnfe) {
2349 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07002350 } finally {
2351 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002352 }
2353 }
2354
Fyodor Kupolov82402752015-10-28 14:54:51 -07002355 private Bundle readApplicationRestrictionsLP(String packageName, int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002356 AtomicFile restrictionsFile =
2357 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
2358 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002359 return readApplicationRestrictionsLP(restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002360 }
2361
2362 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002363 static Bundle readApplicationRestrictionsLP(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002364 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002365 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002366 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07002367 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002368 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002369
2370 FileInputStream fis = null;
2371 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002372 fis = restrictionsFile.openRead();
2373 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002374 parser.setInput(fis, StandardCharsets.UTF_8.name());
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002375 XmlUtils.nextElement(parser);
2376 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002377 Slog.e(LOG_TAG, "Unable to read restrictions file "
2378 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002379 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002380 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002381 while (parser.next() != XmlPullParser.END_DOCUMENT) {
2382 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002383 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002384 } catch (IOException|XmlPullParserException e) {
2385 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002386 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002387 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002388 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002389 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002390 }
2391
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002392 private static void readEntry(Bundle restrictions, ArrayList<String> values,
2393 XmlPullParser parser) throws XmlPullParserException, IOException {
2394 int type = parser.getEventType();
2395 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
2396 String key = parser.getAttributeValue(null, ATTR_KEY);
2397 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
2398 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
2399 if (multiple != null) {
2400 values.clear();
2401 int count = Integer.parseInt(multiple);
2402 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
2403 if (type == XmlPullParser.START_TAG
2404 && parser.getName().equals(TAG_VALUE)) {
2405 values.add(parser.nextText().trim());
2406 count--;
2407 }
2408 }
2409 String [] valueStrings = new String[values.size()];
2410 values.toArray(valueStrings);
2411 restrictions.putStringArray(key, valueStrings);
2412 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
2413 restrictions.putBundle(key, readBundleEntry(parser, values));
2414 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
2415 final int outerDepth = parser.getDepth();
2416 ArrayList<Bundle> bundleList = new ArrayList<>();
2417 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2418 Bundle childBundle = readBundleEntry(parser, values);
2419 bundleList.add(childBundle);
2420 }
2421 restrictions.putParcelableArray(key,
2422 bundleList.toArray(new Bundle[bundleList.size()]));
2423 } else {
2424 String value = parser.nextText().trim();
2425 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
2426 restrictions.putBoolean(key, Boolean.parseBoolean(value));
2427 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
2428 restrictions.putInt(key, Integer.parseInt(value));
2429 } else {
2430 restrictions.putString(key, value);
2431 }
2432 }
2433 }
2434 }
2435
2436 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
2437 throws IOException, XmlPullParserException {
2438 Bundle childBundle = new Bundle();
2439 final int outerDepth = parser.getDepth();
2440 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2441 readEntry(childBundle, values, parser);
2442 }
2443 return childBundle;
2444 }
2445
Fyodor Kupolov82402752015-10-28 14:54:51 -07002446 private void writeApplicationRestrictionsLP(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002447 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002448 AtomicFile restrictionsFile = new AtomicFile(
2449 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07002450 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002451 writeApplicationRestrictionsLP(restrictions, restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002452 }
2453
2454 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002455 static void writeApplicationRestrictionsLP(Bundle restrictions, AtomicFile restrictionsFile) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002456 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002457 try {
2458 fos = restrictionsFile.startWrite();
2459 final BufferedOutputStream bos = new BufferedOutputStream(fos);
2460
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002461 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002462 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002463 serializer.startDocument(null, true);
2464 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2465
2466 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002467 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002468 serializer.endTag(null, TAG_RESTRICTIONS);
2469
2470 serializer.endDocument();
2471 restrictionsFile.finishWrite(fos);
2472 } catch (Exception e) {
2473 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002474 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
2475 }
2476 }
2477
2478 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
2479 throws IOException {
2480 for (String key : restrictions.keySet()) {
2481 Object value = restrictions.get(key);
2482 serializer.startTag(null, TAG_ENTRY);
2483 serializer.attribute(null, ATTR_KEY, key);
2484
2485 if (value instanceof Boolean) {
2486 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
2487 serializer.text(value.toString());
2488 } else if (value instanceof Integer) {
2489 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
2490 serializer.text(value.toString());
2491 } else if (value == null || value instanceof String) {
2492 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
2493 serializer.text(value != null ? (String) value : "");
2494 } else if (value instanceof Bundle) {
2495 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2496 writeBundle((Bundle) value, serializer);
2497 } else if (value instanceof Parcelable[]) {
2498 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
2499 Parcelable[] array = (Parcelable[]) value;
2500 for (Parcelable parcelable : array) {
2501 if (!(parcelable instanceof Bundle)) {
2502 throw new IllegalArgumentException("bundle-array can only hold Bundles");
2503 }
2504 serializer.startTag(null, TAG_ENTRY);
2505 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2506 writeBundle((Bundle) parcelable, serializer);
2507 serializer.endTag(null, TAG_ENTRY);
2508 }
2509 } else {
2510 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
2511 String[] values = (String[]) value;
2512 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
2513 for (String choice : values) {
2514 serializer.startTag(null, TAG_VALUE);
2515 serializer.text(choice != null ? choice : "");
2516 serializer.endTag(null, TAG_VALUE);
2517 }
2518 }
2519 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002520 }
2521 }
2522
2523 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07002524 public int getUserSerialNumber(int userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002525 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002526 if (!exists(userHandle)) return -1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002527 return getUserInfoLU(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07002528 }
2529 }
2530
2531 @Override
2532 public int getUserHandle(int userSerialNumber) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002533 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002534 for (int userId : mUserIds) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002535 UserInfo info = getUserInfoLU(userId);
Kenny Guy945f8832015-02-10 15:17:26 +00002536 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07002537 }
2538 // Not found
2539 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07002540 }
2541 }
2542
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002543 @Override
2544 public long getUserCreationTime(int userHandle) {
2545 int callingUserId = UserHandle.getCallingUserId();
2546 UserInfo userInfo = null;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002547 synchronized (mUsersLock) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002548 if (callingUserId == userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002549 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002550 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002551 UserInfo parent = getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002552 if (parent != null && parent.id == callingUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002553 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002554 }
2555 }
2556 }
2557 if (userInfo == null) {
2558 throw new SecurityException("userHandle can only be the calling user or a managed "
2559 + "profile associated with this user");
2560 }
2561 return userInfo.creationTime;
2562 }
2563
Amith Yamasani0b285492011-04-14 17:35:23 -07002564 /**
2565 * Caches the list of user ids in an array, adjusting the array size when necessary.
2566 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002567 private void updateUserIds() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002568 int num = 0;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002569 synchronized (mUsersLock) {
2570 final int userSize = mUsers.size();
2571 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002572 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002573 num++;
2574 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002575 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002576 final int[] newUsers = new int[num];
2577 int n = 0;
2578 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002579 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002580 newUsers[n++] = mUsers.keyAt(i);
2581 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002582 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002583 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07002584 }
2585 }
2586
2587 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002588 * Called right before a user is started. This gives us a chance to prepare
2589 * app storage and apply any user restrictions.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002590 */
2591 public void onBeforeStartUser(int userId) {
Jeff Sharkey47f71082016-02-01 17:03:54 -07002592 final int userSerial = getUserSerialNumber(userId);
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002593 mPm.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_DE);
Jeff Sharkey47f71082016-02-01 17:03:54 -07002594 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_DE);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002595
2596 if (userId != UserHandle.USER_SYSTEM) {
2597 synchronized (mRestrictionsLock) {
2598 applyUserRestrictionsLR(userId);
2599 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002600 }
2601 }
2602
2603 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002604 * Called right before a user is unlocked. This gives us a chance to prepare
2605 * app storage.
2606 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002607 public void onBeforeUnlockUser(@UserIdInt int userId) {
Jeff Sharkey47f71082016-02-01 17:03:54 -07002608 final int userSerial = getUserSerialNumber(userId);
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002609 mPm.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_CE);
Jeff Sharkey47f71082016-02-01 17:03:54 -07002610 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_CE);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002611 }
2612
2613 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002614 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasani920ace02012-09-20 22:15:37 -07002615 * @param userId the user that was just foregrounded
2616 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002617 public void onUserLoggedIn(@UserIdInt int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -08002618 UserData userData = getUserDataNoChecks(userId);
2619 if (userData == null || userData.info.partial) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002620 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
2621 return;
2622 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002623
2624 final long now = System.currentTimeMillis();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002625 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani12747872015-12-07 14:19:49 -08002626 userData.info.lastLoggedInTime = now;
Amith Yamasani920ace02012-09-20 22:15:37 -07002627 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002628 userData.info.lastLoggedInFingerprint = Build.FINGERPRINT;
2629 scheduleWriteUser(userData);
Amith Yamasani920ace02012-09-20 22:15:37 -07002630 }
2631
2632 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002633 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani742a6712011-05-04 14:49:28 -07002634 * TODO: May not be a good idea to recycle ids, in case it results in confusion
2635 * for data and battery stats collection, or unexpected cross-talk.
Amith Yamasani0b285492011-04-14 17:35:23 -07002636 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002637 private int getNextAvailableId() {
2638 synchronized (mUsersLock) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002639 int i = MIN_USER_ID;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002640 while (i < MAX_USER_ID) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002641 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002642 return i;
Amith Yamasani195263742012-08-21 15:40:12 -07002643 }
2644 i++;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002645 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002646 }
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002647 throw new IllegalStateException("No user id available!");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002648 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002649
Amith Yamasanifc95e702013-09-26 13:20:17 -07002650 private String packageToRestrictionsFileName(String packageName) {
2651 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
2652 }
2653
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002654 /**
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002655 * Enforce that serial number stored in user directory inode matches the
2656 * given expected value. Gracefully sets the serial number if currently
2657 * undefined.
2658 *
2659 * @throws IOException when problem extracting serial number, or serial
2660 * number is mismatched.
2661 */
2662 public static void enforceSerialNumber(File file, int serialNumber) throws IOException {
2663 final int foundSerial = getSerialNumber(file);
2664 Slog.v(LOG_TAG, "Found " + file + " with serial number " + foundSerial);
2665
2666 if (foundSerial == -1) {
2667 Slog.d(LOG_TAG, "Serial number missing on " + file + "; assuming current is valid");
2668 try {
2669 setSerialNumber(file, serialNumber);
2670 } catch (IOException e) {
2671 Slog.w(LOG_TAG, "Failed to set serial number on " + file, e);
2672 }
2673
2674 } else if (foundSerial != serialNumber) {
2675 throw new IOException("Found serial number " + foundSerial
2676 + " doesn't match expected " + serialNumber);
2677 }
2678 }
2679
2680 /**
2681 * Set serial number stored in user directory inode.
2682 *
2683 * @throws IOException if serial number was already set
2684 */
2685 private static void setSerialNumber(File file, int serialNumber)
2686 throws IOException {
2687 try {
2688 final byte[] buf = Integer.toString(serialNumber).getBytes(StandardCharsets.UTF_8);
2689 Os.setxattr(file.getAbsolutePath(), XATTR_SERIAL, buf, OsConstants.XATTR_CREATE);
2690 } catch (ErrnoException e) {
2691 throw e.rethrowAsIOException();
2692 }
2693 }
2694
2695 /**
2696 * Return serial number stored in user directory inode.
2697 *
2698 * @return parsed serial number, or -1 if not set
2699 */
2700 private static int getSerialNumber(File file) throws IOException {
2701 try {
2702 final byte[] buf = new byte[256];
2703 final int len = Os.getxattr(file.getAbsolutePath(), XATTR_SERIAL, buf);
2704 final String serial = new String(buf, 0, len);
2705 try {
2706 return Integer.parseInt(serial);
2707 } catch (NumberFormatException e) {
2708 throw new IOException("Bad serial number: " + serial);
2709 }
2710 } catch (ErrnoException e) {
2711 if (e.errno == OsConstants.ENODATA) {
2712 return -1;
2713 } else {
2714 throw e.rethrowAsIOException();
2715 }
2716 }
2717 }
2718
Amith Yamasani920ace02012-09-20 22:15:37 -07002719 @Override
Amith Yamasani12747872015-12-07 14:19:49 -08002720 public void setSeedAccountData(int userId, String accountName, String accountType,
2721 PersistableBundle accountOptions, boolean persist) {
2722 checkManageUsersPermission("Require MANAGE_USERS permission to set user seed data");
2723 synchronized (mPackagesLock) {
2724 final UserData userData;
2725 synchronized (mUsersLock) {
2726 userData = getUserDataLU(userId);
2727 if (userData == null) {
2728 Slog.e(LOG_TAG, "No such user for settings seed data u=" + userId);
2729 return;
2730 }
2731 userData.seedAccountName = accountName;
2732 userData.seedAccountType = accountType;
2733 userData.seedAccountOptions = accountOptions;
2734 userData.persistSeedData = persist;
2735 }
2736 if (persist) {
2737 writeUserLP(userData);
2738 }
2739 }
2740 }
2741
2742 @Override
2743 public String getSeedAccountName() throws RemoteException {
2744 checkManageUsersPermission("Cannot get seed account information");
2745 synchronized (mUsersLock) {
2746 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
2747 return userData.seedAccountName;
2748 }
2749 }
2750
2751 @Override
2752 public String getSeedAccountType() throws RemoteException {
2753 checkManageUsersPermission("Cannot get seed account information");
2754 synchronized (mUsersLock) {
2755 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
2756 return userData.seedAccountType;
2757 }
2758 }
2759
2760 @Override
2761 public PersistableBundle getSeedAccountOptions() throws RemoteException {
2762 checkManageUsersPermission("Cannot get seed account information");
2763 synchronized (mUsersLock) {
2764 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
2765 return userData.seedAccountOptions;
2766 }
2767 }
2768
2769 @Override
2770 public void clearSeedAccountData() throws RemoteException {
2771 checkManageUsersPermission("Cannot clear seed account information");
2772 synchronized (mPackagesLock) {
2773 UserData userData;
2774 synchronized (mUsersLock) {
2775 userData = getUserDataLU(UserHandle.getCallingUserId());
2776 if (userData == null) return;
2777 userData.clearSeedAccountData();
2778 }
2779 writeUserLP(userData);
2780 }
2781 }
2782
2783 @Override
2784 public boolean someUserHasSeedAccount(String accountName, String accountType)
2785 throws RemoteException {
2786 checkManageUsersPermission("Cannot check seed account information");
2787 synchronized (mUsersLock) {
2788 final int userSize = mUsers.size();
2789 for (int i = 0; i < userSize; i++) {
2790 final UserData data = mUsers.valueAt(i);
2791 if (data.info.isInitialized()) continue;
2792 if (data.seedAccountName == null || !data.seedAccountName.equals(accountName)) {
2793 continue;
2794 }
2795 if (data.seedAccountType == null || !data.seedAccountType.equals(accountType)) {
2796 continue;
2797 }
2798 return true;
2799 }
2800 }
2801 return false;
2802 }
2803
2804 @Override
Todd Kennedy60459ab2015-10-30 11:32:16 -07002805 public void onShellCommand(FileDescriptor in, FileDescriptor out,
2806 FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
2807 (new Shell()).exec(this, in, out, err, args, resultReceiver);
2808 }
2809
2810 int onShellCommand(Shell shell, String cmd) {
2811 if (cmd == null) {
2812 return shell.handleDefaultCommands(cmd);
2813 }
2814
2815 final PrintWriter pw = shell.getOutPrintWriter();
2816 try {
2817 switch(cmd) {
2818 case "list":
2819 return runList(pw);
2820 }
2821 } catch (RemoteException e) {
2822 pw.println("Remote exception: " + e);
2823 }
2824 return -1;
2825 }
2826
2827 private int runList(PrintWriter pw) throws RemoteException {
2828 final IActivityManager am = ActivityManagerNative.getDefault();
2829 final List<UserInfo> users = getUsers(false);
2830 if (users == null) {
2831 pw.println("Error: couldn't get users");
2832 return 1;
2833 } else {
2834 pw.println("Users:");
2835 for (int i = 0; i < users.size(); i++) {
Jeff Sharkeye17ac152015-11-06 22:40:29 -08002836 String running = am.isUserRunning(users.get(i).id, 0) ? " running" : "";
Todd Kennedy60459ab2015-10-30 11:32:16 -07002837 pw.println("\t" + users.get(i).toString() + running);
2838 }
2839 return 0;
2840 }
2841 }
2842
2843 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -07002844 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2845 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2846 != PackageManager.PERMISSION_GRANTED) {
2847 pw.println("Permission Denial: can't dump UserManager from from pid="
2848 + Binder.getCallingPid()
2849 + ", uid=" + Binder.getCallingUid()
2850 + " without permission "
2851 + android.Manifest.permission.DUMP);
2852 return;
2853 }
2854
2855 long now = System.currentTimeMillis();
2856 StringBuilder sb = new StringBuilder();
2857 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002858 synchronized (mUsersLock) {
2859 pw.println("Users:");
2860 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002861 UserData userData = mUsers.valueAt(i);
2862 if (userData == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002863 continue;
2864 }
Amith Yamasani12747872015-12-07 14:19:49 -08002865 UserInfo userInfo = userData.info;
2866 final int userId = userInfo.id;
2867 pw.print(" "); pw.print(userInfo);
2868 pw.print(" serialNo="); pw.print(userInfo.serialNumber);
Makoto Onukie7927da2015-11-25 10:05:17 -08002869 if (mRemovingUserIds.get(userId)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002870 pw.print(" <removing> ");
2871 }
Amith Yamasani12747872015-12-07 14:19:49 -08002872 if (userInfo.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002873 pw.print(" <partial>");
2874 }
2875 pw.println();
2876 pw.print(" Created: ");
Amith Yamasani12747872015-12-07 14:19:49 -08002877 if (userInfo.creationTime == 0) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002878 pw.println("<unknown>");
2879 } else {
2880 sb.setLength(0);
Amith Yamasani12747872015-12-07 14:19:49 -08002881 TimeUtils.formatDuration(now - userInfo.creationTime, sb);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002882 sb.append(" ago");
2883 pw.println(sb);
2884 }
2885 pw.print(" Last logged in: ");
Amith Yamasani12747872015-12-07 14:19:49 -08002886 if (userInfo.lastLoggedInTime == 0) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002887 pw.println("<unknown>");
2888 } else {
2889 sb.setLength(0);
Amith Yamasani12747872015-12-07 14:19:49 -08002890 TimeUtils.formatDuration(now - userInfo.lastLoggedInTime, sb);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002891 sb.append(" ago");
2892 pw.println(sb);
2893 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002894 pw.print(" Last logged in fingerprint: ");
2895 pw.println(userInfo.lastLoggedInFingerprint);
Makoto Onukie7927da2015-11-25 10:05:17 -08002896 pw.print(" Has profile owner: ");
2897 pw.println(mIsUserManaged.get(userId));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002898 pw.println(" Restrictions:");
2899 synchronized (mRestrictionsLock) {
2900 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08002901 pw, " ", mBaseUserRestrictions.get(userInfo.id));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002902 pw.println(" Device policy local restrictions:");
2903 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08002904 pw, " ", mDevicePolicyLocalUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002905 pw.println(" Effective restrictions:");
2906 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08002907 pw, " ", mCachedEffectiveUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002908 }
Amith Yamasani12747872015-12-07 14:19:49 -08002909
2910 if (userData.account != null) {
2911 pw.print(" Account name: " + userData.account);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08002912 pw.println();
2913 }
Amith Yamasani12747872015-12-07 14:19:49 -08002914
2915 if (userData.seedAccountName != null) {
2916 pw.print(" Seed account name: " + userData.seedAccountName);
2917 pw.println();
2918 if (userData.seedAccountType != null) {
2919 pw.print(" account type: " + userData.seedAccountType);
2920 pw.println();
2921 }
2922 if (userData.seedAccountOptions != null) {
2923 pw.print(" account options exist");
2924 pw.println();
2925 }
2926 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002927 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002928 }
Amith Yamasani12747872015-12-07 14:19:49 -08002929 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002930 pw.println(" Device policy global restrictions:");
2931 synchronized (mRestrictionsLock) {
2932 UserRestrictionsUtils
2933 .dumpRestrictions(pw, " ", mDevicePolicyGlobalUserRestrictions);
2934 }
Makoto Onukia4f11972015-10-01 13:19:58 -07002935 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002936 pw.println(" Guest restrictions:");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002937 synchronized (mGuestRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002938 UserRestrictionsUtils.dumpRestrictions(pw, " ", mGuestRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002939 }
Makoto Onukie7927da2015-11-25 10:05:17 -08002940 synchronized (mUsersLock) {
2941 pw.println();
2942 pw.println(" Device managed: " + mIsDeviceManaged);
2943 }
Amith Yamasani12747872015-12-07 14:19:49 -08002944 // Dump some capabilities
2945 pw.println();
2946 pw.println(" Max users: " + UserManager.getMaxSupportedUsers());
2947 pw.println(" Supports switchable users: " + UserManager.supportsMultipleUsers());
Lenka Trochtova02fee152015-12-22 14:26:18 +01002948 pw.println(" All guests ephemeral: " + Resources.getSystem().getBoolean(
2949 com.android.internal.R.bool.config_guestUserEphemeral));
Amith Yamasani920ace02012-09-20 22:15:37 -07002950 }
2951 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002952
2953 final class MainHandler extends Handler {
2954
2955 @Override
2956 public void handleMessage(Message msg) {
2957 switch (msg.what) {
2958 case WRITE_USER_MSG:
2959 removeMessages(WRITE_USER_MSG, msg.obj);
2960 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002961 int userId = ((UserData) msg.obj).info.id;
2962 UserData userData = getUserDataNoChecks(userId);
2963 if (userData != null) {
2964 writeUserLP(userData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002965 }
2966 }
2967 }
2968 }
2969 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07002970
2971 /**
2972 * @param userId
2973 * @return whether the user has been initialized yet
2974 */
2975 boolean isInitialized(int userId) {
2976 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
2977 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07002978
2979 private class LocalService extends UserManagerInternal {
Makoto Onuki068c54a2015-10-13 14:34:03 -07002980 @Override
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002981 public void setDevicePolicyUserRestrictions(int userId, @NonNull Bundle localRestrictions,
2982 @Nullable Bundle globalRestrictions) {
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002983 UserManagerService.this.setDevicePolicyUserRestrictionsInner(userId, localRestrictions,
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002984 globalRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002985 }
2986
2987 @Override
2988 public Bundle getBaseUserRestrictions(int userId) {
2989 synchronized (mRestrictionsLock) {
2990 return mBaseUserRestrictions.get(userId);
2991 }
2992 }
2993
2994 @Override
2995 public void setBaseUserRestrictionsByDpmsForMigration(
2996 int userId, Bundle baseRestrictions) {
2997 synchronized (mRestrictionsLock) {
2998 mBaseUserRestrictions.put(userId, new Bundle(baseRestrictions));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002999 invalidateEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003000 }
3001
Amith Yamasani12747872015-12-07 14:19:49 -08003002 final UserData userData = getUserDataNoChecks(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003003 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08003004 if (userData != null) {
3005 writeUserLP(userData);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003006 } else {
3007 Slog.w(LOG_TAG, "UserInfo not found for " + userId);
3008 }
3009 }
3010 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08003011
3012 @Override
3013 public boolean getUserRestriction(int userId, String key) {
3014 return getUserRestrictions(userId).getBoolean(key);
3015 }
3016
3017 @Override
3018 public void addUserRestrictionsListener(UserRestrictionsListener listener) {
3019 synchronized (mUserRestrictionsListeners) {
3020 mUserRestrictionsListeners.add(listener);
3021 }
3022 }
3023
3024 @Override
3025 public void removeUserRestrictionsListener(UserRestrictionsListener listener) {
3026 synchronized (mUserRestrictionsListeners) {
3027 mUserRestrictionsListeners.remove(listener);
3028 }
3029 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003030
3031 @Override
3032 public void setDeviceManaged(boolean isManaged) {
3033 synchronized (mUsersLock) {
3034 mIsDeviceManaged = isManaged;
3035 }
3036 }
3037
3038 @Override
3039 public void setUserManaged(int userId, boolean isManaged) {
3040 synchronized (mUsersLock) {
3041 mIsUserManaged.put(userId, isManaged);
3042 }
3043 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01003044
3045 @Override
3046 public void setUserIcon(int userId, Bitmap bitmap) {
3047 long ident = Binder.clearCallingIdentity();
3048 try {
3049 synchronized (mPackagesLock) {
3050 UserData userData = getUserDataNoChecks(userId);
3051 if (userData == null || userData.info.partial) {
3052 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
3053 return;
3054 }
3055 writeBitmapLP(userData.info, bitmap);
3056 writeUserLP(userData);
3057 }
3058 sendUserInfoChangedBroadcast(userId);
3059 } finally {
3060 Binder.restoreCallingIdentity(ident);
3061 }
3062 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01003063
3064 @Override
3065 public void setForceEphemeralUsers(boolean forceEphemeralUsers) {
3066 synchronized (mUsersLock) {
3067 mForceEphemeralUsers = forceEphemeralUsers;
3068 }
3069 }
3070
3071 @Override
3072 public void removeAllUsers() {
3073 if (UserHandle.USER_SYSTEM == ActivityManager.getCurrentUser()) {
3074 // Remove the non-system users straight away.
3075 removeNonSystemUsers();
3076 } else {
3077 // Switch to the system user first and then remove the other users.
3078 BroadcastReceiver userSwitchedReceiver = new BroadcastReceiver() {
3079 @Override
3080 public void onReceive(Context context, Intent intent) {
3081 int userId =
3082 intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3083 if (userId != UserHandle.USER_SYSTEM) {
3084 return;
3085 }
3086 mContext.unregisterReceiver(this);
3087 removeNonSystemUsers();
3088 }
3089 };
3090 IntentFilter userSwitchedFilter = new IntentFilter();
3091 userSwitchedFilter.addAction(Intent.ACTION_USER_SWITCHED);
3092 mContext.registerReceiver(
3093 userSwitchedReceiver, userSwitchedFilter, null, mHandler);
3094
3095 // Switch to the system user.
3096 ActivityManager am =
3097 (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
3098 am.switchUser(UserHandle.USER_SYSTEM);
3099 }
3100 }
phweisse9c44062016-02-10 12:57:38 +01003101
3102 @Override
Lenka Trochtova1ddda472016-02-12 10:42:12 +01003103 public void onEphemeralUserStop(int userId) {
3104 synchronized (mUsersLock) {
3105 UserInfo userInfo = getUserInfoLU(userId);
3106 if (userInfo != null && userInfo.isEphemeral()) {
3107 // Do not allow switching back to the ephemeral user again as the user is going
3108 // to be deleted.
3109 userInfo.flags |= UserInfo.FLAG_DISABLED;
3110 if (userInfo.isGuest()) {
3111 // Indicate that the guest will be deleted after it stops.
3112 userInfo.guestToRemove = true;
3113 }
3114 }
3115 }
3116 }
3117
3118 @Override
phweisse9c44062016-02-10 12:57:38 +01003119 public UserInfo createUserEvenWhenDisallowed(String name, int flags) {
3120 UserInfo user = createUserInternalUnchecked(name, flags, UserHandle.USER_NULL);
3121 // Keep this in sync with UserManager.createUser
3122 if (user != null && !user.isAdmin()) {
3123 setUserRestriction(UserManager.DISALLOW_SMS, true, user.id);
3124 setUserRestriction(UserManager.DISALLOW_OUTGOING_CALLS, true, user.id);
3125 }
3126 return user;
3127 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01003128 }
3129
3130 /* Remove all the users except of the system one. */
3131 private void removeNonSystemUsers() {
3132 ArrayList<UserInfo> usersToRemove = new ArrayList<>();
3133 synchronized (mUsersLock) {
3134 final int userSize = mUsers.size();
3135 for (int i = 0; i < userSize; i++) {
3136 UserInfo ui = mUsers.valueAt(i).info;
3137 if (ui.id != UserHandle.USER_SYSTEM) {
3138 usersToRemove.add(ui);
3139 }
3140 }
3141 }
3142 for (UserInfo ui: usersToRemove) {
3143 removeUser(ui.id);
3144 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003145 }
Todd Kennedy60459ab2015-10-30 11:32:16 -07003146
3147 private class Shell extends ShellCommand {
3148 @Override
3149 public int onCommand(String cmd) {
3150 return onShellCommand(this, cmd);
3151 }
3152
3153 @Override
3154 public void onHelp() {
3155 final PrintWriter pw = getOutPrintWriter();
3156 pw.println("User manager (user) commands:");
3157 pw.println(" help");
3158 pw.println(" Print this help text.");
3159 pw.println("");
3160 pw.println(" list");
3161 pw.println(" Prints all users on the system.");
3162 }
3163 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003164
3165 private static void debug(String message) {
3166 Log.d(LOG_TAG, message +
3167 (DBG_WITH_STACKTRACE ? " called at\n" + Debug.getCallers(10, " ") : ""));
3168 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003169}