blob: e7518e731559d4342cab5757bdde2b39602bc890 [file] [log] [blame]
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
Benjamin Franzf02420c2016-04-04 18:52:21 +010019import static android.content.Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS;
20import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
21
Xiaohui Chenb3b92582015-12-07 11:22:13 -080022import android.Manifest;
Xiaohui Chen594f2082015-08-18 11:04:20 -070023import android.annotation.NonNull;
Makoto Onuki068c54a2015-10-13 14:34:03 -070024import android.annotation.Nullable;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -060025import android.annotation.UserIdInt;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070026import android.app.Activity;
Amith Yamasani2a003292012-08-14 18:25:45 -070027import android.app.ActivityManager;
Amith Yamasani515d4062015-09-28 11:30:06 -070028import android.app.ActivityManagerInternal;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070029import android.app.ActivityManagerNative;
Todd Kennedy60459ab2015-10-30 11:32:16 -070030import android.app.IActivityManager;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070031import android.app.IStopUserCallback;
Benjamin Franzf02420c2016-04-04 18:52:21 +010032import android.app.KeyguardManager;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070033import android.content.BroadcastReceiver;
Amith Yamasani258848d2012-08-10 17:06:33 -070034import android.content.Context;
35import android.content.Intent;
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +010036import android.content.IntentFilter;
Benjamin Franzf02420c2016-04-04 18:52:21 +010037import android.content.IntentSender;
Amith Yamasani0b285492011-04-14 17:35:23 -070038import android.content.pm.PackageManager;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -080039import android.content.pm.PackageManager.NameNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070040import android.content.pm.UserInfo;
Lenka Trochtova02fee152015-12-22 14:26:18 +010041import android.content.res.Resources;
Amith Yamasanie928d7d2012-09-17 21:46:51 -070042import android.graphics.Bitmap;
Amith Yamasani258848d2012-08-10 17:06:33 -070043import android.os.Binder;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -060044import android.os.Build;
Amith Yamasanie4cf7342012-12-17 11:12:09 -080045import android.os.Bundle;
Makoto Onuki1a2cd742015-11-16 13:51:27 -080046import android.os.Debug;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070047import android.os.Environment;
48import android.os.FileUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080049import android.os.Handler;
Svet Ganov9cea80cd2016-02-16 11:47:00 -080050import android.os.IBinder;
Amith Yamasani258848d2012-08-10 17:06:33 -070051import android.os.IUserManager;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -080052import android.os.Message;
Adrian Roos1bdff912015-02-17 15:51:35 +010053import android.os.ParcelFileDescriptor;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070054import android.os.Parcelable;
Amith Yamasani12747872015-12-07 14:19:49 -080055import android.os.PersistableBundle;
Amith Yamasani258848d2012-08-10 17:06:33 -070056import android.os.Process;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070057import android.os.RemoteException;
Todd Kennedy60459ab2015-10-30 11:32:16 -070058import android.os.ResultReceiver;
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +010059import android.os.SELinux;
Jason Monk62062992014-05-06 09:55:28 -040060import android.os.ServiceManager;
Todd Kennedy60459ab2015-10-30 11:32:16 -070061import android.os.ShellCommand;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070062import android.os.UserHandle;
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070063import android.os.UserManager;
Makoto Onuki068c54a2015-10-13 14:34:03 -070064import android.os.UserManagerInternal;
Makoto Onukid45a4a22015-11-02 17:17:38 -080065import android.os.UserManagerInternal.UserRestrictionsListener;
Paul Crowley85e4e812015-05-19 12:42:00 +010066import android.os.storage.StorageManager;
Jeff Sharkey6dce4962015-07-03 18:08:41 -070067import android.system.ErrnoException;
68import android.system.Os;
69import android.system.OsConstants;
Amith Yamasani2a003292012-08-14 18:25:45 -070070import android.util.AtomicFile;
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -070071import android.util.IntArray;
Amith Yamasani655d0e22013-06-12 14:19:10 -070072import android.util.Log;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070073import android.util.Slog;
74import android.util.SparseArray;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080075import android.util.SparseBooleanArray;
Fyodor Kupolovac06a492016-05-25 14:45:29 -070076import android.util.SparseIntArray;
Amith Yamasani920ace02012-09-20 22:15:37 -070077import android.util.TimeUtils;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070078import android.util.Xml;
79
Makoto Onuki068c54a2015-10-13 14:34:03 -070080import com.android.internal.annotations.GuardedBy;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070081import com.android.internal.annotations.VisibleForTesting;
Jason Monk62062992014-05-06 09:55:28 -040082import com.android.internal.app.IAppOpsService;
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -080083import com.android.internal.logging.MetricsLogger;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080084import com.android.internal.util.FastXmlSerializer;
Makoto Onuki068c54a2015-10-13 14:34:03 -070085import com.android.internal.util.Preconditions;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070086import com.android.internal.util.XmlUtils;
Clara Bayarri10ad84a2015-12-01 17:38:05 +000087import com.android.internal.widget.LockPatternUtils;
Amith Yamasani515d4062015-09-28 11:30:06 -070088import com.android.server.LocalServices;
Fyodor Kupolovac06a492016-05-25 14:45:29 -070089import com.android.server.am.UserState;
Jeff Sharkey47f71082016-02-01 17:03:54 -070090
91import libcore.io.IoUtils;
92import libcore.util.Objects;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080093
94import org.xmlpull.v1.XmlPullParser;
95import org.xmlpull.v1.XmlPullParserException;
96import org.xmlpull.v1.XmlSerializer;
97
Amith Yamasani4b2e9342011-03-31 12:38:53 -070098import java.io.BufferedOutputStream;
99import java.io.File;
Amith Yamasani920ace02012-09-20 22:15:37 -0700100import java.io.FileDescriptor;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700101import java.io.FileInputStream;
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700102import java.io.FileNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700103import java.io.FileOutputStream;
104import java.io.IOException;
Amith Yamasani920ace02012-09-20 22:15:37 -0700105import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100106import java.nio.charset.StandardCharsets;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700107import java.util.ArrayList;
108import java.util.List;
109
Makoto Onuki068c54a2015-10-13 14:34:03 -0700110/**
111 * Service for {@link UserManager}.
112 *
113 * Method naming convention:
Fyodor Kupolov82402752015-10-28 14:54:51 -0700114 * <ul>
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800115 * <li> Methods suffixed with "LP" should be called within the {@link #mPackagesLock} lock.
Fyodor Kupolov82402752015-10-28 14:54:51 -0700116 * <li> Methods suffixed with "LR" should be called within the {@link #mRestrictionsLock} lock.
117 * <li> Methods suffixed with "LU" should be called within the {@link #mUsersLock} lock.
118 * </ul>
Makoto Onuki068c54a2015-10-13 14:34:03 -0700119 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700120public class UserManagerService extends IUserManager.Stub {
Amith Yamasani2a003292012-08-14 18:25:45 -0700121 private static final String LOG_TAG = "UserManagerService";
Makoto Onuki81c61ea2016-01-22 11:22:26 -0800122 static final boolean DBG = false; // DO NOT SUBMIT WITH TRUE
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800123 private static final boolean DBG_WITH_STACKTRACE = false; // DO NOT SUBMIT WITH TRUE
Amith Yamasani16389312012-10-17 21:20:14 -0700124
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700125 private static final String TAG_NAME = "name";
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800126 private static final String TAG_ACCOUNT = "account";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700127 private static final String ATTR_FLAGS = "flags";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700128 private static final String ATTR_ICON_PATH = "icon";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700129 private static final String ATTR_ID = "id";
Amith Yamasani920ace02012-09-20 22:15:37 -0700130 private static final String ATTR_CREATION_TIME = "created";
131 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -0600132 private static final String ATTR_LAST_LOGGED_IN_FINGERPRINT = "lastLoggedInFingerprint";
Amith Yamasani2a003292012-08-14 18:25:45 -0700133 private static final String ATTR_SERIAL_NO = "serialNumber";
134 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700135 private static final String ATTR_PARTIAL = "partial";
Adam Lesinskieddeb492014-09-08 17:50:03 -0700136 private static final String ATTR_GUEST_TO_REMOVE = "guestToRemove";
Amith Yamasani6f34b412012-10-22 18:19:27 -0700137 private static final String ATTR_USER_VERSION = "version";
Kenny Guy2a764942014-04-02 13:29:20 +0100138 private static final String ATTR_PROFILE_GROUP_ID = "profileGroupId";
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700139 private static final String ATTR_RESTRICTED_PROFILE_PARENT_ID = "restrictedProfileParentId";
Amith Yamasani12747872015-12-07 14:19:49 -0800140 private static final String ATTR_SEED_ACCOUNT_NAME = "seedAccountName";
141 private static final String ATTR_SEED_ACCOUNT_TYPE = "seedAccountType";
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530142 private static final String TAG_GUEST_RESTRICTIONS = "guestRestrictions";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700143 private static final String TAG_USERS = "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700144 private static final String TAG_USER = "user";
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800145 private static final String TAG_RESTRICTIONS = "restrictions";
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800146 private static final String TAG_DEVICE_POLICY_RESTRICTIONS = "device_policy_restrictions";
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +0100147 private static final String TAG_GLOBAL_RESTRICTION_OWNER_ID = "globalRestrictionOwnerUserId";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800148 private static final String TAG_ENTRY = "entry";
149 private static final String TAG_VALUE = "value";
Amith Yamasani12747872015-12-07 14:19:49 -0800150 private static final String TAG_SEED_ACCOUNT_OPTIONS = "seedAccountOptions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800151 private static final String ATTR_KEY = "key";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700152 private static final String ATTR_VALUE_TYPE = "type";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800153 private static final String ATTR_MULTIPLE = "m";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700154
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700155 private static final String ATTR_TYPE_STRING_ARRAY = "sa";
156 private static final String ATTR_TYPE_STRING = "s";
157 private static final String ATTR_TYPE_BOOLEAN = "b";
Amith Yamasani5b5aa402014-06-01 20:10:14 -0700158 private static final String ATTR_TYPE_INTEGER = "i";
Fyodor Kupolov262f9952015-03-23 18:55:11 -0700159 private static final String ATTR_TYPE_BUNDLE = "B";
160 private static final String ATTR_TYPE_BUNDLE_ARRAY = "BA";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700161
Amith Yamasani0b285492011-04-14 17:35:23 -0700162 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700163 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700164 private static final String USER_PHOTO_FILENAME = "photo.png";
Adrian Roos1bdff912015-02-17 15:51:35 +0100165 private static final String USER_PHOTO_FILENAME_TMP = USER_PHOTO_FILENAME + ".tmp";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700166
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800167 private static final String RESTRICTIONS_FILE_PREFIX = "res_";
Amith Yamasanifc95e702013-09-26 13:20:17 -0700168 private static final String XML_SUFFIX = ".xml";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800169
Sudheer Shankaf5cea032016-06-08 17:13:24 -0700170 private static final int ALLOWED_FLAGS_FOR_CREATE_USERS_PERMISSION =
171 UserInfo.FLAG_MANAGED_PROFILE
172 | UserInfo.FLAG_EPHEMERAL
173 | UserInfo.FLAG_RESTRICTED
174 | UserInfo.FLAG_GUEST;
175
Amith Yamasani634cf312012-10-04 17:34:21 -0700176 private static final int MIN_USER_ID = 10;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700177 // We need to keep process uid within Integer.MAX_VALUE.
178 private static final int MAX_USER_ID = Integer.MAX_VALUE / UserHandle.PER_USER_RANGE;
Amith Yamasani634cf312012-10-04 17:34:21 -0700179
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700180 private static final int USER_VERSION = 6;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700181
Amith Yamasani920ace02012-09-20 22:15:37 -0700182 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
183
Nicolas Prevotb8186812015-08-06 15:00:03 +0100184 // Maximum number of managed profiles permitted per user is 1. This cannot be increased
Amith Yamasani95ab7842014-08-11 17:09:26 -0700185 // without first making sure that the rest of the framework is prepared for it.
186 private static final int MAX_MANAGED_PROFILES = 1;
187
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800188 static final int WRITE_USER_MSG = 1;
189 static final int WRITE_USER_DELAY = 2*1000; // 2 seconds
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530190
Jeff Sharkey6dce4962015-07-03 18:08:41 -0700191 private static final String XATTR_SERIAL = "user.serial";
192
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -0800193 // Tron counters
194 private static final String TRON_GUEST_CREATED = "users_guest_created";
195 private static final String TRON_USER_CREATED = "users_user_created";
196
Dianne Hackborn4428e172012-08-24 17:43:05 -0700197 private final Context mContext;
198 private final PackageManagerService mPm;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700199 private final Object mPackagesLock;
Fyodor Kupolov82402752015-10-28 14:54:51 -0700200 // Short-term lock for internal state, when interaction/sync with PM is not required
201 private final Object mUsersLock = new Object();
202 private final Object mRestrictionsLock = new Object();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700203
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800204 private final Handler mHandler;
205
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700206 private final File mUsersDir;
207 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700208
Svet Ganov9cea80cd2016-02-16 11:47:00 -0800209 private static final IBinder mUserRestriconToken = new Binder();
210
Makoto Onuki068c54a2015-10-13 14:34:03 -0700211 /**
Amith Yamasani12747872015-12-07 14:19:49 -0800212 * User-related information that is used for persisting to flash. Only UserInfo is
213 * directly exposed to other system apps.
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800214 */
Amith Yamasani12747872015-12-07 14:19:49 -0800215 private static class UserData {
216 // Basic user information and properties
217 UserInfo info;
218 // Account name used when there is a strong association between a user and an account
219 String account;
220 // Account information for seeding into a newly created user. This could also be
221 // used for login validation for an existing user, for updating their credentials.
222 // In the latter case, data may not need to be persisted as it is only valid for the
223 // current login session.
224 String seedAccountName;
225 String seedAccountType;
226 PersistableBundle seedAccountOptions;
227 // Whether to perist the seed account information to be available after a boot
228 boolean persistSeedData;
229
230 void clearSeedAccountData() {
231 seedAccountName = null;
232 seedAccountType = null;
233 seedAccountOptions = null;
234 persistSeedData = false;
235 }
236 }
237
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800238 @GuardedBy("mUsersLock")
Amith Yamasani12747872015-12-07 14:19:49 -0800239 private final SparseArray<UserData> mUsers = new SparseArray<>();
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800240
241 /**
Makoto Onuki068c54a2015-10-13 14:34:03 -0700242 * User restrictions set via UserManager. This doesn't include restrictions set by
243 * device owner / profile owners.
244 *
245 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
246 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
247 * maybe shared between {@link #mBaseUserRestrictions} and
248 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
249 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700250 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700251 */
252 @GuardedBy("mRestrictionsLock")
253 private final SparseArray<Bundle> mBaseUserRestrictions = new SparseArray<>();
254
255 /**
256 * Cached user restrictions that are in effect -- i.e. {@link #mBaseUserRestrictions} combined
257 * with device / profile owner restrictions. We'll initialize it lazily; use
258 * {@link #getEffectiveUserRestrictions} to access it.
259 *
260 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
261 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
262 * maybe shared between {@link #mBaseUserRestrictions} and
263 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
264 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700265 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700266 */
267 @GuardedBy("mRestrictionsLock")
268 private final SparseArray<Bundle> mCachedEffectiveUserRestrictions = new SparseArray<>();
269
Makoto Onuki4f160732015-10-27 17:15:38 -0700270 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800271 * User restrictions that have already been applied in
272 * {@link #updateUserRestrictionsInternalLR(Bundle, int)}. We use it to detect restrictions
273 * that have changed since the last
274 * {@link #updateUserRestrictionsInternalLR(Bundle, int)} call.
Makoto Onuki4f160732015-10-27 17:15:38 -0700275 */
276 @GuardedBy("mRestrictionsLock")
277 private final SparseArray<Bundle> mAppliedUserRestrictions = new SparseArray<>();
278
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800279 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800280 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
281 * that should be applied to all users, including guests.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800282 */
283 @GuardedBy("mRestrictionsLock")
284 private Bundle mDevicePolicyGlobalUserRestrictions;
285
286 /**
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +0100287 * Id of the user that set global restrictions.
288 */
289 @GuardedBy("mRestrictionsLock")
290 private int mGlobalRestrictionOwnerUserId = UserHandle.USER_NULL;
291
292 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800293 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
294 * for each user.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800295 */
296 @GuardedBy("mRestrictionsLock")
297 private final SparseArray<Bundle> mDevicePolicyLocalUserRestrictions = new SparseArray<>();
298
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800299 @GuardedBy("mGuestRestrictions")
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530300 private final Bundle mGuestRestrictions = new Bundle();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800301
302 /**
303 * Set of user IDs being actively removed. Removed IDs linger in this set
304 * for several seconds to work around a VFS caching issue.
305 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700306 @GuardedBy("mUsersLock")
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800307 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700308
Fyodor Kupolov82402752015-10-28 14:54:51 -0700309 @GuardedBy("mUsersLock")
Amith Yamasani0b285492011-04-14 17:35:23 -0700310 private int[] mUserIds;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800311 @GuardedBy("mPackagesLock")
Amith Yamasani2a003292012-08-14 18:25:45 -0700312 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700313 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700314
Jason Monk62062992014-05-06 09:55:28 -0400315 private IAppOpsService mAppOpsService;
316
Makoto Onuki068c54a2015-10-13 14:34:03 -0700317 private final LocalService mLocalService;
318
Makoto Onukie7927da2015-11-25 10:05:17 -0800319 @GuardedBy("mUsersLock")
320 private boolean mIsDeviceManaged;
321
322 @GuardedBy("mUsersLock")
323 private final SparseBooleanArray mIsUserManaged = new SparseBooleanArray();
324
Makoto Onukid45a4a22015-11-02 17:17:38 -0800325 @GuardedBy("mUserRestrictionsListeners")
326 private final ArrayList<UserRestrictionsListener> mUserRestrictionsListeners =
327 new ArrayList<>();
328
Clara Bayarria1771112015-12-18 16:29:18 +0000329 private final LockPatternUtils mLockPatternUtils;
330
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +0100331 /**
332 * Whether all users should be created ephemeral.
333 */
334 @GuardedBy("mUsersLock")
335 private boolean mForceEphemeralUsers;
336
Fyodor Kupolovac06a492016-05-25 14:45:29 -0700337 @GuardedBy("mUserStates")
338 private final SparseIntArray mUserStates = new SparseIntArray();
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -0700339
Amith Yamasani258848d2012-08-10 17:06:33 -0700340 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700341
Dianne Hackborn4428e172012-08-24 17:43:05 -0700342 public static UserManagerService getInstance() {
343 synchronized (UserManagerService.class) {
344 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700345 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700346 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700347
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800348 @VisibleForTesting
349 UserManagerService(File dataDir) {
350 this(null, null, new Object(), dataDir);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700351 }
352
Dianne Hackborn4428e172012-08-24 17:43:05 -0700353 /**
354 * Called by package manager to create the service. This is closely
355 * associated with the package manager, and the given lock is the
356 * package manager's own lock.
357 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800358 UserManagerService(Context context, PackageManagerService pm, Object packagesLock) {
359 this(context, pm, packagesLock, Environment.getDataDirectory());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700360 }
361
Dianne Hackborn4428e172012-08-24 17:43:05 -0700362 private UserManagerService(Context context, PackageManagerService pm,
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800363 Object packagesLock, File dataDir) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700364 mContext = context;
365 mPm = pm;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700366 mPackagesLock = packagesLock;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800367 mHandler = new MainHandler();
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800368 synchronized (mPackagesLock) {
369 mUsersDir = new File(dataDir, USER_INFO_DIR);
370 mUsersDir.mkdirs();
371 // Make zeroth user directory, for services to migrate their files to that location
372 File userZeroDir = new File(mUsersDir, String.valueOf(UserHandle.USER_SYSTEM));
373 userZeroDir.mkdirs();
374 FileUtils.setPermissions(mUsersDir.toString(),
375 FileUtils.S_IRWXU | FileUtils.S_IRWXG | FileUtils.S_IROTH | FileUtils.S_IXOTH,
376 -1, -1);
377 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
378 initDefaultGuestRestrictions();
379 readUserListLP();
380 sInstance = this;
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700381 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700382 mLocalService = new LocalService();
383 LocalServices.addService(UserManagerInternal.class, mLocalService);
Clara Bayarria1771112015-12-18 16:29:18 +0000384 mLockPatternUtils = new LockPatternUtils(mContext);
Fyodor Kupolovac06a492016-05-25 14:45:29 -0700385 mUserStates.put(UserHandle.USER_SYSTEM, UserState.STATE_BOOTING);
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700386 }
387
388 void systemReady() {
Lenka Trochtovac4dd0212015-11-18 12:22:06 +0100389 // Prune out any partially created, partially removed and ephemeral users.
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800390 ArrayList<UserInfo> partials = new ArrayList<>();
391 synchronized (mUsersLock) {
392 final int userSize = mUsers.size();
393 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800394 UserInfo ui = mUsers.valueAt(i).info;
Lenka Trochtovac4dd0212015-11-18 12:22:06 +0100395 if ((ui.partial || ui.guestToRemove || ui.isEphemeral()) && i != 0) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800396 partials.add(ui);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700397 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700398 }
Dianne Hackborn4428e172012-08-24 17:43:05 -0700399 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800400 final int partialsSize = partials.size();
401 for (int i = 0; i < partialsSize; i++) {
402 UserInfo ui = partials.get(i);
403 Slog.w(LOG_TAG, "Removing partially created user " + ui.id
404 + " (name=" + ui.name + ")");
405 removeUserState(ui.id);
406 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800407
Jason Monk62062992014-05-06 09:55:28 -0400408 mAppOpsService = IAppOpsService.Stub.asInterface(
409 ServiceManager.getService(Context.APP_OPS_SERVICE));
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800410
411 synchronized (mRestrictionsLock) {
412 applyUserRestrictionsLR(UserHandle.USER_SYSTEM);
Jason Monk62062992014-05-06 09:55:28 -0400413 }
Samuel Tand9453b82016-03-14 15:57:02 -0700414
415 UserInfo currentGuestUser = findCurrentGuestUser();
416 if (currentGuestUser != null && !hasUserRestriction(
417 UserManager.DISALLOW_CONFIG_WIFI, currentGuestUser.id)) {
418 // If a guest user currently exists, apply the DISALLOW_CONFIG_WIFI option
419 // to it, in case this guest was created in a previous version where this
420 // user restriction was not a default guest restriction.
421 setUserRestriction(UserManager.DISALLOW_CONFIG_WIFI, true, currentGuestUser.id);
422 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700423 }
424
425 @Override
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800426 public String getUserAccount(int userId) {
427 checkManageUserAndAcrossUsersFullPermission("get user account");
428 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800429 return mUsers.get(userId).account;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800430 }
431 }
432
433 @Override
434 public void setUserAccount(int userId, String accountName) {
435 checkManageUserAndAcrossUsersFullPermission("set user account");
Amith Yamasani12747872015-12-07 14:19:49 -0800436 UserData userToUpdate = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800437 synchronized (mPackagesLock) {
438 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800439 final UserData userData = mUsers.get(userId);
440 if (userData == null) {
441 Slog.e(LOG_TAG, "User not found for setting user account: u" + userId);
442 return;
443 }
444 String currentAccount = userData.account;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800445 if (!Objects.equal(currentAccount, accountName)) {
Amith Yamasani12747872015-12-07 14:19:49 -0800446 userData.account = accountName;
447 userToUpdate = userData;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800448 }
449 }
450
451 if (userToUpdate != null) {
452 writeUserLP(userToUpdate);
453 }
454 }
455 }
456
457 @Override
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700458 public UserInfo getPrimaryUser() {
459 checkManageUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700460 synchronized (mUsersLock) {
Amith Yamasani515d4062015-09-28 11:30:06 -0700461 final int userSize = mUsers.size();
462 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800463 UserInfo ui = mUsers.valueAt(i).info;
Xiaohui Chend3e9e182015-11-18 13:37:32 -0800464 if (ui.isPrimary() && !mRemovingUserIds.get(ui.id)) {
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700465 return ui;
466 }
467 }
468 }
469 return null;
470 }
471
472 @Override
Xiaohui Chen594f2082015-08-18 11:04:20 -0700473 public @NonNull List<UserInfo> getUsers(boolean excludeDying) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -0700474 checkManageOrCreateUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700475 synchronized (mUsersLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700476 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasani515d4062015-09-28 11:30:06 -0700477 final int userSize = mUsers.size();
478 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800479 UserInfo ui = mUsers.valueAt(i).info;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700480 if (ui.partial) {
481 continue;
482 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800483 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Amith Yamasani6f48d6e2016-03-23 14:28:25 -0700484 users.add(userWithName(ui));
Amith Yamasani920ace02012-09-20 22:15:37 -0700485 }
Amith Yamasani13593602012-03-22 16:16:17 -0700486 }
487 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700488 }
Amith Yamasani13593602012-03-22 16:16:17 -0700489 }
490
Amith Yamasani258848d2012-08-10 17:06:33 -0700491 @Override
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100492 public List<UserInfo> getProfiles(int userId, boolean enabledOnly) {
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700493 boolean returnFullInfo = true;
Amith Yamasani4f582632014-02-19 14:31:52 -0800494 if (userId != UserHandle.getCallingUserId()) {
495 checkManageUsersPermission("getting profiles related to user " + userId);
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700496 } else {
497 returnFullInfo = hasManageUsersPermission();
Amith Yamasani4f582632014-02-19 14:31:52 -0800498 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700499 final long ident = Binder.clearCallingIdentity();
500 try {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700501 synchronized (mUsersLock) {
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700502 return getProfilesLU(userId, enabledOnly, returnFullInfo);
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100503 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700504 } finally {
505 Binder.restoreCallingIdentity(ident);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000506 }
507 }
508
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700509 @Override
510 public int[] getProfileIds(int userId, boolean enabledOnly) {
511 if (userId != UserHandle.getCallingUserId()) {
512 checkManageUsersPermission("getting profiles related to user " + userId);
513 }
514 final long ident = Binder.clearCallingIdentity();
515 try {
516 synchronized (mUsersLock) {
517 return getProfileIdsLU(userId, enabledOnly).toArray();
518 }
519 } finally {
520 Binder.restoreCallingIdentity(ident);
521 }
522 }
523
Amith Yamasanibe465322014-04-24 13:45:17 -0700524 /** Assume permissions already checked and caller's identity cleared */
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700525 private List<UserInfo> getProfilesLU(int userId, boolean enabledOnly, boolean fullInfo) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700526 IntArray profileIds = getProfileIdsLU(userId, enabledOnly);
527 ArrayList<UserInfo> users = new ArrayList<>(profileIds.size());
528 for (int i = 0; i < profileIds.size(); i++) {
529 int profileId = profileIds.get(i);
530 UserInfo userInfo = mUsers.get(profileId).info;
531 // If full info is not required - clear PII data to prevent 3P apps from reading it
532 if (!fullInfo) {
533 userInfo = new UserInfo(userInfo);
534 userInfo.name = null;
535 userInfo.iconPath = null;
536 } else {
537 userInfo = userWithName(userInfo);
538 }
539 users.add(userInfo);
540 }
541 return users;
542 }
543
544 /**
545 * Assume permissions already checked and caller's identity cleared
546 */
547 private IntArray getProfileIdsLU(int userId, boolean enabledOnly) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700548 UserInfo user = getUserInfoLU(userId);
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700549 IntArray result = new IntArray(mUsers.size());
Amith Yamasanidda003f2014-08-28 18:06:51 -0700550 if (user == null) {
551 // Probably a dying user
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700552 return result;
Amith Yamasanidda003f2014-08-28 18:06:51 -0700553 }
Amith Yamasani515d4062015-09-28 11:30:06 -0700554 final int userSize = mUsers.size();
555 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800556 UserInfo profile = mUsers.valueAt(i).info;
Amith Yamasanibe465322014-04-24 13:45:17 -0700557 if (!isProfileOf(user, profile)) {
558 continue;
559 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100560 if (enabledOnly && !profile.isEnabled()) {
561 continue;
Amith Yamasanibe465322014-04-24 13:45:17 -0700562 }
Amith Yamasani70fcf0c2014-07-11 08:40:19 -0700563 if (mRemovingUserIds.get(profile.id)) {
564 continue;
565 }
Tony Mak80189cd2016-04-05 17:21:42 +0100566 if (profile.partial) {
567 continue;
568 }
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700569 result.add(profile.id);
Amith Yamasanibe465322014-04-24 13:45:17 -0700570 }
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700571 return result;
Amith Yamasanibe465322014-04-24 13:45:17 -0700572 }
573
Jessica Hummelbe81c802014-04-22 15:49:22 +0100574 @Override
Andres Moralesc5548c02015-08-05 10:23:12 -0700575 public int getCredentialOwnerProfile(int userHandle) {
576 checkManageUsersPermission("get the credential owner");
Clara Bayarria1771112015-12-18 16:29:18 +0000577 if (!mLockPatternUtils.isSeparateProfileChallengeEnabled(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700578 synchronized (mUsersLock) {
579 UserInfo profileParent = getProfileParentLU(userHandle);
Andres Moralesc5548c02015-08-05 10:23:12 -0700580 if (profileParent != null) {
581 return profileParent.id;
582 }
583 }
584 }
585
586 return userHandle;
587 }
588
589 @Override
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700590 public boolean isSameProfileGroup(int userId, int otherUserId) {
591 if (userId == otherUserId) return true;
592 checkManageUsersPermission("check if in the same profile group");
593 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700594 return isSameProfileGroupLP(userId, otherUserId);
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700595 }
596 }
597
Fyodor Kupolov82402752015-10-28 14:54:51 -0700598 private boolean isSameProfileGroupLP(int userId, int otherUserId) {
599 synchronized (mUsersLock) {
600 UserInfo userInfo = getUserInfoLU(userId);
601 if (userInfo == null || userInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
602 return false;
603 }
604 UserInfo otherUserInfo = getUserInfoLU(otherUserId);
605 if (otherUserInfo == null
606 || otherUserInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
607 return false;
608 }
609 return userInfo.profileGroupId == otherUserInfo.profileGroupId;
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700610 }
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700611 }
612
613 @Override
Jessica Hummelbe81c802014-04-22 15:49:22 +0100614 public UserInfo getProfileParent(int userHandle) {
615 checkManageUsersPermission("get the profile parent");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700616 synchronized (mUsersLock) {
617 return getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700618 }
619 }
620
Fyodor Kupolov82402752015-10-28 14:54:51 -0700621 private UserInfo getProfileParentLU(int userHandle) {
622 UserInfo profile = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700623 if (profile == null) {
624 return null;
625 }
626 int parentUserId = profile.profileGroupId;
627 if (parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
628 return null;
629 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700630 return getUserInfoLU(parentUserId);
Jessica Hummelbe81c802014-04-22 15:49:22 +0100631 }
632 }
633
Fyodor Kupolov82402752015-10-28 14:54:51 -0700634 private static boolean isProfileOf(UserInfo user, UserInfo profile) {
Kenny Guy2a764942014-04-02 13:29:20 +0100635 return user.id == profile.id ||
636 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
637 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000638 }
639
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000640 private void broadcastProfileAvailabilityChanges(UserHandle profileHandle,
Rubin Xuf13c9802016-01-21 18:06:00 +0000641 UserHandle parentHandle, boolean inQuietMode) {
Rubin Xue95057a2016-04-01 16:49:25 +0100642 Intent intent = new Intent();
643 if (inQuietMode) {
644 intent.setAction(Intent.ACTION_MANAGED_PROFILE_UNAVAILABLE);
645 } else {
646 intent.setAction(Intent.ACTION_MANAGED_PROFILE_AVAILABLE);
647 }
Rubin Xuf13c9802016-01-21 18:06:00 +0000648 intent.putExtra(Intent.EXTRA_QUIET_MODE, inQuietMode);
649 intent.putExtra(Intent.EXTRA_USER, profileHandle);
650 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileHandle.getIdentifier());
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000651 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Rubin Xuf13c9802016-01-21 18:06:00 +0000652 mContext.sendBroadcastAsUser(intent, parentHandle);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000653 }
654
655 @Override
656 public void setQuietModeEnabled(int userHandle, boolean enableQuietMode) {
657 checkManageUsersPermission("silence profile");
658 boolean changed = false;
659 UserInfo profile, parent;
660 synchronized (mPackagesLock) {
661 synchronized (mUsersLock) {
662 profile = getUserInfoLU(userHandle);
663 parent = getProfileParentLU(userHandle);
664
665 }
666 if (profile == null || !profile.isManagedProfile()) {
667 throw new IllegalArgumentException("User " + userHandle + " is not a profile");
668 }
669 if (profile.isQuietModeEnabled() != enableQuietMode) {
670 profile.flags ^= UserInfo.FLAG_QUIET_MODE;
Amith Yamasani12747872015-12-07 14:19:49 -0800671 writeUserLP(getUserDataLU(profile.id));
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000672 changed = true;
673 }
674 }
675 if (changed) {
Rubin Xuf13c9802016-01-21 18:06:00 +0000676 long identity = Binder.clearCallingIdentity();
677 try {
678 if (enableQuietMode) {
Rubin Xuf8451b92016-04-01 15:50:58 +0100679 LocalServices.getService(ActivityManagerInternal.class)
680 .killForegroundAppsForUser(userHandle);
Rubin Xuf13c9802016-01-21 18:06:00 +0000681 ActivityManagerNative.getDefault().stopUser(userHandle, /* force */true, null);
682 } else {
683 ActivityManagerNative.getDefault().startUserInBackground(userHandle);
684 }
685 } catch (RemoteException e) {
686 Slog.e(LOG_TAG, "fail to start/stop user for quiet mode", e);
687 } finally {
688 Binder.restoreCallingIdentity(identity);
689 }
690
691 broadcastProfileAvailabilityChanges(profile.getUserHandle(), parent.getUserHandle(),
692 enableQuietMode);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000693 }
694 }
695
696 @Override
697 public boolean isQuietModeEnabled(int userHandle) {
698 synchronized (mPackagesLock) {
699 UserInfo info;
700 synchronized (mUsersLock) {
701 info = getUserInfoLU(userHandle);
702 }
703 if (info == null || !info.isManagedProfile()) {
Rubin Xuf13c9802016-01-21 18:06:00 +0000704 return false;
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000705 }
706 return info.isQuietModeEnabled();
707 }
708 }
709
Kenny Guya52dc3e2014-02-11 15:33:14 +0000710 @Override
Benjamin Franzf02420c2016-04-04 18:52:21 +0100711 public boolean trySetQuietModeDisabled(int userHandle, IntentSender target) {
Jeff Sharkeyce18c812016-04-27 16:00:41 -0600712 if (StorageManager.isUserKeyUnlocked(userHandle)
Ricky Wai9cc7ad62016-05-11 18:00:20 +0100713 || !mLockPatternUtils.isSecure(userHandle)) {
Benjamin Franzf02420c2016-04-04 18:52:21 +0100714 // if the user is already unlocked, no need to show a profile challenge
715 setQuietModeEnabled(userHandle, false);
716 return true;
717 }
718
719 long identity = Binder.clearCallingIdentity();
720 try {
721 // otherwise, we show a profile challenge to trigger decryption of the user
722 final KeyguardManager km = (KeyguardManager) mContext.getSystemService(
723 Context.KEYGUARD_SERVICE);
Ricky Wai7881cf82016-04-15 17:20:12 +0100724 // We should use userHandle not credentialOwnerUserId here, as even if it is unified
725 // lock, confirm screenlock page will know and show personal challenge, and unlock
726 // work profile when personal challenge is correct
Benjamin Franzf02420c2016-04-04 18:52:21 +0100727 final Intent unlockIntent = km.createConfirmDeviceCredentialIntent(null, null,
728 userHandle);
729 if (unlockIntent == null) {
730 return false;
731 }
732 if (target != null) {
733 unlockIntent.putExtra(Intent.EXTRA_INTENT, target);
734 }
735 unlockIntent.setFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
736 mContext.startActivity(unlockIntent);
737 } finally {
738 Binder.restoreCallingIdentity(identity);
739 }
740 return false;
741 }
742
743 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100744 public void setUserEnabled(int userId) {
745 checkManageUsersPermission("enable user");
746 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700747 UserInfo info;
748 synchronized (mUsersLock) {
749 info = getUserInfoLU(userId);
750 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100751 if (info != null && !info.isEnabled()) {
752 info.flags ^= UserInfo.FLAG_DISABLED;
Amith Yamasani12747872015-12-07 14:19:49 -0800753 writeUserLP(getUserDataLU(info.id));
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100754 }
755 }
756 }
757
758 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700759 public UserInfo getUserInfo(int userId) {
Tony Mak8673b282016-03-21 21:10:59 +0000760 checkManageUsersPermission("query user");
761 synchronized (mUsersLock) {
Amith Yamasani6f48d6e2016-03-23 14:28:25 -0700762 return userWithName(getUserInfoLU(userId));
763 }
764 }
765
766 /**
767 * Returns a UserInfo object with the name filled in, for Owner, or the original
768 * if the name is already set.
769 */
770 private UserInfo userWithName(UserInfo orig) {
771 if (orig != null && orig.name == null && orig.id == UserHandle.USER_SYSTEM) {
772 UserInfo withName = new UserInfo(orig);
773 withName.name = getOwnerName();
774 return withName;
775 } else {
776 return orig;
Tony Mak8673b282016-03-21 21:10:59 +0000777 }
778 }
779
780 @Override
781 public boolean isManagedProfile(int userId) {
Tony Makb531d082016-03-16 14:49:52 +0000782 int callingUserId = UserHandle.getCallingUserId();
783 if (callingUserId != userId && !hasManageUsersPermission()) {
784 synchronized (mPackagesLock) {
785 if (!isSameProfileGroupLP(callingUserId, userId)) {
786 throw new SecurityException(
Tony Mak8673b282016-03-21 21:10:59 +0000787 "You need MANAGE_USERS permission to: check if specified user a " +
788 "managed profile outside your profile group");
Tony Makb531d082016-03-16 14:49:52 +0000789 }
790 }
Tony Mak4dc008c2016-03-16 10:46:49 +0000791 }
Fyodor Kupolov82402752015-10-28 14:54:51 -0700792 synchronized (mUsersLock) {
Tony Mak8673b282016-03-21 21:10:59 +0000793 UserInfo userInfo = getUserInfoLU(userId);
794 return userInfo != null && userInfo.isManagedProfile();
Amith Yamasani13593602012-03-22 16:16:17 -0700795 }
796 }
797
Amith Yamasani71e6c692013-03-24 17:39:28 -0700798 @Override
799 public boolean isRestricted() {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700800 synchronized (mUsersLock) {
801 return getUserInfoLU(UserHandle.getCallingUserId()).isRestricted();
Amith Yamasani71e6c692013-03-24 17:39:28 -0700802 }
803 }
804
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700805 @Override
806 public boolean canHaveRestrictedProfile(int userId) {
807 checkManageUsersPermission("canHaveRestrictedProfile");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700808 synchronized (mUsersLock) {
809 final UserInfo userInfo = getUserInfoLU(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700810 if (userInfo == null || !userInfo.canHaveProfile()) {
811 return false;
812 }
813 if (!userInfo.isAdmin()) {
814 return false;
815 }
Makoto Onukie7927da2015-11-25 10:05:17 -0800816 // restricted profile can be created if there is no DO set and the admin user has no PO;
817 return !mIsDeviceManaged && !mIsUserManaged.get(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700818 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700819 }
820
Amith Yamasani195263742012-08-21 15:40:12 -0700821 /*
822 * Should be locked on mUsers before calling this.
823 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700824 private UserInfo getUserInfoLU(int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -0800825 final UserData userData = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -0700826 // If it is partial and not in the process of being removed, return as unknown user.
Amith Yamasani12747872015-12-07 14:19:49 -0800827 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700828 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
829 return null;
830 }
Amith Yamasani12747872015-12-07 14:19:49 -0800831 return userData != null ? userData.info : null;
832 }
833
834 private UserData getUserDataLU(int userId) {
835 final UserData userData = mUsers.get(userId);
836 // If it is partial and not in the process of being removed, return as unknown user.
837 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
838 return null;
839 }
840 return userData;
Amith Yamasani195263742012-08-21 15:40:12 -0700841 }
842
Fyodor Kupolov82402752015-10-28 14:54:51 -0700843 /**
844 * Obtains {@link #mUsersLock} and return UserInfo from mUsers.
845 * <p>No permissions checking or any addition checks are made</p>
846 */
847 private UserInfo getUserInfoNoChecks(int userId) {
848 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800849 final UserData userData = mUsers.get(userId);
850 return userData != null ? userData.info : null;
851 }
852 }
853
854 /**
855 * Obtains {@link #mUsersLock} and return UserData from mUsers.
856 * <p>No permissions checking or any addition checks are made</p>
857 */
858 private UserData getUserDataNoChecks(int userId) {
859 synchronized (mUsersLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700860 return mUsers.get(userId);
861 }
862 }
863
Amith Yamasani236b2b52015-08-18 14:32:14 -0700864 /** Called by PackageManagerService */
Amith Yamasani13593602012-03-22 16:16:17 -0700865 public boolean exists(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700866 return getUserInfoNoChecks(userId) != null;
Amith Yamasani13593602012-03-22 16:16:17 -0700867 }
868
Amith Yamasani258848d2012-08-10 17:06:33 -0700869 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700870 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700871 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700872 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700873 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800874 UserData userData = getUserDataNoChecks(userId);
875 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700876 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
877 return;
878 }
Amith Yamasani12747872015-12-07 14:19:49 -0800879 if (name != null && !name.equals(userData.info.name)) {
880 userData.info.name = name;
881 writeUserLP(userData);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700882 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -0700883 }
884 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700885 if (changed) {
886 sendUserInfoChangedBroadcast(userId);
887 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700888 }
889
Amith Yamasani258848d2012-08-10 17:06:33 -0700890 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700891 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700892 checkManageUsersPermission("update users");
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +0100893 if (hasUserRestriction(UserManager.DISALLOW_SET_USER_ICON, userId)) {
894 Log.w(LOG_TAG, "Cannot set user icon. DISALLOW_SET_USER_ICON is enabled.");
895 return;
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700896 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +0100897 mLocalService.setUserIcon(userId, bitmap);
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700898 }
899
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +0100900
901
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700902 private void sendUserInfoChangedBroadcast(int userId) {
903 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
904 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
905 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -0700906 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700907 }
908
Amith Yamasani258848d2012-08-10 17:06:33 -0700909 @Override
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +0100910 public ParcelFileDescriptor getUserIcon(int targetUserId) {
Adrian Roos1bdff912015-02-17 15:51:35 +0100911 String iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700912 synchronized (mPackagesLock) {
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +0100913 UserInfo targetUserInfo = getUserInfoNoChecks(targetUserId);
914 if (targetUserInfo == null || targetUserInfo.partial) {
915 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + targetUserId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700916 return null;
917 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +0100918
919 final int callingUserId = UserHandle.getCallingUserId();
920 final int callingGroupId = getUserInfoNoChecks(callingUserId).profileGroupId;
921 final int targetGroupId = targetUserInfo.profileGroupId;
922 final boolean sameGroup = (callingGroupId != UserInfo.NO_PROFILE_GROUP_ID
923 && callingGroupId == targetGroupId);
924 if ((callingUserId != targetUserId) && !sameGroup) {
Nicolas Prevot88cc3462014-05-14 14:51:48 +0100925 checkManageUsersPermission("get the icon of a user who is not related");
926 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +0100927
928 if (targetUserInfo.iconPath == null) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700929 return null;
930 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +0100931 iconPath = targetUserInfo.iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700932 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100933
934 try {
935 return ParcelFileDescriptor.open(
936 new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
937 } catch (FileNotFoundException e) {
938 Log.e(LOG_TAG, "Couldn't find icon file", e);
939 }
940 return null;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700941 }
942
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700943 public void makeInitialized(int userId) {
944 checkManageUsersPermission("makeInitialized");
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800945 boolean scheduleWriteUser = false;
Amith Yamasani12747872015-12-07 14:19:49 -0800946 UserData userData;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800947 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800948 userData = mUsers.get(userId);
949 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700950 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800951 return;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700952 }
Amith Yamasani12747872015-12-07 14:19:49 -0800953 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
954 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800955 scheduleWriteUser = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700956 }
957 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800958 if (scheduleWriteUser) {
Amith Yamasani12747872015-12-07 14:19:49 -0800959 scheduleWriteUser(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800960 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700961 }
962
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700963 /**
964 * If default guest restrictions haven't been initialized yet, add the basic
965 * restrictions.
966 */
967 private void initDefaultGuestRestrictions() {
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800968 synchronized (mGuestRestrictions) {
969 if (mGuestRestrictions.isEmpty()) {
Samuel Tand9453b82016-03-14 15:57:02 -0700970 mGuestRestrictions.putBoolean(UserManager.DISALLOW_CONFIG_WIFI, true);
Fyodor Kupolove04462c2015-11-30 15:02:53 -0800971 mGuestRestrictions.putBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, true);
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800972 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
973 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
974 }
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700975 }
976 }
977
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800978 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530979 public Bundle getDefaultGuestRestrictions() {
980 checkManageUsersPermission("getDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800981 synchronized (mGuestRestrictions) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530982 return new Bundle(mGuestRestrictions);
983 }
984 }
985
986 @Override
987 public void setDefaultGuestRestrictions(Bundle restrictions) {
988 checkManageUsersPermission("setDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800989 synchronized (mGuestRestrictions) {
990 mGuestRestrictions.clear();
991 mGuestRestrictions.putAll(restrictions);
992 }
993 synchronized (mPackagesLock) {
994 writeUserListLP();
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530995 }
996 }
997
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800998 /**
999 * See {@link UserManagerInternal#setDevicePolicyUserRestrictions(int, Bundle, Bundle)}
1000 */
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08001001 void setDevicePolicyUserRestrictionsInner(int userId, @NonNull Bundle local,
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001002 @Nullable Bundle global) {
1003 Preconditions.checkNotNull(local);
1004 boolean globalChanged = false;
1005 boolean localChanged;
1006 synchronized (mRestrictionsLock) {
1007 if (global != null) {
1008 // Update global.
1009 globalChanged = !UserRestrictionsUtils.areEqual(
1010 mDevicePolicyGlobalUserRestrictions, global);
1011 if (globalChanged) {
1012 mDevicePolicyGlobalUserRestrictions = global;
1013 }
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001014 // Remember the global restriction owner userId to be able to make a distinction
1015 // in getUserRestrictionSource on who set local policies.
1016 mGlobalRestrictionOwnerUserId = userId;
1017 } else {
Zoltan Szatmary-Ban8a5536d2016-05-27 17:56:44 +01001018 if (mGlobalRestrictionOwnerUserId == userId) {
1019 // When profile owner sets restrictions it passes null global bundle and we
1020 // reset global restriction owner userId.
1021 // This means this user used to have DO, but now the DO is gone and the user
1022 // instead has PO.
1023 mGlobalRestrictionOwnerUserId = UserHandle.USER_NULL;
1024 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001025 }
1026 {
1027 // Update local.
1028 final Bundle prev = mDevicePolicyLocalUserRestrictions.get(userId);
1029 localChanged = !UserRestrictionsUtils.areEqual(prev, local);
1030 if (localChanged) {
1031 mDevicePolicyLocalUserRestrictions.put(userId, local);
1032 }
1033 }
1034 }
1035 if (DBG) {
1036 Log.d(LOG_TAG, "setDevicePolicyUserRestrictions: userId=" + userId
1037 + " global=" + global + (globalChanged ? " (changed)" : "")
1038 + " local=" + local + (localChanged ? " (changed)" : "")
1039 );
1040 }
1041 // Don't call them within the mRestrictionsLock.
1042 synchronized (mPackagesLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001043 if (localChanged) {
Amith Yamasani12747872015-12-07 14:19:49 -08001044 writeUserLP(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001045 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06001046 if (globalChanged) {
1047 writeUserListLP();
1048 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001049 }
1050
1051 synchronized (mRestrictionsLock) {
1052 if (globalChanged) {
1053 applyUserRestrictionsForAllUsersLR();
1054 } else if (localChanged) {
1055 applyUserRestrictionsLR(userId);
1056 }
1057 }
1058 }
1059
Makoto Onuki068c54a2015-10-13 14:34:03 -07001060 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001061 private Bundle computeEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001062 final Bundle baseRestrictions =
1063 UserRestrictionsUtils.nonNull(mBaseUserRestrictions.get(userId));
1064 final Bundle global = mDevicePolicyGlobalUserRestrictions;
1065 final Bundle local = mDevicePolicyLocalUserRestrictions.get(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001066
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001067 if (UserRestrictionsUtils.isEmpty(global) && UserRestrictionsUtils.isEmpty(local)) {
1068 // Common case first.
1069 return baseRestrictions;
Makoto Onuki068c54a2015-10-13 14:34:03 -07001070 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001071 final Bundle effective = UserRestrictionsUtils.clone(baseRestrictions);
1072 UserRestrictionsUtils.merge(effective, global);
1073 UserRestrictionsUtils.merge(effective, local);
1074
Makoto Onuki068c54a2015-10-13 14:34:03 -07001075 return effective;
1076 }
1077
1078 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001079 private void invalidateEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki068c54a2015-10-13 14:34:03 -07001080 if (DBG) {
1081 Log.d(LOG_TAG, "invalidateEffectiveUserRestrictions userId=" + userId);
1082 }
1083 mCachedEffectiveUserRestrictions.remove(userId);
1084 }
1085
1086 private Bundle getEffectiveUserRestrictions(int userId) {
1087 synchronized (mRestrictionsLock) {
1088 Bundle restrictions = mCachedEffectiveUserRestrictions.get(userId);
1089 if (restrictions == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001090 restrictions = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001091 mCachedEffectiveUserRestrictions.put(userId, restrictions);
1092 }
1093 return restrictions;
Amith Yamasani8cd28b52014-06-08 17:54:27 -07001094 }
1095 }
1096
Makoto Onuki068c54a2015-10-13 14:34:03 -07001097 /** @return a specific user restriction that's in effect currently. */
1098 @Override
1099 public boolean hasUserRestriction(String restrictionKey, int userId) {
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001100 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1101 return false;
1102 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001103 Bundle restrictions = getEffectiveUserRestrictions(userId);
1104 return restrictions != null && restrictions.getBoolean(restrictionKey);
1105 }
1106
1107 /**
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001108 * @hide
1109 *
1110 * Returns who set a user restriction on a user.
1111 * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
1112 * @param restrictionKey the string key representing the restriction
1113 * @param userId the id of the user for whom to retrieve the restrictions.
1114 * @return The source of user restriction. Any combination of
1115 * {@link UserManager#RESTRICTION_NOT_SET},
1116 * {@link UserManager#RESTRICTION_SOURCE_SYSTEM},
1117 * {@link UserManager#RESTRICTION_SOURCE_DEVICE_OWNER}
1118 * and {@link UserManager#RESTRICTION_SOURCE_PROFILE_OWNER}
1119 */
1120 @Override
1121 public int getUserRestrictionSource(String restrictionKey, int userId) {
1122 checkManageUsersPermission("getUserRestrictionSource");
1123 int result = UserManager.RESTRICTION_NOT_SET;
1124
1125 // Shortcut for the most common case
1126 if (!hasUserRestriction(restrictionKey, userId)) {
1127 return result;
1128 }
1129
1130 if (hasBaseUserRestriction(restrictionKey, userId)) {
1131 result |= UserManager.RESTRICTION_SOURCE_SYSTEM;
1132 }
1133
1134 synchronized(mRestrictionsLock) {
1135 Bundle localRestrictions = mDevicePolicyLocalUserRestrictions.get(userId);
1136 if (!UserRestrictionsUtils.isEmpty(localRestrictions)
1137 && localRestrictions.getBoolean(restrictionKey)) {
1138 // Local restrictions may have been set by device owner the userId of which is
1139 // stored in mGlobalRestrictionOwnerUserId.
1140 if (mGlobalRestrictionOwnerUserId == userId) {
1141 result |= UserManager.RESTRICTION_SOURCE_DEVICE_OWNER;
1142 } else {
1143 result |= UserManager.RESTRICTION_SOURCE_PROFILE_OWNER;
1144 }
1145 }
1146 if (!UserRestrictionsUtils.isEmpty(mDevicePolicyGlobalUserRestrictions)
1147 && mDevicePolicyGlobalUserRestrictions.getBoolean(restrictionKey)) {
1148 result |= UserManager.RESTRICTION_SOURCE_DEVICE_OWNER;
1149 }
1150 }
1151
1152 return result;
1153 }
1154
1155 /**
Makoto Onuki068c54a2015-10-13 14:34:03 -07001156 * @return UserRestrictions that are in effect currently. This always returns a new
1157 * {@link Bundle}.
1158 */
Amith Yamasani8cd28b52014-06-08 17:54:27 -07001159 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001160 public Bundle getUserRestrictions(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001161 return UserRestrictionsUtils.clone(getEffectiveUserRestrictions(userId));
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001162 }
1163
1164 @Override
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +00001165 public boolean hasBaseUserRestriction(String restrictionKey, int userId) {
1166 checkManageUsersPermission("hasBaseUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001167 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1168 return false;
1169 }
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +00001170 synchronized (mRestrictionsLock) {
1171 Bundle bundle = mBaseUserRestrictions.get(userId);
1172 return (bundle != null && bundle.getBoolean(restrictionKey, false));
1173 }
1174 }
1175
1176 @Override
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001177 public void setUserRestriction(String key, boolean value, int userId) {
Fyodor Kupolovd4b26042015-07-27 14:30:59 -07001178 checkManageUsersPermission("setUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001179 if (!UserRestrictionsUtils.isValidRestriction(key)) {
1180 return;
1181 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001182 synchronized (mRestrictionsLock) {
1183 // Note we can't modify Bundles stored in mBaseUserRestrictions directly, so create
1184 // a copy.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001185 final Bundle newRestrictions = UserRestrictionsUtils.clone(
1186 mBaseUserRestrictions.get(userId));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001187 newRestrictions.putBoolean(key, value);
1188
Fyodor Kupolov82402752015-10-28 14:54:51 -07001189 updateUserRestrictionsInternalLR(newRestrictions, userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001190 }
1191 }
1192
Makoto Onuki068c54a2015-10-13 14:34:03 -07001193 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001194 * Optionally updating user restrictions, calculate the effective user restrictions and also
1195 * propagate to other services and system settings.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001196 *
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001197 * @param newRestrictions User restrictions to set.
1198 * If null, will not update user restrictions and only does the propagation.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001199 * @param userId target user ID.
1200 */
1201 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001202 private void updateUserRestrictionsInternalLR(
Makoto Onuki068c54a2015-10-13 14:34:03 -07001203 @Nullable Bundle newRestrictions, int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001204
1205 final Bundle prevAppliedRestrictions = UserRestrictionsUtils.nonNull(
1206 mAppliedUserRestrictions.get(userId));
1207
1208 // Update base restrictions.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001209 if (newRestrictions != null) {
1210 // If newRestrictions == the current one, it's probably a bug.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001211 final Bundle prevBaseRestrictions = mBaseUserRestrictions.get(userId);
1212
1213 Preconditions.checkState(prevBaseRestrictions != newRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001214 Preconditions.checkState(mCachedEffectiveUserRestrictions.get(userId)
1215 != newRestrictions);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001216
1217 if (!UserRestrictionsUtils.areEqual(prevBaseRestrictions, newRestrictions)) {
1218 mBaseUserRestrictions.put(userId, newRestrictions);
Amith Yamasani12747872015-12-07 14:19:49 -08001219 scheduleWriteUser(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001220 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001221 }
1222
Fyodor Kupolov82402752015-10-28 14:54:51 -07001223 final Bundle effective = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001224
Makoto Onuki759a7632015-10-28 16:43:10 -07001225 mCachedEffectiveUserRestrictions.put(userId, effective);
1226
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001227 // Apply the new restrictions.
Makoto Onuki4f160732015-10-27 17:15:38 -07001228 if (DBG) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001229 debug("Applying user restrictions: userId=" + userId
1230 + " new=" + effective + " prev=" + prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001231 }
1232
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001233 if (mAppOpsService != null) { // We skip it until system-ready.
1234 final long token = Binder.clearCallingIdentity();
1235 try {
Svet Ganov9cea80cd2016-02-16 11:47:00 -08001236 mAppOpsService.setUserRestrictions(effective, mUserRestriconToken, userId);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001237 } catch (RemoteException e) {
1238 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
1239 } finally {
1240 Binder.restoreCallingIdentity(token);
1241 }
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001242 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001243
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001244 propagateUserRestrictionsLR(userId, effective, prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001245
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001246 mAppliedUserRestrictions.put(userId, new Bundle(effective));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001247 }
1248
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001249 private void propagateUserRestrictionsLR(final int userId,
Makoto Onukid45a4a22015-11-02 17:17:38 -08001250 Bundle newRestrictions, Bundle prevRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001251 // Note this method doesn't touch any state, meaning it doesn't require mRestrictionsLock
1252 // actually, but we still need some kind of synchronization otherwise we might end up
1253 // calling listeners out-of-order, thus "LR".
1254
1255 if (UserRestrictionsUtils.areEqual(newRestrictions, prevRestrictions)) {
1256 return;
1257 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08001258
1259 final Bundle newRestrictionsFinal = new Bundle(newRestrictions);
1260 final Bundle prevRestrictionsFinal = new Bundle(prevRestrictions);
1261
1262 mHandler.post(new Runnable() {
1263 @Override
1264 public void run() {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07001265 UserRestrictionsUtils.applyUserRestrictions(
1266 mContext, userId, newRestrictionsFinal, prevRestrictionsFinal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001267
Makoto Onukid45a4a22015-11-02 17:17:38 -08001268 final UserRestrictionsListener[] listeners;
1269 synchronized (mUserRestrictionsListeners) {
1270 listeners = new UserRestrictionsListener[mUserRestrictionsListeners.size()];
1271 mUserRestrictionsListeners.toArray(listeners);
1272 }
1273 for (int i = 0; i < listeners.length; i++) {
1274 listeners[i].onUserRestrictionsChanged(userId,
1275 newRestrictionsFinal, prevRestrictionsFinal);
1276 }
1277 }
1278 });
1279 }
1280
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001281 // Package private for the inner class.
1282 void applyUserRestrictionsLR(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001283 updateUserRestrictionsInternalLR(null, userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001284 }
1285
1286 @GuardedBy("mRestrictionsLock")
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001287 // Package private for the inner class.
1288 void applyUserRestrictionsForAllUsersLR() {
1289 if (DBG) {
1290 debug("applyUserRestrictionsForAllUsersLR");
1291 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001292 // First, invalidate all cached values.
Makoto Onuki4f160732015-10-27 17:15:38 -07001293 mCachedEffectiveUserRestrictions.clear();
1294
Makoto Onuki068c54a2015-10-13 14:34:03 -07001295 // We don't want to call into ActivityManagerNative while taking a lock, so we'll call
1296 // it on a handler.
1297 final Runnable r = new Runnable() {
1298 @Override
1299 public void run() {
1300 // Then get the list of running users.
1301 final int[] runningUsers;
1302 try {
1303 runningUsers = ActivityManagerNative.getDefault().getRunningUserIds();
1304 } catch (RemoteException e) {
1305 Log.w(LOG_TAG, "Unable to access ActivityManagerNative");
1306 return;
1307 }
1308 // Then re-calculate the effective restrictions and apply, only for running users.
1309 // It's okay if a new user has started after the getRunningUserIds() call,
1310 // because we'll do the same thing (re-calculate the restrictions and apply)
1311 // when we start a user.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001312 synchronized (mRestrictionsLock) {
1313 for (int i = 0; i < runningUsers.length; i++) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001314 applyUserRestrictionsLR(runningUsers[i]);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001315 }
1316 }
1317 }
1318 };
1319 mHandler.post(r);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001320 }
1321
Amith Yamasani258848d2012-08-10 17:06:33 -07001322 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001323 * Check if we've hit the limit of how many users can be created.
1324 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001325 private boolean isUserLimitReached() {
1326 int count;
1327 synchronized (mUsersLock) {
1328 count = getAliveUsersExcludingGuestsCountLU();
1329 }
1330 return count >= UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001331 }
1332
1333 @Override
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001334 public boolean canAddMoreManagedProfiles(int userId, boolean allowedToRemoveOne) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001335 checkManageUsersPermission("check if more managed profiles can be added.");
1336 if (ActivityManager.isLowRamDeviceStatic()) {
1337 return false;
1338 }
Fyodor Kupolovb6157992015-06-05 15:32:28 -07001339 if (!mContext.getPackageManager().hasSystemFeature(
1340 PackageManager.FEATURE_MANAGED_USERS)) {
1341 return false;
1342 }
Nicolas Prevotb8186812015-08-06 15:00:03 +01001343 // Limit number of managed profiles that can be created
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001344 final int managedProfilesCount = getProfiles(userId, true).size() - 1;
1345 final int profilesRemovedCount = managedProfilesCount > 0 && allowedToRemoveOne ? 1 : 0;
1346 if (managedProfilesCount - profilesRemovedCount >= MAX_MANAGED_PROFILES) {
Nicolas Prevotb8186812015-08-06 15:00:03 +01001347 return false;
1348 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001349 synchronized(mUsersLock) {
1350 UserInfo userInfo = getUserInfoLU(userId);
Nicolas Prevotb8186812015-08-06 15:00:03 +01001351 if (!userInfo.canHaveProfile()) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001352 return false;
1353 }
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001354 int usersCountAfterRemoving = getAliveUsersExcludingGuestsCountLU()
1355 - profilesRemovedCount;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001356 // We allow creating a managed profile in the special case where there is only one user.
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001357 return usersCountAfterRemoving == 1
1358 || usersCountAfterRemoving < UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001359 }
1360 }
1361
Fyodor Kupolov82402752015-10-28 14:54:51 -07001362 private int getAliveUsersExcludingGuestsCountLU() {
Amith Yamasanif584f012014-05-19 17:57:25 -07001363 int aliveUserCount = 0;
1364 final int totalUserCount = mUsers.size();
1365 // Skip over users being removed
1366 for (int i = 0; i < totalUserCount; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001367 UserInfo user = mUsers.valueAt(i).info;
Amith Yamasani95ab7842014-08-11 17:09:26 -07001368 if (!mRemovingUserIds.get(user.id)
Amith Yamasani1df14732014-08-29 21:37:27 -07001369 && !user.isGuest() && !user.partial) {
Amith Yamasanif584f012014-05-19 17:57:25 -07001370 aliveUserCount++;
1371 }
1372 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001373 return aliveUserCount;
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001374 }
1375
1376 /**
Amith Yamasani195263742012-08-21 15:40:12 -07001377 * Enforces that only the system UID or root's UID or apps that have the
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001378 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} and
1379 * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL INTERACT_ACROSS_USERS_FULL}
1380 * permissions can make certain calls to the UserManager.
1381 *
1382 * @param message used as message if SecurityException is thrown
1383 * @throws SecurityException if the caller does not have enough privilege.
1384 */
1385 private static final void checkManageUserAndAcrossUsersFullPermission(String message) {
1386 final int uid = Binder.getCallingUid();
1387 if (uid != Process.SYSTEM_UID && uid != 0
1388 && ActivityManager.checkComponentPermission(
1389 Manifest.permission.MANAGE_USERS,
1390 uid, -1, true) != PackageManager.PERMISSION_GRANTED
1391 && ActivityManager.checkComponentPermission(
1392 Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1393 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
1394 throw new SecurityException(
1395 "You need MANAGE_USERS and INTERACT_ACROSS_USERS_FULL permission to: "
1396 + message);
1397 }
1398 }
1399
1400 /**
1401 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001402 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -07001403 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -07001404 *
1405 * @param message used as message if SecurityException is thrown
1406 * @throws SecurityException if the caller is not system or root
Tony Mak4dc008c2016-03-16 10:46:49 +00001407 * @see #hasManageUsersPermission()
Amith Yamasani258848d2012-08-10 17:06:33 -07001408 */
Amith Yamasanibe465322014-04-24 13:45:17 -07001409 private static final void checkManageUsersPermission(String message) {
Tony Mak4dc008c2016-03-16 10:46:49 +00001410 if (!hasManageUsersPermission()) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001411 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
1412 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -04001413 }
1414
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001415 /**
Sudheer Shankaf5cea032016-06-08 17:13:24 -07001416 * Enforces that only the system UID or root's UID or apps that have the
1417 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or
1418 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS}
1419 * can make certain calls to the UserManager.
1420 *
1421 * @param message used as message if SecurityException is thrown
1422 * @throws SecurityException if the caller is not system or root
1423 * @see #hasManageOrCreateUsersPermission()
1424 */
1425 private static final void checkManageOrCreateUsersPermission(String message) {
1426 if (!hasManageOrCreateUsersPermission()) {
1427 throw new SecurityException(
1428 "You either need MANAGE_USERS or CREATE_USERS permission to: " + message);
1429 }
1430 }
1431
1432 /**
1433 * Similar to {@link #checkManageOrCreateUsersPermission(String)} but when the caller is tries
1434 * to create user/profiles other than what is allowed for
1435 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS} permission, then it will only
1436 * allow callers with {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} permission.
1437 */
1438 private static final void checkManageOrCreateUsersPermission(int creationFlags) {
1439 if ((creationFlags & ~ALLOWED_FLAGS_FOR_CREATE_USERS_PERMISSION) == 0) {
1440 if (!hasManageOrCreateUsersPermission()) {
1441 throw new SecurityException("You either need MANAGE_USERS or CREATE_USERS "
1442 + "permission to create an user with flags: " + creationFlags);
1443 }
1444 } else if (!hasManageUsersPermission()) {
1445 throw new SecurityException("You need MANAGE_USERS permission to create an user "
1446 + " with flags: " + creationFlags);
1447 }
1448 }
1449
1450 /**
Tony Mak4dc008c2016-03-16 10:46:49 +00001451 * @return whether the calling UID is system UID or root's UID or the calling app has the
1452 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}.
1453 */
1454 private static final boolean hasManageUsersPermission() {
1455 final int callingUid = Binder.getCallingUid();
1456 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
1457 || callingUid == Process.ROOT_UID
1458 || ActivityManager.checkComponentPermission(
1459 android.Manifest.permission.MANAGE_USERS,
1460 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED;
1461 }
1462
1463 /**
Sudheer Shankaf5cea032016-06-08 17:13:24 -07001464 * @return whether the calling UID is system UID or root's UID or the calling app has the
1465 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or
1466 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS}.
1467 */
1468 private static final boolean hasManageOrCreateUsersPermission() {
1469 final int callingUid = Binder.getCallingUid();
1470 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
1471 || callingUid == Process.ROOT_UID
1472 || ActivityManager.checkComponentPermission(
1473 android.Manifest.permission.MANAGE_USERS,
1474 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED
1475 || ActivityManager.checkComponentPermission(
1476 android.Manifest.permission.CREATE_USERS,
1477 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED;
1478 }
1479
1480 /**
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001481 * Enforces that only the system UID or root's UID (on any user) can make certain calls to the
1482 * UserManager.
1483 *
1484 * @param message used as message if SecurityException is thrown
1485 * @throws SecurityException if the caller is not system or root
1486 */
1487 private static void checkSystemOrRoot(String message) {
1488 final int uid = Binder.getCallingUid();
1489 if (!UserHandle.isSameApp(uid, Process.SYSTEM_UID) && uid != Process.ROOT_UID) {
1490 throw new SecurityException("Only system may: " + message);
1491 }
1492 }
1493
Fyodor Kupolov82402752015-10-28 14:54:51 -07001494 private void writeBitmapLP(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001495 try {
1496 File dir = new File(mUsersDir, Integer.toString(info.id));
1497 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +01001498 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001499 if (!dir.exists()) {
1500 dir.mkdir();
1501 FileUtils.setPermissions(
1502 dir.getPath(),
1503 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
1504 -1, -1);
1505 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001506 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +01001507 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001508 && tmp.renameTo(file) && SELinux.restorecon(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -07001509 info.iconPath = file.getAbsolutePath();
1510 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001511 try {
1512 os.close();
1513 } catch (IOException ioe) {
1514 // What the ... !
1515 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001516 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001517 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001518 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001519 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001520 }
1521
Amith Yamasani0b285492011-04-14 17:35:23 -07001522 /**
1523 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
1524 * cache it elsewhere.
1525 * @return the array of user ids.
1526 */
Dianne Hackborn1676c852012-09-10 14:52:30 -07001527 public int[] getUserIds() {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001528 synchronized (mUsersLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001529 return mUserIds;
1530 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001531 }
1532
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001533 private void readUserListLP() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001534 if (!mUserListFile.exists()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001535 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001536 return;
1537 }
1538 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001539 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001540 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001541 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001542 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001543 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001544 int type;
1545 while ((type = parser.next()) != XmlPullParser.START_TAG
1546 && type != XmlPullParser.END_DOCUMENT) {
Amith Yamasani12747872015-12-07 14:19:49 -08001547 // Skip
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001548 }
1549
1550 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001551 Slog.e(LOG_TAG, "Unable to read user list");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001552 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001553 return;
1554 }
1555
Amith Yamasani2a003292012-08-14 18:25:45 -07001556 mNextSerialNumber = -1;
1557 if (parser.getName().equals(TAG_USERS)) {
1558 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
1559 if (lastSerialNumber != null) {
1560 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
1561 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001562 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
1563 if (versionNumber != null) {
1564 mUserVersion = Integer.parseInt(versionNumber);
1565 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001566 }
1567
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001568 final Bundle newDevicePolicyGlobalUserRestrictions = new Bundle();
1569
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001570 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301571 if (type == XmlPullParser.START_TAG) {
1572 final String name = parser.getName();
1573 if (name.equals(TAG_USER)) {
1574 String id = parser.getAttributeValue(null, ATTR_ID);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001575
Amith Yamasani12747872015-12-07 14:19:49 -08001576 UserData userData = readUserLP(Integer.parseInt(id));
1577
1578 if (userData != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001579 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001580 mUsers.put(userData.info.id, userData);
1581 if (mNextSerialNumber < 0
1582 || mNextSerialNumber <= userData.info.id) {
1583 mNextSerialNumber = userData.info.id + 1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001584 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301585 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001586 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301587 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -08001588 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1589 && type != XmlPullParser.END_TAG) {
1590 if (type == XmlPullParser.START_TAG) {
1591 if (parser.getName().equals(TAG_RESTRICTIONS)) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001592 synchronized (mGuestRestrictions) {
1593 UserRestrictionsUtils
1594 .readRestrictions(parser, mGuestRestrictions);
1595 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001596 } else if (parser.getName().equals(TAG_DEVICE_POLICY_RESTRICTIONS)
1597 ) {
1598 UserRestrictionsUtils.readRestrictions(parser,
1599 newDevicePolicyGlobalUserRestrictions);
Amith Yamasanida0b1682014-11-21 12:58:17 -08001600 }
1601 break;
1602 }
1603 }
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001604 } else if (name.equals(TAG_GLOBAL_RESTRICTION_OWNER_ID)) {
1605 String ownerUserId = parser.getAttributeValue(null, ATTR_ID);
1606 if (ownerUserId != null) {
1607 mGlobalRestrictionOwnerUserId = Integer.parseInt(ownerUserId);
1608 }
Amith Yamasani258848d2012-08-10 17:06:33 -07001609 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001610 }
1611 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001612 synchronized (mRestrictionsLock) {
1613 mDevicePolicyGlobalUserRestrictions = newDevicePolicyGlobalUserRestrictions;
1614 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001615 updateUserIds();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001616 upgradeIfNecessaryLP();
1617 } catch (IOException | XmlPullParserException e) {
1618 fallbackToSingleUserLP();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001619 } finally {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001620 IoUtils.closeQuietly(fis);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001621 }
1622 }
1623
Amith Yamasani6f34b412012-10-22 18:19:27 -07001624 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -08001625 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -07001626 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001627 private void upgradeIfNecessaryLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001628 final int originalVersion = mUserVersion;
Amith Yamasani6f34b412012-10-22 18:19:27 -07001629 int userVersion = mUserVersion;
1630 if (userVersion < 1) {
1631 // Assign a proper name for the owner, if not initialized correctly before
Amith Yamasani12747872015-12-07 14:19:49 -08001632 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
1633 if ("Primary".equals(userData.info.name)) {
1634 userData.info.name =
1635 mContext.getResources().getString(com.android.internal.R.string.owner_name);
1636 scheduleWriteUser(userData);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001637 }
1638 userVersion = 1;
1639 }
1640
Amith Yamasanibc9625052012-11-15 14:39:18 -08001641 if (userVersion < 2) {
1642 // Owner should be marked as initialized
Amith Yamasani12747872015-12-07 14:19:49 -08001643 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
1644 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1645 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
1646 scheduleWriteUser(userData);
Amith Yamasanibc9625052012-11-15 14:39:18 -08001647 }
1648 userVersion = 2;
1649 }
1650
Amith Yamasani350962c2013-08-06 11:18:53 -07001651
Amith Yamasani5e486f52013-08-07 11:06:44 -07001652 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -07001653 userVersion = 4;
1654 }
1655
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001656 if (userVersion < 5) {
1657 initDefaultGuestRestrictions();
1658 userVersion = 5;
1659 }
1660
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001661 if (userVersion < 6) {
1662 final boolean splitSystemUser = UserManager.isSplitSystemUser();
Fyodor Kupolov82402752015-10-28 14:54:51 -07001663 synchronized (mUsersLock) {
1664 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001665 UserData userData = mUsers.valueAt(i);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001666 // In non-split mode, only user 0 can have restricted profiles
Amith Yamasani12747872015-12-07 14:19:49 -08001667 if (!splitSystemUser && userData.info.isRestricted()
1668 && (userData.info.restrictedProfileParentId
1669 == UserInfo.NO_PROFILE_GROUP_ID)) {
1670 userData.info.restrictedProfileParentId = UserHandle.USER_SYSTEM;
1671 scheduleWriteUser(userData);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001672 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001673 }
1674 }
1675 userVersion = 6;
1676 }
1677
Amith Yamasani6f34b412012-10-22 18:19:27 -07001678 if (userVersion < USER_VERSION) {
1679 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
1680 + USER_VERSION);
1681 } else {
1682 mUserVersion = userVersion;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001683
1684 if (originalVersion < mUserVersion) {
1685 writeUserListLP();
1686 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001687 }
1688 }
1689
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001690 private void fallbackToSingleUserLP() {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001691 int flags = UserInfo.FLAG_INITIALIZED;
1692 // In split system user mode, the admin and primary flags are assigned to the first human
1693 // user.
1694 if (!UserManager.isSplitSystemUser()) {
1695 flags |= UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY;
1696 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001697 // Create the system user
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001698 UserInfo system = new UserInfo(UserHandle.USER_SYSTEM, null, null, flags);
Amith Yamasani12747872015-12-07 14:19:49 -08001699 UserData userData = new UserData();
1700 userData.info = system;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001701 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001702 mUsers.put(system.id, userData);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001703 }
Amith Yamasani634cf312012-10-04 17:34:21 -07001704 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -04001705 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -08001706
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001707 Bundle restrictions = new Bundle();
Makoto Onuki068c54a2015-10-13 14:34:03 -07001708 synchronized (mRestrictionsLock) {
1709 mBaseUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions);
1710 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001711
Fyodor Kupolov82402752015-10-28 14:54:51 -07001712 updateUserIds();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001713 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001714
Amith Yamasani12747872015-12-07 14:19:49 -08001715 writeUserLP(userData);
Jeff Sharkeycd575992016-03-29 14:12:49 -06001716 writeUserListLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001717 }
1718
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001719 private String getOwnerName() {
1720 return mContext.getResources().getString(com.android.internal.R.string.owner_name);
1721 }
1722
Amith Yamasani12747872015-12-07 14:19:49 -08001723 private void scheduleWriteUser(UserData UserData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001724 if (DBG) {
1725 debug("scheduleWriteUser");
1726 }
Makoto Onuki9e935a32015-11-06 14:24:24 -08001727 // No need to wrap it within a lock -- worst case, we'll just post the same message
1728 // twice.
Amith Yamasani12747872015-12-07 14:19:49 -08001729 if (!mHandler.hasMessages(WRITE_USER_MSG, UserData)) {
1730 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, UserData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001731 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
1732 }
1733 }
1734
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001735 /*
1736 * Writes the user file in this format:
1737 *
1738 * <user flags="20039023" id="0">
1739 * <name>Primary</name>
1740 * </user>
1741 */
Amith Yamasani12747872015-12-07 14:19:49 -08001742 private void writeUserLP(UserData userData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001743 if (DBG) {
Amith Yamasani12747872015-12-07 14:19:49 -08001744 debug("writeUserLP " + userData);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001745 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001746 FileOutputStream fos = null;
Amith Yamasani12747872015-12-07 14:19:49 -08001747 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userData.info.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001748 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001749 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001750 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1751
1752 // XmlSerializer serializer = XmlUtils.serializerInstance();
1753 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001754 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001755 serializer.startDocument(null, true);
1756 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1757
Amith Yamasani12747872015-12-07 14:19:49 -08001758 final UserInfo userInfo = userData.info;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001759 serializer.startTag(null, TAG_USER);
1760 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
Amith Yamasani2a003292012-08-14 18:25:45 -07001761 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001762 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Amith Yamasani920ace02012-09-20 22:15:37 -07001763 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
1764 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
1765 Long.toString(userInfo.lastLoggedInTime));
Jeff Sharkeycd575992016-03-29 14:12:49 -06001766 if (userInfo.lastLoggedInFingerprint != null) {
1767 serializer.attribute(null, ATTR_LAST_LOGGED_IN_FINGERPRINT,
1768 userInfo.lastLoggedInFingerprint);
1769 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001770 if (userInfo.iconPath != null) {
1771 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
1772 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001773 if (userInfo.partial) {
1774 serializer.attribute(null, ATTR_PARTIAL, "true");
1775 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001776 if (userInfo.guestToRemove) {
1777 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
1778 }
Kenny Guy2a764942014-04-02 13:29:20 +01001779 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
1780 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
1781 Integer.toString(userInfo.profileGroupId));
Kenny Guya52dc3e2014-02-11 15:33:14 +00001782 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001783 if (userInfo.restrictedProfileParentId != UserInfo.NO_PROFILE_GROUP_ID) {
1784 serializer.attribute(null, ATTR_RESTRICTED_PROFILE_PARENT_ID,
1785 Integer.toString(userInfo.restrictedProfileParentId));
1786 }
Amith Yamasani12747872015-12-07 14:19:49 -08001787 // Write seed data
1788 if (userData.persistSeedData) {
1789 if (userData.seedAccountName != null) {
1790 serializer.attribute(null, ATTR_SEED_ACCOUNT_NAME, userData.seedAccountName);
1791 }
1792 if (userData.seedAccountType != null) {
1793 serializer.attribute(null, ATTR_SEED_ACCOUNT_TYPE, userData.seedAccountType);
1794 }
1795 }
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001796 if (userInfo.name != null) {
1797 serializer.startTag(null, TAG_NAME);
1798 serializer.text(userInfo.name);
1799 serializer.endTag(null, TAG_NAME);
1800 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001801 synchronized (mRestrictionsLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001802 UserRestrictionsUtils.writeRestrictions(serializer,
1803 mBaseUserRestrictions.get(userInfo.id), TAG_RESTRICTIONS);
1804 UserRestrictionsUtils.writeRestrictions(serializer,
1805 mDevicePolicyLocalUserRestrictions.get(userInfo.id),
1806 TAG_DEVICE_POLICY_RESTRICTIONS);
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001807 }
Amith Yamasani12747872015-12-07 14:19:49 -08001808
1809 if (userData.account != null) {
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001810 serializer.startTag(null, TAG_ACCOUNT);
Amith Yamasani12747872015-12-07 14:19:49 -08001811 serializer.text(userData.account);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001812 serializer.endTag(null, TAG_ACCOUNT);
1813 }
1814
Amith Yamasani12747872015-12-07 14:19:49 -08001815 if (userData.persistSeedData && userData.seedAccountOptions != null) {
1816 serializer.startTag(null, TAG_SEED_ACCOUNT_OPTIONS);
1817 userData.seedAccountOptions.saveToXml(serializer);
1818 serializer.endTag(null, TAG_SEED_ACCOUNT_OPTIONS);
1819 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001820 serializer.endTag(null, TAG_USER);
1821
1822 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001823 userFile.finishWrite(fos);
1824 } catch (Exception ioe) {
Jeff Sharkeycd575992016-03-29 14:12:49 -06001825 Slog.e(LOG_TAG, "Error writing user info " + userData.info.id, ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -07001826 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001827 }
1828 }
1829
1830 /*
1831 * Writes the user list file in this format:
1832 *
Amith Yamasani2a003292012-08-14 18:25:45 -07001833 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001834 * <user id="0"></user>
1835 * <user id="2"></user>
1836 * </users>
1837 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001838 private void writeUserListLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001839 if (DBG) {
1840 debug("writeUserList");
1841 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001842 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001843 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001844 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001845 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001846 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1847
1848 // XmlSerializer serializer = XmlUtils.serializerInstance();
1849 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001850 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001851 serializer.startDocument(null, true);
1852 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1853
1854 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -07001855 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -07001856 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001857
Adam Lesinskieddeb492014-09-08 17:50:03 -07001858 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001859 synchronized (mGuestRestrictions) {
1860 UserRestrictionsUtils
1861 .writeRestrictions(serializer, mGuestRestrictions, TAG_RESTRICTIONS);
1862 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301863 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001864 synchronized (mRestrictionsLock) {
1865 UserRestrictionsUtils.writeRestrictions(serializer,
1866 mDevicePolicyGlobalUserRestrictions, TAG_DEVICE_POLICY_RESTRICTIONS);
1867 }
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001868 serializer.startTag(null, TAG_GLOBAL_RESTRICTION_OWNER_ID);
1869 serializer.attribute(null, ATTR_ID, Integer.toString(mGlobalRestrictionOwnerUserId));
1870 serializer.endTag(null, TAG_GLOBAL_RESTRICTION_OWNER_ID);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001871 int[] userIdsToWrite;
1872 synchronized (mUsersLock) {
1873 userIdsToWrite = new int[mUsers.size()];
1874 for (int i = 0; i < userIdsToWrite.length; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001875 UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001876 userIdsToWrite[i] = user.id;
1877 }
1878 }
1879 for (int id : userIdsToWrite) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001880 serializer.startTag(null, TAG_USER);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001881 serializer.attribute(null, ATTR_ID, Integer.toString(id));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001882 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001883 }
1884
1885 serializer.endTag(null, TAG_USERS);
1886
1887 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001888 userListFile.finishWrite(fos);
1889 } catch (Exception e) {
1890 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -07001891 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001892 }
1893 }
1894
Amith Yamasani12747872015-12-07 14:19:49 -08001895 private UserData readUserLP(int id) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001896 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -07001897 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001898 String name = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001899 String account = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001900 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -07001901 long creationTime = 0L;
1902 long lastLoggedInTime = 0L;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06001903 String lastLoggedInFingerprint = null;
Kenny Guy2a764942014-04-02 13:29:20 +01001904 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001905 int restrictedProfileParentId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001906 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001907 boolean guestToRemove = false;
Amith Yamasani12747872015-12-07 14:19:49 -08001908 boolean persistSeedData = false;
1909 String seedAccountName = null;
1910 String seedAccountType = null;
1911 PersistableBundle seedAccountOptions = null;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001912 Bundle baseRestrictions = new Bundle();
1913 Bundle localRestrictions = new Bundle();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001914
1915 FileInputStream fis = null;
1916 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001917 AtomicFile userFile =
Amith Yamasanifc95e702013-09-26 13:20:17 -07001918 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
Amith Yamasani2a003292012-08-14 18:25:45 -07001919 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001920 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001921 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001922 int type;
1923 while ((type = parser.next()) != XmlPullParser.START_TAG
1924 && type != XmlPullParser.END_DOCUMENT) {
Amith Yamasani12747872015-12-07 14:19:49 -08001925 // Skip
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001926 }
1927
1928 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001929 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001930 return null;
1931 }
1932
1933 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001934 int storedId = readIntAttribute(parser, ATTR_ID, -1);
1935 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001936 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001937 return null;
1938 }
Amith Yamasani920ace02012-09-20 22:15:37 -07001939 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
1940 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001941 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -07001942 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
1943 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06001944 lastLoggedInFingerprint = parser.getAttributeValue(null,
1945 ATTR_LAST_LOGGED_IN_FINGERPRINT);
Kenny Guy2a764942014-04-02 13:29:20 +01001946 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
1947 UserInfo.NO_PROFILE_GROUP_ID);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001948 restrictedProfileParentId = readIntAttribute(parser,
1949 ATTR_RESTRICTED_PROFILE_PARENT_ID, UserInfo.NO_PROFILE_GROUP_ID);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001950 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
1951 if ("true".equals(valueString)) {
1952 partial = true;
1953 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001954 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
1955 if ("true".equals(valueString)) {
1956 guestToRemove = true;
1957 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001958
Amith Yamasani12747872015-12-07 14:19:49 -08001959 seedAccountName = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_NAME);
1960 seedAccountType = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_TYPE);
1961 if (seedAccountName != null || seedAccountType != null) {
1962 persistSeedData = true;
1963 }
1964
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001965 int outerDepth = parser.getDepth();
1966 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1967 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1968 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1969 continue;
1970 }
1971 String tag = parser.getName();
1972 if (TAG_NAME.equals(tag)) {
1973 type = parser.next();
1974 if (type == XmlPullParser.TEXT) {
1975 name = parser.getText();
1976 }
1977 } else if (TAG_RESTRICTIONS.equals(tag)) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001978 UserRestrictionsUtils.readRestrictions(parser, baseRestrictions);
1979 } else if (TAG_DEVICE_POLICY_RESTRICTIONS.equals(tag)) {
1980 UserRestrictionsUtils.readRestrictions(parser, localRestrictions);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001981 } else if (TAG_ACCOUNT.equals(tag)) {
1982 type = parser.next();
1983 if (type == XmlPullParser.TEXT) {
1984 account = parser.getText();
1985 }
Amith Yamasani12747872015-12-07 14:19:49 -08001986 } else if (TAG_SEED_ACCOUNT_OPTIONS.equals(tag)) {
1987 seedAccountOptions = PersistableBundle.restoreFromXml(parser);
1988 persistSeedData = true;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001989 }
1990 }
1991 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001992
Amith Yamasani12747872015-12-07 14:19:49 -08001993 // Create the UserInfo object that gets passed around
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001994 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -07001995 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -07001996 userInfo.creationTime = creationTime;
1997 userInfo.lastLoggedInTime = lastLoggedInTime;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06001998 userInfo.lastLoggedInFingerprint = lastLoggedInFingerprint;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001999 userInfo.partial = partial;
Adam Lesinskieddeb492014-09-08 17:50:03 -07002000 userInfo.guestToRemove = guestToRemove;
Kenny Guy2a764942014-04-02 13:29:20 +01002001 userInfo.profileGroupId = profileGroupId;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002002 userInfo.restrictedProfileParentId = restrictedProfileParentId;
Amith Yamasani12747872015-12-07 14:19:49 -08002003
2004 // Create the UserData object that's internal to this class
2005 UserData userData = new UserData();
2006 userData.info = userInfo;
2007 userData.account = account;
2008 userData.seedAccountName = seedAccountName;
2009 userData.seedAccountType = seedAccountType;
2010 userData.persistSeedData = persistSeedData;
2011 userData.seedAccountOptions = seedAccountOptions;
2012
Makoto Onuki068c54a2015-10-13 14:34:03 -07002013 synchronized (mRestrictionsLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002014 mBaseUserRestrictions.put(id, baseRestrictions);
2015 mDevicePolicyLocalUserRestrictions.put(id, localRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002016 }
Amith Yamasani12747872015-12-07 14:19:49 -08002017 return userData;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002018 } catch (IOException ioe) {
2019 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08002020 } finally {
2021 if (fis != null) {
2022 try {
2023 fis.close();
2024 } catch (IOException e) {
2025 }
2026 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002027 }
2028 return null;
2029 }
2030
Amith Yamasani920ace02012-09-20 22:15:37 -07002031 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
2032 String valueString = parser.getAttributeValue(null, attr);
2033 if (valueString == null) return defaultValue;
2034 try {
2035 return Integer.parseInt(valueString);
2036 } catch (NumberFormatException nfe) {
2037 return defaultValue;
2038 }
2039 }
2040
2041 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
2042 String valueString = parser.getAttributeValue(null, attr);
2043 if (valueString == null) return defaultValue;
2044 try {
2045 return Long.parseLong(valueString);
2046 } catch (NumberFormatException nfe) {
2047 return defaultValue;
2048 }
2049 }
2050
Amith Yamasanib82add22013-07-09 11:24:44 -07002051 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002052 * Removes the app restrictions file for a specific package and user id, if it exists.
2053 */
2054 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
2055 synchronized (mPackagesLock) {
2056 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07002057 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002058 if (resFile.exists()) {
2059 resFile.delete();
2060 }
2061 }
2062 }
2063
Kenny Guya52dc3e2014-02-11 15:33:14 +00002064 @Override
Kenny Guy2a764942014-04-02 13:29:20 +01002065 public UserInfo createProfileForUser(String name, int flags, int userId) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002066 checkManageOrCreateUsersPermission(flags);
Kenny Guy2a764942014-04-02 13:29:20 +01002067 return createUserInternal(name, flags, userId);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002068 }
2069
Amith Yamasani258848d2012-08-10 17:06:33 -07002070 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07002071 public UserInfo createUser(String name, int flags) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002072 checkManageOrCreateUsersPermission(flags);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00002073 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002074 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07002075
Jessica Hummelbe81c802014-04-22 15:49:22 +01002076 private UserInfo createUserInternal(String name, int flags, int parentId) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002077 if (hasUserRestriction(UserManager.DISALLOW_ADD_USER, UserHandle.getCallingUserId())) {
Julia Reynolds75175022014-06-26 16:35:00 -04002078 Log.w(LOG_TAG, "Cannot add user. DISALLOW_ADD_USER is enabled.");
2079 return null;
2080 }
phweisse9c44062016-02-10 12:57:38 +01002081 return createUserInternalUnchecked(name, flags, parentId);
2082 }
2083
2084 private UserInfo createUserInternalUnchecked(String name, int flags, int parentId) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07002085 if (ActivityManager.isLowRamDeviceStatic()) {
2086 return null;
2087 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07002088 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Nicolas Prevot12678a92015-05-13 12:15:03 -07002089 final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002090 final boolean isRestricted = (flags & UserInfo.FLAG_RESTRICTED) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002091 final long ident = Binder.clearCallingIdentity();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002092 UserInfo userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08002093 UserData userData;
Amith Yamasanibb054c92015-07-09 14:16:27 -07002094 final int userId;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002095 try {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002096 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002097 UserData parent = null;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002098 if (parentId != UserHandle.USER_NULL) {
2099 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002100 parent = getUserDataLU(parentId);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00002101 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002102 if (parent == null) return null;
2103 }
2104 if (isManagedProfile && !canAddMoreManagedProfiles(parentId, false)) {
2105 Log.e(LOG_TAG, "Cannot add more managed profiles for user " + parentId);
2106 return null;
2107 }
2108 if (!isGuest && !isManagedProfile && isUserLimitReached()) {
2109 // If we're not adding a guest user or a managed profile and the limit has
2110 // been reached, cannot add a user.
2111 return null;
2112 }
2113 // If we're adding a guest and there already exists one, bail.
2114 if (isGuest && findCurrentGuestUser() != null) {
2115 return null;
2116 }
2117 // In legacy mode, restricted profile's parent can only be the owner user
2118 if (isRestricted && !UserManager.isSplitSystemUser()
2119 && (parentId != UserHandle.USER_SYSTEM)) {
2120 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
2121 return null;
2122 }
2123 if (isRestricted && UserManager.isSplitSystemUser()) {
2124 if (parent == null) {
2125 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be "
2126 + "specified");
Nicolas Prevot12678a92015-05-13 12:15:03 -07002127 return null;
2128 }
Amith Yamasani12747872015-12-07 14:19:49 -08002129 if (!parent.info.canHaveProfile()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002130 Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be "
2131 + "created for the specified parent user id " + parentId);
Amith Yamasani95ab7842014-08-11 17:09:26 -07002132 return null;
2133 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002134 }
Lenka Trochtova024f9792016-02-17 13:55:17 +01002135 if (!UserManager.isSplitSystemUser() && (flags & UserInfo.FLAG_EPHEMERAL) != 0) {
2136 Log.e(LOG_TAG,
2137 "Ephemeral users are supported on split-system-user systems only.");
2138 return null;
2139 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002140 // In split system user mode, we assign the first human user the primary flag.
2141 // And if there is no device owner, we also assign the admin flag to primary user.
2142 if (UserManager.isSplitSystemUser()
2143 && !isGuest && !isManagedProfile && getPrimaryUser() == null) {
2144 flags |= UserInfo.FLAG_PRIMARY;
Makoto Onukie7927da2015-11-25 10:05:17 -08002145 synchronized (mUsersLock) {
2146 if (!mIsDeviceManaged) {
2147 flags |= UserInfo.FLAG_ADMIN;
2148 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07002149 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002150 }
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002151
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002152 userId = getNextAvailableId();
2153 Environment.getUserSystemDirectory(userId).mkdirs();
Lenka Trochtova02fee152015-12-22 14:26:18 +01002154 boolean ephemeralGuests = Resources.getSystem()
2155 .getBoolean(com.android.internal.R.bool.config_guestUserEphemeral);
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002156
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002157 synchronized (mUsersLock) {
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002158 // Add ephemeral flag to guests/users if required. Also inherit it from parent.
2159 if ((isGuest && ephemeralGuests) || mForceEphemeralUsers
2160 || (parent != null && parent.info.isEphemeral())) {
2161 flags |= UserInfo.FLAG_EPHEMERAL;
2162 }
2163
2164 userInfo = new UserInfo(userId, name, null, flags);
2165 userInfo.serialNumber = mNextSerialNumber++;
2166 long now = System.currentTimeMillis();
2167 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
2168 userInfo.partial = true;
Fyodor Kupolov83c24242016-03-31 13:30:42 -07002169 userInfo.lastLoggedInFingerprint = Build.FINGERPRINT;
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002170 userData = new UserData();
2171 userData.info = userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08002172 mUsers.put(userId, userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002173 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06002174 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002175 writeUserListLP();
2176 if (parent != null) {
2177 if (isManagedProfile) {
Amith Yamasani12747872015-12-07 14:19:49 -08002178 if (parent.info.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
2179 parent.info.profileGroupId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002180 writeUserLP(parent);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002181 }
Amith Yamasani12747872015-12-07 14:19:49 -08002182 userInfo.profileGroupId = parent.info.profileGroupId;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002183 } else if (isRestricted) {
Amith Yamasani12747872015-12-07 14:19:49 -08002184 if (parent.info.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) {
2185 parent.info.restrictedProfileParentId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002186 writeUserLP(parent);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002187 }
Amith Yamasani12747872015-12-07 14:19:49 -08002188 userInfo.restrictedProfileParentId = parent.info.restrictedProfileParentId;
Makoto Onuki068c54a2015-10-13 14:34:03 -07002189 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002190 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07002191 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002192 final StorageManager storage = mContext.getSystemService(StorageManager.class);
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002193 storage.createUserKey(userId, userInfo.serialNumber, userInfo.isEphemeral());
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002194 mPm.prepareUserData(userId, userInfo.serialNumber,
Jeff Sharkey47f71082016-02-01 17:03:54 -07002195 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002196 mPm.createNewUser(userId);
2197 userInfo.partial = false;
2198 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002199 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002200 }
2201 updateUserIds();
2202 Bundle restrictions = new Bundle();
Fyodor Kupolove04462c2015-11-30 15:02:53 -08002203 if (isGuest) {
2204 synchronized (mGuestRestrictions) {
2205 restrictions.putAll(mGuestRestrictions);
2206 }
2207 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002208 synchronized (mRestrictionsLock) {
2209 mBaseUserRestrictions.append(userId, restrictions);
2210 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002211 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
2212 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
2213 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
2214 android.Manifest.permission.MANAGE_USERS);
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -08002215 MetricsLogger.count(mContext, isGuest ? TRON_GUEST_CREATED : TRON_USER_CREATED, 1);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002216 } finally {
2217 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07002218 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002219 return userInfo;
2220 }
2221
Amith Yamasani0b285492011-04-14 17:35:23 -07002222 /**
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002223 * @hide
2224 */
Amith Yamasani12747872015-12-07 14:19:49 -08002225 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002226 public UserInfo createRestrictedProfile(String name, int parentUserId) {
2227 checkManageUsersPermission("setupRestrictedProfile");
2228 final UserInfo user = createProfileForUser(name, UserInfo.FLAG_RESTRICTED, parentUserId);
2229 if (user == null) {
2230 return null;
2231 }
Fyodor Kupolov9e912ba2016-02-09 18:29:43 -08002232 long identity = Binder.clearCallingIdentity();
2233 try {
2234 setUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, true, user.id);
2235 // Change the setting before applying the DISALLOW_SHARE_LOCATION restriction, otherwise
2236 // the putIntForUser() will fail.
2237 android.provider.Settings.Secure.putIntForUser(mContext.getContentResolver(),
2238 android.provider.Settings.Secure.LOCATION_MODE,
2239 android.provider.Settings.Secure.LOCATION_MODE_OFF, user.id);
2240 setUserRestriction(UserManager.DISALLOW_SHARE_LOCATION, true, user.id);
2241 } finally {
2242 Binder.restoreCallingIdentity(identity);
2243 }
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002244 return user;
2245 }
2246
2247 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07002248 * Find the current guest user. If the Guest user is partial,
2249 * then do not include it in the results as it is about to die.
Adam Lesinskieddeb492014-09-08 17:50:03 -07002250 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002251 private UserInfo findCurrentGuestUser() {
2252 synchronized (mUsersLock) {
2253 final int size = mUsers.size();
2254 for (int i = 0; i < size; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002255 final UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002256 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
2257 return user;
2258 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002259 }
2260 }
2261 return null;
2262 }
2263
2264 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07002265 * Mark this guest user for deletion to allow us to create another guest
2266 * and switch to that user before actually removing this guest.
2267 * @param userHandle the userid of the current guest
2268 * @return whether the user could be marked for deletion
2269 */
Amith Yamasani12747872015-12-07 14:19:49 -08002270 @Override
Amith Yamasani1df14732014-08-29 21:37:27 -07002271 public boolean markGuestForDeletion(int userHandle) {
2272 checkManageUsersPermission("Only the system can remove users");
2273 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
2274 UserManager.DISALLOW_REMOVE_USER, false)) {
2275 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
2276 return false;
2277 }
2278
2279 long ident = Binder.clearCallingIdentity();
2280 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002281 final UserData userData;
Amith Yamasani1df14732014-08-29 21:37:27 -07002282 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002283 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002284 userData = mUsers.get(userHandle);
2285 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002286 return false;
2287 }
Amith Yamasani1df14732014-08-29 21:37:27 -07002288 }
Amith Yamasani12747872015-12-07 14:19:49 -08002289 if (!userData.info.isGuest()) {
Amith Yamasani1df14732014-08-29 21:37:27 -07002290 return false;
2291 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002292 // We set this to a guest user that is to be removed. This is a temporary state
2293 // where we are allowed to add new Guest users, even if this one is still not
2294 // removed. This user will still show up in getUserInfo() calls.
2295 // If we don't get around to removing this Guest user, it will be purged on next
2296 // startup.
Amith Yamasani12747872015-12-07 14:19:49 -08002297 userData.info.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07002298 // Mark it as disabled, so that it isn't returned any more when
2299 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002300 userData.info.flags |= UserInfo.FLAG_DISABLED;
2301 writeUserLP(userData);
Amith Yamasani1df14732014-08-29 21:37:27 -07002302 }
2303 } finally {
2304 Binder.restoreCallingIdentity(ident);
2305 }
2306 return true;
2307 }
2308
2309 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002310 * Removes a user and all data directories created for that user. This method should be called
2311 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07002312 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07002313 */
Amith Yamasani12747872015-12-07 14:19:49 -08002314 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -07002315 public boolean removeUser(int userHandle) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002316 checkManageOrCreateUsersPermission("Only the system can remove users");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04002317 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
2318 UserManager.DISALLOW_REMOVE_USER, false)) {
2319 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
2320 return false;
2321 }
2322
Kenny Guyee58b4f2014-05-23 15:19:53 +01002323 long ident = Binder.clearCallingIdentity();
2324 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002325 final UserData userData;
Fyodor Kupolov0df68cd2015-10-01 13:54:22 -07002326 int currentUser = ActivityManager.getCurrentUser();
2327 if (currentUser == userHandle) {
2328 Log.w(LOG_TAG, "Current user cannot be removed");
2329 return false;
2330 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002331 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002332 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002333 userData = mUsers.get(userHandle);
2334 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002335 return false;
2336 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002337
Fyodor Kupolov82402752015-10-28 14:54:51 -07002338 // We remember deleted user IDs to prevent them from being
2339 // reused during the current boot; they can still be reused
2340 // after a reboot.
2341 mRemovingUserIds.put(userHandle, true);
2342 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002343
Kenny Guyee58b4f2014-05-23 15:19:53 +01002344 try {
2345 mAppOpsService.removeUser(userHandle);
2346 } catch (RemoteException e) {
2347 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
2348 }
2349 // Set this to a partially created user, so that the user will be purged
2350 // on next startup, in case the runtime stops now before stopping and
2351 // removing the user completely.
Amith Yamasani12747872015-12-07 14:19:49 -08002352 userData.info.partial = true;
Kenny Guyee58b4f2014-05-23 15:19:53 +01002353 // Mark it as disabled, so that it isn't returned any more when
2354 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002355 userData.info.flags |= UserInfo.FLAG_DISABLED;
2356 writeUserLP(userData);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002357 }
2358
Amith Yamasani12747872015-12-07 14:19:49 -08002359 if (userData.info.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
2360 && userData.info.isManagedProfile()) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002361 // Send broadcast to notify system that the user removed was a
2362 // managed user.
Amith Yamasani12747872015-12-07 14:19:49 -08002363 sendProfileRemovedBroadcast(userData.info.profileGroupId, userData.info.id);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002364 }
2365
2366 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
2367 int res;
2368 try {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07002369 res = ActivityManagerNative.getDefault().stopUser(userHandle, /* force= */ true,
2370 new IStopUserCallback.Stub() {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002371 @Override
2372 public void userStopped(int userId) {
2373 finishRemoveUser(userId);
2374 }
2375 @Override
2376 public void userStopAborted(int userId) {
2377 }
2378 });
2379 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002380 return false;
2381 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002382 return res == ActivityManager.USER_OP_SUCCESS;
2383 } finally {
2384 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002385 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002386 }
2387
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002388 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07002389 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002390 // Let other services shutdown any activity and clean up their state before completely
2391 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002392 long ident = Binder.clearCallingIdentity();
2393 try {
2394 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
2395 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002396 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
2397 android.Manifest.permission.MANAGE_USERS,
2398
2399 new BroadcastReceiver() {
2400 @Override
2401 public void onReceive(Context context, Intent intent) {
2402 if (DBG) {
2403 Slog.i(LOG_TAG,
2404 "USER_REMOVED broadcast sent, cleaning up user data "
2405 + userHandle);
2406 }
2407 new Thread() {
Amith Yamasani12747872015-12-07 14:19:49 -08002408 @Override
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002409 public void run() {
Amith Yamasani515d4062015-09-28 11:30:06 -07002410 // Clean up any ActivityManager state
2411 LocalServices.getService(ActivityManagerInternal.class)
2412 .onUserRemoved(userHandle);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002413 removeUserState(userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002414 }
2415 }.start();
2416 }
2417 },
2418
2419 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002420 } finally {
2421 Binder.restoreCallingIdentity(ident);
2422 }
Amith Yamasani2a003292012-08-14 18:25:45 -07002423 }
2424
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002425 private void removeUserState(final int userHandle) {
Paul Crowley91293792016-03-25 15:23:07 -07002426 try {
2427 mContext.getSystemService(StorageManager.class).destroyUserKey(userHandle);
2428 } catch (IllegalStateException e) {
2429 // This may be simply because the user was partially created.
2430 Slog.i(LOG_TAG,
2431 "Destroying key for user " + userHandle + " failed, continuing anyway", e);
2432 }
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002433
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002434 // Cleanup package manager settings
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002435 mPm.cleanUpUser(this, userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002436 // Remove this user from the list
Fyodor Kupolov82402752015-10-28 14:54:51 -07002437 synchronized (mUsersLock) {
2438 mUsers.remove(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08002439 mIsUserManaged.delete(userHandle);
Fyodor Kupolovac06a492016-05-25 14:45:29 -07002440 }
2441 synchronized (mUserStates) {
2442 mUserStates.delete(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08002443 }
2444 synchronized (mRestrictionsLock) {
2445 mBaseUserRestrictions.remove(userHandle);
2446 mAppliedUserRestrictions.remove(userHandle);
2447 mCachedEffectiveUserRestrictions.remove(userHandle);
2448 mDevicePolicyLocalUserRestrictions.remove(userHandle);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002449 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002450 // Update the user list
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002451 synchronized (mPackagesLock) {
2452 writeUserListLP();
2453 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06002454 // Remove user file
2455 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
2456 userFile.delete();
Fyodor Kupolov82402752015-10-28 14:54:51 -07002457 updateUserIds();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002458
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002459 // Now that we've purged all the metadata above, destroy the actual data
2460 // on disk; if we battery pull in here we'll finish cleaning up when
2461 // reconciling after reboot.
2462 mPm.destroyUserData(userHandle,
2463 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
Amith Yamasani61f57372012-08-31 12:12:28 -07002464 }
2465
Kenny Guyf8d3a232014-05-15 16:09:52 +01002466 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01002467 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01002468 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
2469 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002470 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
Jeff Sharkeyaf6ec292015-12-17 11:19:00 -07002471 managedProfileIntent.putExtra(Intent.EXTRA_USER_HANDLE, removedUserId);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002472 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01002473 }
2474
Amith Yamasani2a003292012-08-14 18:25:45 -07002475 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002476 public Bundle getApplicationRestrictions(String packageName) {
2477 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
2478 }
2479
2480 @Override
2481 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002482 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07002483 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00002484 checkSystemOrRoot("get application restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002485 }
2486 synchronized (mPackagesLock) {
2487 // Read the restrictions from XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07002488 return readApplicationRestrictionsLP(packageName, userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002489 }
2490 }
2491
2492 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002493 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002494 int userId) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00002495 checkSystemOrRoot("set application restrictions");
Fyodor Kupolov0d88d542016-04-19 11:37:22 -07002496 if (restrictions != null) {
2497 restrictions.setDefusable(true);
2498 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002499 synchronized (mPackagesLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01002500 if (restrictions == null || restrictions.isEmpty()) {
2501 cleanAppRestrictionsForPackage(packageName, userId);
2502 } else {
2503 // Write the restrictions to XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07002504 writeApplicationRestrictionsLP(packageName, restrictions, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01002505 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002506 }
Robin Lee66e5d962014-04-09 16:44:21 +01002507
Fyodor Kupolovd2846122016-02-11 18:06:34 -08002508 // Notify package of changes via an intent - only sent to explicitly registered receivers.
2509 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
2510 changeIntent.setPackage(packageName);
2511 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
2512 mContext.sendBroadcastAsUser(changeIntent, UserHandle.of(userId));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002513 }
2514
2515 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07002516 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002517 try {
2518 return mContext.getPackageManager().getApplicationInfo(packageName,
Fyodor Kupolovd2846122016-02-11 18:06:34 -08002519 PackageManager.MATCH_UNINSTALLED_PACKAGES).uid;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002520 } catch (NameNotFoundException nnfe) {
2521 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07002522 } finally {
2523 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002524 }
2525 }
2526
Fyodor Kupolov82402752015-10-28 14:54:51 -07002527 private Bundle readApplicationRestrictionsLP(String packageName, int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002528 AtomicFile restrictionsFile =
2529 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
2530 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002531 return readApplicationRestrictionsLP(restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002532 }
2533
2534 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002535 static Bundle readApplicationRestrictionsLP(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002536 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002537 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002538 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07002539 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002540 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002541
2542 FileInputStream fis = null;
2543 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002544 fis = restrictionsFile.openRead();
2545 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002546 parser.setInput(fis, StandardCharsets.UTF_8.name());
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002547 XmlUtils.nextElement(parser);
2548 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002549 Slog.e(LOG_TAG, "Unable to read restrictions file "
2550 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002551 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002552 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002553 while (parser.next() != XmlPullParser.END_DOCUMENT) {
2554 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002555 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002556 } catch (IOException|XmlPullParserException e) {
2557 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002558 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002559 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002560 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002561 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002562 }
2563
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002564 private static void readEntry(Bundle restrictions, ArrayList<String> values,
2565 XmlPullParser parser) throws XmlPullParserException, IOException {
2566 int type = parser.getEventType();
2567 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
2568 String key = parser.getAttributeValue(null, ATTR_KEY);
2569 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
2570 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
2571 if (multiple != null) {
2572 values.clear();
2573 int count = Integer.parseInt(multiple);
2574 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
2575 if (type == XmlPullParser.START_TAG
2576 && parser.getName().equals(TAG_VALUE)) {
2577 values.add(parser.nextText().trim());
2578 count--;
2579 }
2580 }
2581 String [] valueStrings = new String[values.size()];
2582 values.toArray(valueStrings);
2583 restrictions.putStringArray(key, valueStrings);
2584 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
2585 restrictions.putBundle(key, readBundleEntry(parser, values));
2586 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
2587 final int outerDepth = parser.getDepth();
2588 ArrayList<Bundle> bundleList = new ArrayList<>();
2589 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2590 Bundle childBundle = readBundleEntry(parser, values);
2591 bundleList.add(childBundle);
2592 }
2593 restrictions.putParcelableArray(key,
2594 bundleList.toArray(new Bundle[bundleList.size()]));
2595 } else {
2596 String value = parser.nextText().trim();
2597 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
2598 restrictions.putBoolean(key, Boolean.parseBoolean(value));
2599 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
2600 restrictions.putInt(key, Integer.parseInt(value));
2601 } else {
2602 restrictions.putString(key, value);
2603 }
2604 }
2605 }
2606 }
2607
2608 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
2609 throws IOException, XmlPullParserException {
2610 Bundle childBundle = new Bundle();
2611 final int outerDepth = parser.getDepth();
2612 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2613 readEntry(childBundle, values, parser);
2614 }
2615 return childBundle;
2616 }
2617
Fyodor Kupolov82402752015-10-28 14:54:51 -07002618 private void writeApplicationRestrictionsLP(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002619 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002620 AtomicFile restrictionsFile = new AtomicFile(
2621 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07002622 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002623 writeApplicationRestrictionsLP(restrictions, restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002624 }
2625
2626 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002627 static void writeApplicationRestrictionsLP(Bundle restrictions, AtomicFile restrictionsFile) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002628 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002629 try {
2630 fos = restrictionsFile.startWrite();
2631 final BufferedOutputStream bos = new BufferedOutputStream(fos);
2632
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002633 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002634 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002635 serializer.startDocument(null, true);
2636 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2637
2638 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002639 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002640 serializer.endTag(null, TAG_RESTRICTIONS);
2641
2642 serializer.endDocument();
2643 restrictionsFile.finishWrite(fos);
2644 } catch (Exception e) {
2645 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002646 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
2647 }
2648 }
2649
2650 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
2651 throws IOException {
2652 for (String key : restrictions.keySet()) {
2653 Object value = restrictions.get(key);
2654 serializer.startTag(null, TAG_ENTRY);
2655 serializer.attribute(null, ATTR_KEY, key);
2656
2657 if (value instanceof Boolean) {
2658 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
2659 serializer.text(value.toString());
2660 } else if (value instanceof Integer) {
2661 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
2662 serializer.text(value.toString());
2663 } else if (value == null || value instanceof String) {
2664 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
2665 serializer.text(value != null ? (String) value : "");
2666 } else if (value instanceof Bundle) {
2667 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2668 writeBundle((Bundle) value, serializer);
2669 } else if (value instanceof Parcelable[]) {
2670 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
2671 Parcelable[] array = (Parcelable[]) value;
2672 for (Parcelable parcelable : array) {
2673 if (!(parcelable instanceof Bundle)) {
2674 throw new IllegalArgumentException("bundle-array can only hold Bundles");
2675 }
2676 serializer.startTag(null, TAG_ENTRY);
2677 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2678 writeBundle((Bundle) parcelable, serializer);
2679 serializer.endTag(null, TAG_ENTRY);
2680 }
2681 } else {
2682 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
2683 String[] values = (String[]) value;
2684 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
2685 for (String choice : values) {
2686 serializer.startTag(null, TAG_VALUE);
2687 serializer.text(choice != null ? choice : "");
2688 serializer.endTag(null, TAG_VALUE);
2689 }
2690 }
2691 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002692 }
2693 }
2694
2695 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07002696 public int getUserSerialNumber(int userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002697 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002698 if (!exists(userHandle)) return -1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002699 return getUserInfoLU(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07002700 }
2701 }
2702
2703 @Override
2704 public int getUserHandle(int userSerialNumber) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002705 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002706 for (int userId : mUserIds) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002707 UserInfo info = getUserInfoLU(userId);
Kenny Guy945f8832015-02-10 15:17:26 +00002708 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07002709 }
2710 // Not found
2711 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07002712 }
2713 }
2714
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002715 @Override
2716 public long getUserCreationTime(int userHandle) {
2717 int callingUserId = UserHandle.getCallingUserId();
2718 UserInfo userInfo = null;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002719 synchronized (mUsersLock) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002720 if (callingUserId == userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002721 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002722 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002723 UserInfo parent = getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002724 if (parent != null && parent.id == callingUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002725 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002726 }
2727 }
2728 }
2729 if (userInfo == null) {
2730 throw new SecurityException("userHandle can only be the calling user or a managed "
2731 + "profile associated with this user");
2732 }
2733 return userInfo.creationTime;
2734 }
2735
Amith Yamasani0b285492011-04-14 17:35:23 -07002736 /**
2737 * Caches the list of user ids in an array, adjusting the array size when necessary.
2738 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002739 private void updateUserIds() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002740 int num = 0;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002741 synchronized (mUsersLock) {
2742 final int userSize = mUsers.size();
2743 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002744 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002745 num++;
2746 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002747 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002748 final int[] newUsers = new int[num];
2749 int n = 0;
2750 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002751 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002752 newUsers[n++] = mUsers.keyAt(i);
2753 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002754 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002755 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07002756 }
2757 }
2758
2759 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002760 * Called right before a user is started. This gives us a chance to prepare
2761 * app storage and apply any user restrictions.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002762 */
2763 public void onBeforeStartUser(int userId) {
Jeff Sharkey47f71082016-02-01 17:03:54 -07002764 final int userSerial = getUserSerialNumber(userId);
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002765 mPm.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_DE);
Jeff Sharkey47f71082016-02-01 17:03:54 -07002766 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_DE);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002767
2768 if (userId != UserHandle.USER_SYSTEM) {
2769 synchronized (mRestrictionsLock) {
2770 applyUserRestrictionsLR(userId);
2771 }
Fyodor Kupolovb45d9832016-05-16 13:25:34 -07002772 UserInfo userInfo = getUserInfoNoChecks(userId);
2773 if (userInfo != null && !userInfo.isInitialized()) {
2774 mPm.onBeforeUserStartUninitialized(userId);
2775 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002776 }
2777 }
2778
2779 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002780 * Called right before a user is unlocked. This gives us a chance to prepare
2781 * app storage.
2782 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002783 public void onBeforeUnlockUser(@UserIdInt int userId) {
Jeff Sharkey47f71082016-02-01 17:03:54 -07002784 final int userSerial = getUserSerialNumber(userId);
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002785 mPm.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_CE);
Jeff Sharkey47f71082016-02-01 17:03:54 -07002786 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_CE);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002787 }
2788
2789 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002790 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasani920ace02012-09-20 22:15:37 -07002791 * @param userId the user that was just foregrounded
2792 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002793 public void onUserLoggedIn(@UserIdInt int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -08002794 UserData userData = getUserDataNoChecks(userId);
2795 if (userData == null || userData.info.partial) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002796 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
2797 return;
2798 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002799
2800 final long now = System.currentTimeMillis();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002801 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani12747872015-12-07 14:19:49 -08002802 userData.info.lastLoggedInTime = now;
Amith Yamasani920ace02012-09-20 22:15:37 -07002803 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002804 userData.info.lastLoggedInFingerprint = Build.FINGERPRINT;
2805 scheduleWriteUser(userData);
Amith Yamasani920ace02012-09-20 22:15:37 -07002806 }
2807
2808 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002809 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani742a6712011-05-04 14:49:28 -07002810 * TODO: May not be a good idea to recycle ids, in case it results in confusion
2811 * for data and battery stats collection, or unexpected cross-talk.
Amith Yamasani0b285492011-04-14 17:35:23 -07002812 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002813 private int getNextAvailableId() {
2814 synchronized (mUsersLock) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002815 int i = MIN_USER_ID;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002816 while (i < MAX_USER_ID) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002817 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002818 return i;
Amith Yamasani195263742012-08-21 15:40:12 -07002819 }
2820 i++;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002821 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002822 }
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002823 throw new IllegalStateException("No user id available!");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002824 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002825
Amith Yamasanifc95e702013-09-26 13:20:17 -07002826 private String packageToRestrictionsFileName(String packageName) {
2827 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
2828 }
2829
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002830 /**
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002831 * Enforce that serial number stored in user directory inode matches the
2832 * given expected value. Gracefully sets the serial number if currently
2833 * undefined.
2834 *
2835 * @throws IOException when problem extracting serial number, or serial
2836 * number is mismatched.
2837 */
2838 public static void enforceSerialNumber(File file, int serialNumber) throws IOException {
2839 final int foundSerial = getSerialNumber(file);
2840 Slog.v(LOG_TAG, "Found " + file + " with serial number " + foundSerial);
2841
2842 if (foundSerial == -1) {
2843 Slog.d(LOG_TAG, "Serial number missing on " + file + "; assuming current is valid");
2844 try {
2845 setSerialNumber(file, serialNumber);
2846 } catch (IOException e) {
2847 Slog.w(LOG_TAG, "Failed to set serial number on " + file, e);
2848 }
2849
2850 } else if (foundSerial != serialNumber) {
2851 throw new IOException("Found serial number " + foundSerial
2852 + " doesn't match expected " + serialNumber);
2853 }
2854 }
2855
2856 /**
2857 * Set serial number stored in user directory inode.
2858 *
2859 * @throws IOException if serial number was already set
2860 */
2861 private static void setSerialNumber(File file, int serialNumber)
2862 throws IOException {
2863 try {
2864 final byte[] buf = Integer.toString(serialNumber).getBytes(StandardCharsets.UTF_8);
2865 Os.setxattr(file.getAbsolutePath(), XATTR_SERIAL, buf, OsConstants.XATTR_CREATE);
2866 } catch (ErrnoException e) {
2867 throw e.rethrowAsIOException();
2868 }
2869 }
2870
2871 /**
2872 * Return serial number stored in user directory inode.
2873 *
2874 * @return parsed serial number, or -1 if not set
2875 */
2876 private static int getSerialNumber(File file) throws IOException {
2877 try {
2878 final byte[] buf = new byte[256];
2879 final int len = Os.getxattr(file.getAbsolutePath(), XATTR_SERIAL, buf);
2880 final String serial = new String(buf, 0, len);
2881 try {
2882 return Integer.parseInt(serial);
2883 } catch (NumberFormatException e) {
2884 throw new IOException("Bad serial number: " + serial);
2885 }
2886 } catch (ErrnoException e) {
2887 if (e.errno == OsConstants.ENODATA) {
2888 return -1;
2889 } else {
2890 throw e.rethrowAsIOException();
2891 }
2892 }
2893 }
2894
Amith Yamasani920ace02012-09-20 22:15:37 -07002895 @Override
Amith Yamasani12747872015-12-07 14:19:49 -08002896 public void setSeedAccountData(int userId, String accountName, String accountType,
2897 PersistableBundle accountOptions, boolean persist) {
2898 checkManageUsersPermission("Require MANAGE_USERS permission to set user seed data");
2899 synchronized (mPackagesLock) {
2900 final UserData userData;
2901 synchronized (mUsersLock) {
2902 userData = getUserDataLU(userId);
2903 if (userData == null) {
2904 Slog.e(LOG_TAG, "No such user for settings seed data u=" + userId);
2905 return;
2906 }
2907 userData.seedAccountName = accountName;
2908 userData.seedAccountType = accountType;
2909 userData.seedAccountOptions = accountOptions;
2910 userData.persistSeedData = persist;
2911 }
2912 if (persist) {
2913 writeUserLP(userData);
2914 }
2915 }
2916 }
2917
2918 @Override
2919 public String getSeedAccountName() throws RemoteException {
2920 checkManageUsersPermission("Cannot get seed account information");
2921 synchronized (mUsersLock) {
2922 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
2923 return userData.seedAccountName;
2924 }
2925 }
2926
2927 @Override
2928 public String getSeedAccountType() throws RemoteException {
2929 checkManageUsersPermission("Cannot get seed account information");
2930 synchronized (mUsersLock) {
2931 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
2932 return userData.seedAccountType;
2933 }
2934 }
2935
2936 @Override
2937 public PersistableBundle getSeedAccountOptions() throws RemoteException {
2938 checkManageUsersPermission("Cannot get seed account information");
2939 synchronized (mUsersLock) {
2940 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
2941 return userData.seedAccountOptions;
2942 }
2943 }
2944
2945 @Override
2946 public void clearSeedAccountData() throws RemoteException {
2947 checkManageUsersPermission("Cannot clear seed account information");
2948 synchronized (mPackagesLock) {
2949 UserData userData;
2950 synchronized (mUsersLock) {
2951 userData = getUserDataLU(UserHandle.getCallingUserId());
2952 if (userData == null) return;
2953 userData.clearSeedAccountData();
2954 }
2955 writeUserLP(userData);
2956 }
2957 }
2958
2959 @Override
2960 public boolean someUserHasSeedAccount(String accountName, String accountType)
2961 throws RemoteException {
2962 checkManageUsersPermission("Cannot check seed account information");
2963 synchronized (mUsersLock) {
2964 final int userSize = mUsers.size();
2965 for (int i = 0; i < userSize; i++) {
2966 final UserData data = mUsers.valueAt(i);
2967 if (data.info.isInitialized()) continue;
2968 if (data.seedAccountName == null || !data.seedAccountName.equals(accountName)) {
2969 continue;
2970 }
2971 if (data.seedAccountType == null || !data.seedAccountType.equals(accountType)) {
2972 continue;
2973 }
2974 return true;
2975 }
2976 }
2977 return false;
2978 }
2979
2980 @Override
Todd Kennedy60459ab2015-10-30 11:32:16 -07002981 public void onShellCommand(FileDescriptor in, FileDescriptor out,
2982 FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
2983 (new Shell()).exec(this, in, out, err, args, resultReceiver);
2984 }
2985
2986 int onShellCommand(Shell shell, String cmd) {
2987 if (cmd == null) {
2988 return shell.handleDefaultCommands(cmd);
2989 }
2990
2991 final PrintWriter pw = shell.getOutPrintWriter();
2992 try {
2993 switch(cmd) {
2994 case "list":
2995 return runList(pw);
2996 }
2997 } catch (RemoteException e) {
2998 pw.println("Remote exception: " + e);
2999 }
3000 return -1;
3001 }
3002
3003 private int runList(PrintWriter pw) throws RemoteException {
3004 final IActivityManager am = ActivityManagerNative.getDefault();
3005 final List<UserInfo> users = getUsers(false);
3006 if (users == null) {
3007 pw.println("Error: couldn't get users");
3008 return 1;
3009 } else {
3010 pw.println("Users:");
3011 for (int i = 0; i < users.size(); i++) {
Jeff Sharkeye17ac152015-11-06 22:40:29 -08003012 String running = am.isUserRunning(users.get(i).id, 0) ? " running" : "";
Todd Kennedy60459ab2015-10-30 11:32:16 -07003013 pw.println("\t" + users.get(i).toString() + running);
3014 }
3015 return 0;
3016 }
3017 }
3018
3019 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -07003020 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
3021 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
3022 != PackageManager.PERMISSION_GRANTED) {
3023 pw.println("Permission Denial: can't dump UserManager from from pid="
3024 + Binder.getCallingPid()
3025 + ", uid=" + Binder.getCallingUid()
3026 + " without permission "
3027 + android.Manifest.permission.DUMP);
3028 return;
3029 }
3030
3031 long now = System.currentTimeMillis();
3032 StringBuilder sb = new StringBuilder();
3033 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003034 synchronized (mUsersLock) {
3035 pw.println("Users:");
3036 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003037 UserData userData = mUsers.valueAt(i);
3038 if (userData == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003039 continue;
3040 }
Amith Yamasani12747872015-12-07 14:19:49 -08003041 UserInfo userInfo = userData.info;
3042 final int userId = userInfo.id;
3043 pw.print(" "); pw.print(userInfo);
3044 pw.print(" serialNo="); pw.print(userInfo.serialNumber);
Makoto Onukie7927da2015-11-25 10:05:17 -08003045 if (mRemovingUserIds.get(userId)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003046 pw.print(" <removing> ");
3047 }
Amith Yamasani12747872015-12-07 14:19:49 -08003048 if (userInfo.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003049 pw.print(" <partial>");
3050 }
3051 pw.println();
3052 pw.print(" Created: ");
Amith Yamasani12747872015-12-07 14:19:49 -08003053 if (userInfo.creationTime == 0) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003054 pw.println("<unknown>");
3055 } else {
3056 sb.setLength(0);
Amith Yamasani12747872015-12-07 14:19:49 -08003057 TimeUtils.formatDuration(now - userInfo.creationTime, sb);
Fyodor Kupolov82402752015-10-28 14:54:51 -07003058 sb.append(" ago");
3059 pw.println(sb);
3060 }
3061 pw.print(" Last logged in: ");
Amith Yamasani12747872015-12-07 14:19:49 -08003062 if (userInfo.lastLoggedInTime == 0) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003063 pw.println("<unknown>");
3064 } else {
3065 sb.setLength(0);
Amith Yamasani12747872015-12-07 14:19:49 -08003066 TimeUtils.formatDuration(now - userInfo.lastLoggedInTime, sb);
Fyodor Kupolov82402752015-10-28 14:54:51 -07003067 sb.append(" ago");
3068 pw.println(sb);
3069 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003070 pw.print(" Last logged in fingerprint: ");
3071 pw.println(userInfo.lastLoggedInFingerprint);
Makoto Onukie7927da2015-11-25 10:05:17 -08003072 pw.print(" Has profile owner: ");
3073 pw.println(mIsUserManaged.get(userId));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003074 pw.println(" Restrictions:");
3075 synchronized (mRestrictionsLock) {
3076 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003077 pw, " ", mBaseUserRestrictions.get(userInfo.id));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003078 pw.println(" Device policy local restrictions:");
3079 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003080 pw, " ", mDevicePolicyLocalUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003081 pw.println(" Effective restrictions:");
3082 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003083 pw, " ", mCachedEffectiveUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003084 }
Amith Yamasani12747872015-12-07 14:19:49 -08003085
3086 if (userData.account != null) {
3087 pw.print(" Account name: " + userData.account);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08003088 pw.println();
3089 }
Amith Yamasani12747872015-12-07 14:19:49 -08003090
3091 if (userData.seedAccountName != null) {
3092 pw.print(" Seed account name: " + userData.seedAccountName);
3093 pw.println();
3094 if (userData.seedAccountType != null) {
3095 pw.print(" account type: " + userData.seedAccountType);
3096 pw.println();
3097 }
3098 if (userData.seedAccountOptions != null) {
3099 pw.print(" account options exist");
3100 pw.println();
3101 }
3102 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003103 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003104 }
Amith Yamasani12747872015-12-07 14:19:49 -08003105 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003106 pw.println(" Device policy global restrictions:");
3107 synchronized (mRestrictionsLock) {
3108 UserRestrictionsUtils
3109 .dumpRestrictions(pw, " ", mDevicePolicyGlobalUserRestrictions);
3110 }
Makoto Onukia4f11972015-10-01 13:19:58 -07003111 pw.println();
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01003112 pw.println(" Global restrictions owner id:" + mGlobalRestrictionOwnerUserId);
3113 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003114 pw.println(" Guest restrictions:");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003115 synchronized (mGuestRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003116 UserRestrictionsUtils.dumpRestrictions(pw, " ", mGuestRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003117 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003118 synchronized (mUsersLock) {
3119 pw.println();
3120 pw.println(" Device managed: " + mIsDeviceManaged);
3121 }
Fyodor Kupolovac06a492016-05-25 14:45:29 -07003122 synchronized (mUserStates) {
3123 pw.println(" Started users state: " + mUserStates);
3124 }
Amith Yamasani12747872015-12-07 14:19:49 -08003125 // Dump some capabilities
3126 pw.println();
3127 pw.println(" Max users: " + UserManager.getMaxSupportedUsers());
3128 pw.println(" Supports switchable users: " + UserManager.supportsMultipleUsers());
Lenka Trochtova02fee152015-12-22 14:26:18 +01003129 pw.println(" All guests ephemeral: " + Resources.getSystem().getBoolean(
3130 com.android.internal.R.bool.config_guestUserEphemeral));
Amith Yamasani920ace02012-09-20 22:15:37 -07003131 }
3132 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08003133
3134 final class MainHandler extends Handler {
3135
3136 @Override
3137 public void handleMessage(Message msg) {
3138 switch (msg.what) {
3139 case WRITE_USER_MSG:
3140 removeMessages(WRITE_USER_MSG, msg.obj);
3141 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08003142 int userId = ((UserData) msg.obj).info.id;
3143 UserData userData = getUserDataNoChecks(userId);
3144 if (userData != null) {
3145 writeUserLP(userData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08003146 }
3147 }
3148 }
3149 }
3150 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07003151
3152 /**
3153 * @param userId
3154 * @return whether the user has been initialized yet
3155 */
3156 boolean isInitialized(int userId) {
3157 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
3158 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003159
3160 private class LocalService extends UserManagerInternal {
Makoto Onuki068c54a2015-10-13 14:34:03 -07003161 @Override
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003162 public void setDevicePolicyUserRestrictions(int userId, @NonNull Bundle localRestrictions,
3163 @Nullable Bundle globalRestrictions) {
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08003164 UserManagerService.this.setDevicePolicyUserRestrictionsInner(userId, localRestrictions,
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003165 globalRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003166 }
3167
3168 @Override
3169 public Bundle getBaseUserRestrictions(int userId) {
3170 synchronized (mRestrictionsLock) {
3171 return mBaseUserRestrictions.get(userId);
3172 }
3173 }
3174
3175 @Override
3176 public void setBaseUserRestrictionsByDpmsForMigration(
3177 int userId, Bundle baseRestrictions) {
3178 synchronized (mRestrictionsLock) {
3179 mBaseUserRestrictions.put(userId, new Bundle(baseRestrictions));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003180 invalidateEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003181 }
3182
Amith Yamasani12747872015-12-07 14:19:49 -08003183 final UserData userData = getUserDataNoChecks(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003184 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08003185 if (userData != null) {
3186 writeUserLP(userData);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003187 } else {
3188 Slog.w(LOG_TAG, "UserInfo not found for " + userId);
3189 }
3190 }
3191 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08003192
3193 @Override
3194 public boolean getUserRestriction(int userId, String key) {
3195 return getUserRestrictions(userId).getBoolean(key);
3196 }
3197
3198 @Override
3199 public void addUserRestrictionsListener(UserRestrictionsListener listener) {
3200 synchronized (mUserRestrictionsListeners) {
3201 mUserRestrictionsListeners.add(listener);
3202 }
3203 }
3204
3205 @Override
3206 public void removeUserRestrictionsListener(UserRestrictionsListener listener) {
3207 synchronized (mUserRestrictionsListeners) {
3208 mUserRestrictionsListeners.remove(listener);
3209 }
3210 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003211
3212 @Override
3213 public void setDeviceManaged(boolean isManaged) {
3214 synchronized (mUsersLock) {
3215 mIsDeviceManaged = isManaged;
3216 }
3217 }
3218
3219 @Override
3220 public void setUserManaged(int userId, boolean isManaged) {
3221 synchronized (mUsersLock) {
3222 mIsUserManaged.put(userId, isManaged);
3223 }
3224 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01003225
3226 @Override
3227 public void setUserIcon(int userId, Bitmap bitmap) {
3228 long ident = Binder.clearCallingIdentity();
3229 try {
3230 synchronized (mPackagesLock) {
3231 UserData userData = getUserDataNoChecks(userId);
3232 if (userData == null || userData.info.partial) {
3233 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
3234 return;
3235 }
3236 writeBitmapLP(userData.info, bitmap);
3237 writeUserLP(userData);
3238 }
3239 sendUserInfoChangedBroadcast(userId);
3240 } finally {
3241 Binder.restoreCallingIdentity(ident);
3242 }
3243 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01003244
3245 @Override
3246 public void setForceEphemeralUsers(boolean forceEphemeralUsers) {
3247 synchronized (mUsersLock) {
3248 mForceEphemeralUsers = forceEphemeralUsers;
3249 }
3250 }
3251
3252 @Override
3253 public void removeAllUsers() {
3254 if (UserHandle.USER_SYSTEM == ActivityManager.getCurrentUser()) {
3255 // Remove the non-system users straight away.
3256 removeNonSystemUsers();
3257 } else {
3258 // Switch to the system user first and then remove the other users.
3259 BroadcastReceiver userSwitchedReceiver = new BroadcastReceiver() {
3260 @Override
3261 public void onReceive(Context context, Intent intent) {
3262 int userId =
3263 intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3264 if (userId != UserHandle.USER_SYSTEM) {
3265 return;
3266 }
3267 mContext.unregisterReceiver(this);
3268 removeNonSystemUsers();
3269 }
3270 };
3271 IntentFilter userSwitchedFilter = new IntentFilter();
3272 userSwitchedFilter.addAction(Intent.ACTION_USER_SWITCHED);
3273 mContext.registerReceiver(
3274 userSwitchedReceiver, userSwitchedFilter, null, mHandler);
3275
3276 // Switch to the system user.
3277 ActivityManager am =
3278 (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
3279 am.switchUser(UserHandle.USER_SYSTEM);
3280 }
3281 }
phweisse9c44062016-02-10 12:57:38 +01003282
3283 @Override
Lenka Trochtova1ddda472016-02-12 10:42:12 +01003284 public void onEphemeralUserStop(int userId) {
3285 synchronized (mUsersLock) {
3286 UserInfo userInfo = getUserInfoLU(userId);
3287 if (userInfo != null && userInfo.isEphemeral()) {
3288 // Do not allow switching back to the ephemeral user again as the user is going
3289 // to be deleted.
3290 userInfo.flags |= UserInfo.FLAG_DISABLED;
3291 if (userInfo.isGuest()) {
3292 // Indicate that the guest will be deleted after it stops.
3293 userInfo.guestToRemove = true;
3294 }
3295 }
3296 }
3297 }
3298
3299 @Override
phweisse9c44062016-02-10 12:57:38 +01003300 public UserInfo createUserEvenWhenDisallowed(String name, int flags) {
3301 UserInfo user = createUserInternalUnchecked(name, flags, UserHandle.USER_NULL);
3302 // Keep this in sync with UserManager.createUser
3303 if (user != null && !user.isAdmin()) {
3304 setUserRestriction(UserManager.DISALLOW_SMS, true, user.id);
3305 setUserRestriction(UserManager.DISALLOW_OUTGOING_CALLS, true, user.id);
3306 }
3307 return user;
3308 }
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003309
3310 @Override
Fyodor Kupolovac06a492016-05-25 14:45:29 -07003311 public boolean isUserRunning(int userId) {
3312 synchronized (mUserStates) {
3313 return mUserStates.get(userId, -1) >= 0;
3314 }
3315 }
3316
3317 @Override
3318 public void setUserState(int userId, int userState) {
3319 synchronized (mUserStates) {
3320 mUserStates.put(userId, userState);
3321 }
3322 }
3323
3324 @Override
3325 public void removeUserState(int userId) {
3326 synchronized (mUserStates) {
3327 mUserStates.delete(userId);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003328 }
3329 }
3330
3331 @Override
3332 public boolean isUserUnlockingOrUnlocked(int userId) {
Fyodor Kupolovac06a492016-05-25 14:45:29 -07003333 synchronized (mUserStates) {
3334 int state = mUserStates.get(userId, -1);
3335 return (state == UserState.STATE_RUNNING_UNLOCKING)
3336 || (state == UserState.STATE_RUNNING_UNLOCKED);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003337 }
3338 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01003339 }
3340
3341 /* Remove all the users except of the system one. */
3342 private void removeNonSystemUsers() {
3343 ArrayList<UserInfo> usersToRemove = new ArrayList<>();
3344 synchronized (mUsersLock) {
3345 final int userSize = mUsers.size();
3346 for (int i = 0; i < userSize; i++) {
3347 UserInfo ui = mUsers.valueAt(i).info;
3348 if (ui.id != UserHandle.USER_SYSTEM) {
3349 usersToRemove.add(ui);
3350 }
3351 }
3352 }
3353 for (UserInfo ui: usersToRemove) {
3354 removeUser(ui.id);
3355 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003356 }
Todd Kennedy60459ab2015-10-30 11:32:16 -07003357
3358 private class Shell extends ShellCommand {
3359 @Override
3360 public int onCommand(String cmd) {
3361 return onShellCommand(this, cmd);
3362 }
3363
3364 @Override
3365 public void onHelp() {
3366 final PrintWriter pw = getOutPrintWriter();
3367 pw.println("User manager (user) commands:");
3368 pw.println(" help");
3369 pw.println(" Print this help text.");
3370 pw.println("");
3371 pw.println(" list");
3372 pw.println(" Prints all users on the system.");
3373 }
3374 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003375
3376 private static void debug(String message) {
3377 Log.d(LOG_TAG, message +
3378 (DBG_WITH_STACKTRACE ? " called at\n" + Debug.getCallers(10, " ") : ""));
3379 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003380}