blob: 60a0d6282483ef48e6a126aaf08d24a8385f2e5b [file] [log] [blame]
Tony Mak8673b282016-03-21 21:10:59 +00001
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002/*
3 * Copyright (C) 2011 The Android Open Source Project
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18package com.android.server.pm;
19
Xiaohui Chenb3b92582015-12-07 11:22:13 -080020import android.Manifest;
Xiaohui Chen594f2082015-08-18 11:04:20 -070021import android.annotation.NonNull;
Makoto Onuki068c54a2015-10-13 14:34:03 -070022import android.annotation.Nullable;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -060023import android.annotation.UserIdInt;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070024import android.app.Activity;
Amith Yamasani2a003292012-08-14 18:25:45 -070025import android.app.ActivityManager;
Amith Yamasani515d4062015-09-28 11:30:06 -070026import android.app.ActivityManagerInternal;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070027import android.app.ActivityManagerNative;
Todd Kennedy60459ab2015-10-30 11:32:16 -070028import android.app.IActivityManager;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070029import android.app.IStopUserCallback;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070030import android.content.BroadcastReceiver;
Amith Yamasani258848d2012-08-10 17:06:33 -070031import android.content.Context;
32import android.content.Intent;
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +010033import android.content.IntentFilter;
Amith Yamasani0b285492011-04-14 17:35:23 -070034import android.content.pm.PackageManager;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -080035import android.content.pm.PackageManager.NameNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070036import android.content.pm.UserInfo;
Lenka Trochtova02fee152015-12-22 14:26:18 +010037import android.content.res.Resources;
Amith Yamasanie928d7d2012-09-17 21:46:51 -070038import android.graphics.Bitmap;
Amith Yamasani258848d2012-08-10 17:06:33 -070039import android.os.Binder;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -060040import android.os.Build;
Amith Yamasanie4cf7342012-12-17 11:12:09 -080041import android.os.Bundle;
Makoto Onuki1a2cd742015-11-16 13:51:27 -080042import android.os.Debug;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070043import android.os.Environment;
44import android.os.FileUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080045import android.os.Handler;
Svet Ganov9cea80cd2016-02-16 11:47:00 -080046import android.os.IBinder;
Amith Yamasani258848d2012-08-10 17:06:33 -070047import android.os.IUserManager;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -080048import android.os.Message;
Adrian Roos1bdff912015-02-17 15:51:35 +010049import android.os.ParcelFileDescriptor;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070050import android.os.Parcelable;
Amith Yamasani12747872015-12-07 14:19:49 -080051import android.os.PersistableBundle;
Amith Yamasani258848d2012-08-10 17:06:33 -070052import android.os.Process;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070053import android.os.RemoteException;
Todd Kennedy60459ab2015-10-30 11:32:16 -070054import android.os.ResultReceiver;
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +010055import android.os.SELinux;
Jason Monk62062992014-05-06 09:55:28 -040056import android.os.ServiceManager;
Todd Kennedy60459ab2015-10-30 11:32:16 -070057import android.os.ShellCommand;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070058import android.os.UserHandle;
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070059import android.os.UserManager;
Makoto Onuki068c54a2015-10-13 14:34:03 -070060import android.os.UserManagerInternal;
Makoto Onukid45a4a22015-11-02 17:17:38 -080061import android.os.UserManagerInternal.UserRestrictionsListener;
Paul Crowley85e4e812015-05-19 12:42:00 +010062import android.os.storage.StorageManager;
Jeff Sharkey6dce4962015-07-03 18:08:41 -070063import android.os.storage.VolumeInfo;
64import android.system.ErrnoException;
65import android.system.Os;
66import android.system.OsConstants;
Amith Yamasani2a003292012-08-14 18:25:45 -070067import android.util.AtomicFile;
Amith Yamasani655d0e22013-06-12 14:19:10 -070068import android.util.Log;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070069import android.util.Slog;
70import android.util.SparseArray;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080071import android.util.SparseBooleanArray;
Amith Yamasani920ace02012-09-20 22:15:37 -070072import android.util.TimeUtils;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070073import android.util.Xml;
74
Makoto Onuki068c54a2015-10-13 14:34:03 -070075import com.android.internal.annotations.GuardedBy;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070076import com.android.internal.annotations.VisibleForTesting;
Jason Monk62062992014-05-06 09:55:28 -040077import com.android.internal.app.IAppOpsService;
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -080078import com.android.internal.logging.MetricsLogger;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080079import com.android.internal.util.FastXmlSerializer;
Makoto Onuki068c54a2015-10-13 14:34:03 -070080import com.android.internal.util.Preconditions;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070081import com.android.internal.util.XmlUtils;
Clara Bayarri10ad84a2015-12-01 17:38:05 +000082import com.android.internal.widget.LockPatternUtils;
Amith Yamasani515d4062015-09-28 11:30:06 -070083import com.android.server.LocalServices;
Jeff Sharkey47f71082016-02-01 17:03:54 -070084
85import libcore.io.IoUtils;
86import libcore.util.Objects;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080087
88import org.xmlpull.v1.XmlPullParser;
89import org.xmlpull.v1.XmlPullParserException;
90import org.xmlpull.v1.XmlSerializer;
91
Amith Yamasani4b2e9342011-03-31 12:38:53 -070092import java.io.BufferedOutputStream;
93import java.io.File;
Amith Yamasani920ace02012-09-20 22:15:37 -070094import java.io.FileDescriptor;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070095import java.io.FileInputStream;
Amith Yamasanib8151ec2012-04-18 18:02:48 -070096import java.io.FileNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070097import java.io.FileOutputStream;
98import java.io.IOException;
Amith Yamasani920ace02012-09-20 22:15:37 -070099import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100100import java.nio.charset.StandardCharsets;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700101import java.util.ArrayList;
102import java.util.List;
103
Makoto Onuki068c54a2015-10-13 14:34:03 -0700104/**
105 * Service for {@link UserManager}.
106 *
107 * Method naming convention:
Fyodor Kupolov82402752015-10-28 14:54:51 -0700108 * <ul>
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800109 * <li> Methods suffixed with "LP" should be called within the {@link #mPackagesLock} lock.
Fyodor Kupolov82402752015-10-28 14:54:51 -0700110 * <li> Methods suffixed with "LR" should be called within the {@link #mRestrictionsLock} lock.
111 * <li> Methods suffixed with "LU" should be called within the {@link #mUsersLock} lock.
112 * </ul>
Makoto Onuki068c54a2015-10-13 14:34:03 -0700113 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700114public class UserManagerService extends IUserManager.Stub {
Amith Yamasani2a003292012-08-14 18:25:45 -0700115 private static final String LOG_TAG = "UserManagerService";
Makoto Onuki81c61ea2016-01-22 11:22:26 -0800116 static final boolean DBG = false; // DO NOT SUBMIT WITH TRUE
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800117 private static final boolean DBG_WITH_STACKTRACE = false; // DO NOT SUBMIT WITH TRUE
Amith Yamasani16389312012-10-17 21:20:14 -0700118
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700119 private static final String TAG_NAME = "name";
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800120 private static final String TAG_ACCOUNT = "account";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700121 private static final String ATTR_FLAGS = "flags";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700122 private static final String ATTR_ICON_PATH = "icon";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700123 private static final String ATTR_ID = "id";
Amith Yamasani920ace02012-09-20 22:15:37 -0700124 private static final String ATTR_CREATION_TIME = "created";
125 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -0600126 private static final String ATTR_LAST_LOGGED_IN_FINGERPRINT = "lastLoggedInFingerprint";
Amith Yamasani2a003292012-08-14 18:25:45 -0700127 private static final String ATTR_SERIAL_NO = "serialNumber";
128 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700129 private static final String ATTR_PARTIAL = "partial";
Adam Lesinskieddeb492014-09-08 17:50:03 -0700130 private static final String ATTR_GUEST_TO_REMOVE = "guestToRemove";
Amith Yamasani6f34b412012-10-22 18:19:27 -0700131 private static final String ATTR_USER_VERSION = "version";
Kenny Guy2a764942014-04-02 13:29:20 +0100132 private static final String ATTR_PROFILE_GROUP_ID = "profileGroupId";
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700133 private static final String ATTR_RESTRICTED_PROFILE_PARENT_ID = "restrictedProfileParentId";
Amith Yamasani12747872015-12-07 14:19:49 -0800134 private static final String ATTR_SEED_ACCOUNT_NAME = "seedAccountName";
135 private static final String ATTR_SEED_ACCOUNT_TYPE = "seedAccountType";
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530136 private static final String TAG_GUEST_RESTRICTIONS = "guestRestrictions";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700137 private static final String TAG_USERS = "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700138 private static final String TAG_USER = "user";
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800139 private static final String TAG_RESTRICTIONS = "restrictions";
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800140 private static final String TAG_DEVICE_POLICY_RESTRICTIONS = "device_policy_restrictions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800141 private static final String TAG_ENTRY = "entry";
142 private static final String TAG_VALUE = "value";
Amith Yamasani12747872015-12-07 14:19:49 -0800143 private static final String TAG_SEED_ACCOUNT_OPTIONS = "seedAccountOptions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800144 private static final String ATTR_KEY = "key";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700145 private static final String ATTR_VALUE_TYPE = "type";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800146 private static final String ATTR_MULTIPLE = "m";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700147
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700148 private static final String ATTR_TYPE_STRING_ARRAY = "sa";
149 private static final String ATTR_TYPE_STRING = "s";
150 private static final String ATTR_TYPE_BOOLEAN = "b";
Amith Yamasani5b5aa402014-06-01 20:10:14 -0700151 private static final String ATTR_TYPE_INTEGER = "i";
Fyodor Kupolov262f9952015-03-23 18:55:11 -0700152 private static final String ATTR_TYPE_BUNDLE = "B";
153 private static final String ATTR_TYPE_BUNDLE_ARRAY = "BA";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700154
Amith Yamasani0b285492011-04-14 17:35:23 -0700155 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700156 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700157 private static final String USER_PHOTO_FILENAME = "photo.png";
Adrian Roos1bdff912015-02-17 15:51:35 +0100158 private static final String USER_PHOTO_FILENAME_TMP = USER_PHOTO_FILENAME + ".tmp";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700159
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800160 private static final String RESTRICTIONS_FILE_PREFIX = "res_";
Amith Yamasanifc95e702013-09-26 13:20:17 -0700161 private static final String XML_SUFFIX = ".xml";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800162
Amith Yamasani634cf312012-10-04 17:34:21 -0700163 private static final int MIN_USER_ID = 10;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700164 // We need to keep process uid within Integer.MAX_VALUE.
165 private static final int MAX_USER_ID = Integer.MAX_VALUE / UserHandle.PER_USER_RANGE;
Amith Yamasani634cf312012-10-04 17:34:21 -0700166
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700167 private static final int USER_VERSION = 6;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700168
Amith Yamasani920ace02012-09-20 22:15:37 -0700169 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
170
Nicolas Prevotb8186812015-08-06 15:00:03 +0100171 // Maximum number of managed profiles permitted per user is 1. This cannot be increased
Amith Yamasani95ab7842014-08-11 17:09:26 -0700172 // without first making sure that the rest of the framework is prepared for it.
173 private static final int MAX_MANAGED_PROFILES = 1;
174
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800175 static final int WRITE_USER_MSG = 1;
176 static final int WRITE_USER_DELAY = 2*1000; // 2 seconds
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530177
Jeff Sharkey6dce4962015-07-03 18:08:41 -0700178 private static final String XATTR_SERIAL = "user.serial";
179
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -0800180 // Tron counters
181 private static final String TRON_GUEST_CREATED = "users_guest_created";
182 private static final String TRON_USER_CREATED = "users_user_created";
183
Dianne Hackborn4428e172012-08-24 17:43:05 -0700184 private final Context mContext;
185 private final PackageManagerService mPm;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700186 private final Object mPackagesLock;
Fyodor Kupolov82402752015-10-28 14:54:51 -0700187 // Short-term lock for internal state, when interaction/sync with PM is not required
188 private final Object mUsersLock = new Object();
189 private final Object mRestrictionsLock = new Object();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700190
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800191 private final Handler mHandler;
192
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700193 private final File mUsersDir;
194 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700195
Svet Ganov9cea80cd2016-02-16 11:47:00 -0800196 private static final IBinder mUserRestriconToken = new Binder();
197
Makoto Onuki068c54a2015-10-13 14:34:03 -0700198 /**
Amith Yamasani12747872015-12-07 14:19:49 -0800199 * User-related information that is used for persisting to flash. Only UserInfo is
200 * directly exposed to other system apps.
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800201 */
Amith Yamasani12747872015-12-07 14:19:49 -0800202 private static class UserData {
203 // Basic user information and properties
204 UserInfo info;
205 // Account name used when there is a strong association between a user and an account
206 String account;
207 // Account information for seeding into a newly created user. This could also be
208 // used for login validation for an existing user, for updating their credentials.
209 // In the latter case, data may not need to be persisted as it is only valid for the
210 // current login session.
211 String seedAccountName;
212 String seedAccountType;
213 PersistableBundle seedAccountOptions;
214 // Whether to perist the seed account information to be available after a boot
215 boolean persistSeedData;
216
217 void clearSeedAccountData() {
218 seedAccountName = null;
219 seedAccountType = null;
220 seedAccountOptions = null;
221 persistSeedData = false;
222 }
223 }
224
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800225 @GuardedBy("mUsersLock")
Amith Yamasani12747872015-12-07 14:19:49 -0800226 private final SparseArray<UserData> mUsers = new SparseArray<>();
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800227
228 /**
Makoto Onuki068c54a2015-10-13 14:34:03 -0700229 * User restrictions set via UserManager. This doesn't include restrictions set by
230 * device owner / profile owners.
231 *
232 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
233 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
234 * maybe shared between {@link #mBaseUserRestrictions} and
235 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
236 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700237 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700238 */
239 @GuardedBy("mRestrictionsLock")
240 private final SparseArray<Bundle> mBaseUserRestrictions = new SparseArray<>();
241
242 /**
243 * Cached user restrictions that are in effect -- i.e. {@link #mBaseUserRestrictions} combined
244 * with device / profile owner restrictions. We'll initialize it lazily; use
245 * {@link #getEffectiveUserRestrictions} to access it.
246 *
247 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
248 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
249 * maybe shared between {@link #mBaseUserRestrictions} and
250 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
251 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700252 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700253 */
254 @GuardedBy("mRestrictionsLock")
255 private final SparseArray<Bundle> mCachedEffectiveUserRestrictions = new SparseArray<>();
256
Makoto Onuki4f160732015-10-27 17:15:38 -0700257 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800258 * User restrictions that have already been applied in
259 * {@link #updateUserRestrictionsInternalLR(Bundle, int)}. We use it to detect restrictions
260 * that have changed since the last
261 * {@link #updateUserRestrictionsInternalLR(Bundle, int)} call.
Makoto Onuki4f160732015-10-27 17:15:38 -0700262 */
263 @GuardedBy("mRestrictionsLock")
264 private final SparseArray<Bundle> mAppliedUserRestrictions = new SparseArray<>();
265
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800266 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800267 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
268 * that should be applied to all users, including guests.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800269 */
270 @GuardedBy("mRestrictionsLock")
271 private Bundle mDevicePolicyGlobalUserRestrictions;
272
273 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800274 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
275 * for each user.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800276 */
277 @GuardedBy("mRestrictionsLock")
278 private final SparseArray<Bundle> mDevicePolicyLocalUserRestrictions = new SparseArray<>();
279
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800280 @GuardedBy("mGuestRestrictions")
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530281 private final Bundle mGuestRestrictions = new Bundle();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800282
283 /**
284 * Set of user IDs being actively removed. Removed IDs linger in this set
285 * for several seconds to work around a VFS caching issue.
286 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700287 @GuardedBy("mUsersLock")
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800288 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700289
Fyodor Kupolov82402752015-10-28 14:54:51 -0700290 @GuardedBy("mUsersLock")
Amith Yamasani0b285492011-04-14 17:35:23 -0700291 private int[] mUserIds;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800292 @GuardedBy("mPackagesLock")
Amith Yamasani2a003292012-08-14 18:25:45 -0700293 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700294 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700295
Jason Monk62062992014-05-06 09:55:28 -0400296 private IAppOpsService mAppOpsService;
297
Makoto Onuki068c54a2015-10-13 14:34:03 -0700298 private final LocalService mLocalService;
299
Makoto Onukie7927da2015-11-25 10:05:17 -0800300 @GuardedBy("mUsersLock")
301 private boolean mIsDeviceManaged;
302
303 @GuardedBy("mUsersLock")
304 private final SparseBooleanArray mIsUserManaged = new SparseBooleanArray();
305
Makoto Onukid45a4a22015-11-02 17:17:38 -0800306 @GuardedBy("mUserRestrictionsListeners")
307 private final ArrayList<UserRestrictionsListener> mUserRestrictionsListeners =
308 new ArrayList<>();
309
Clara Bayarria1771112015-12-18 16:29:18 +0000310 private final LockPatternUtils mLockPatternUtils;
311
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +0100312 /**
313 * Whether all users should be created ephemeral.
314 */
315 @GuardedBy("mUsersLock")
316 private boolean mForceEphemeralUsers;
317
Amith Yamasani258848d2012-08-10 17:06:33 -0700318 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700319
Dianne Hackborn4428e172012-08-24 17:43:05 -0700320 public static UserManagerService getInstance() {
321 synchronized (UserManagerService.class) {
322 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700323 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700324 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700325
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800326 @VisibleForTesting
327 UserManagerService(File dataDir) {
328 this(null, null, new Object(), dataDir);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700329 }
330
Dianne Hackborn4428e172012-08-24 17:43:05 -0700331 /**
332 * Called by package manager to create the service. This is closely
333 * associated with the package manager, and the given lock is the
334 * package manager's own lock.
335 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800336 UserManagerService(Context context, PackageManagerService pm, Object packagesLock) {
337 this(context, pm, packagesLock, Environment.getDataDirectory());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700338 }
339
Dianne Hackborn4428e172012-08-24 17:43:05 -0700340 private UserManagerService(Context context, PackageManagerService pm,
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800341 Object packagesLock, File dataDir) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700342 mContext = context;
343 mPm = pm;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700344 mPackagesLock = packagesLock;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800345 mHandler = new MainHandler();
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800346 synchronized (mPackagesLock) {
347 mUsersDir = new File(dataDir, USER_INFO_DIR);
348 mUsersDir.mkdirs();
349 // Make zeroth user directory, for services to migrate their files to that location
350 File userZeroDir = new File(mUsersDir, String.valueOf(UserHandle.USER_SYSTEM));
351 userZeroDir.mkdirs();
352 FileUtils.setPermissions(mUsersDir.toString(),
353 FileUtils.S_IRWXU | FileUtils.S_IRWXG | FileUtils.S_IROTH | FileUtils.S_IXOTH,
354 -1, -1);
355 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
356 initDefaultGuestRestrictions();
357 readUserListLP();
358 sInstance = this;
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700359 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700360 mLocalService = new LocalService();
361 LocalServices.addService(UserManagerInternal.class, mLocalService);
Clara Bayarria1771112015-12-18 16:29:18 +0000362 mLockPatternUtils = new LockPatternUtils(mContext);
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700363 }
364
365 void systemReady() {
Lenka Trochtovac4dd0212015-11-18 12:22:06 +0100366 // Prune out any partially created, partially removed and ephemeral users.
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800367 ArrayList<UserInfo> partials = new ArrayList<>();
368 synchronized (mUsersLock) {
369 final int userSize = mUsers.size();
370 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800371 UserInfo ui = mUsers.valueAt(i).info;
Lenka Trochtovac4dd0212015-11-18 12:22:06 +0100372 if ((ui.partial || ui.guestToRemove || ui.isEphemeral()) && i != 0) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800373 partials.add(ui);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700374 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700375 }
Dianne Hackborn4428e172012-08-24 17:43:05 -0700376 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800377 final int partialsSize = partials.size();
378 for (int i = 0; i < partialsSize; i++) {
379 UserInfo ui = partials.get(i);
380 Slog.w(LOG_TAG, "Removing partially created user " + ui.id
381 + " (name=" + ui.name + ")");
382 removeUserState(ui.id);
383 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800384
Jason Monk62062992014-05-06 09:55:28 -0400385 mAppOpsService = IAppOpsService.Stub.asInterface(
386 ServiceManager.getService(Context.APP_OPS_SERVICE));
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800387
388 synchronized (mRestrictionsLock) {
389 applyUserRestrictionsLR(UserHandle.USER_SYSTEM);
Jason Monk62062992014-05-06 09:55:28 -0400390 }
Samuel Tand9453b82016-03-14 15:57:02 -0700391
392 UserInfo currentGuestUser = findCurrentGuestUser();
393 if (currentGuestUser != null && !hasUserRestriction(
394 UserManager.DISALLOW_CONFIG_WIFI, currentGuestUser.id)) {
395 // If a guest user currently exists, apply the DISALLOW_CONFIG_WIFI option
396 // to it, in case this guest was created in a previous version where this
397 // user restriction was not a default guest restriction.
398 setUserRestriction(UserManager.DISALLOW_CONFIG_WIFI, true, currentGuestUser.id);
399 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700400 }
401
402 @Override
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800403 public String getUserAccount(int userId) {
404 checkManageUserAndAcrossUsersFullPermission("get user account");
405 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800406 return mUsers.get(userId).account;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800407 }
408 }
409
410 @Override
411 public void setUserAccount(int userId, String accountName) {
412 checkManageUserAndAcrossUsersFullPermission("set user account");
Amith Yamasani12747872015-12-07 14:19:49 -0800413 UserData userToUpdate = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800414 synchronized (mPackagesLock) {
415 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800416 final UserData userData = mUsers.get(userId);
417 if (userData == null) {
418 Slog.e(LOG_TAG, "User not found for setting user account: u" + userId);
419 return;
420 }
421 String currentAccount = userData.account;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800422 if (!Objects.equal(currentAccount, accountName)) {
Amith Yamasani12747872015-12-07 14:19:49 -0800423 userData.account = accountName;
424 userToUpdate = userData;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800425 }
426 }
427
428 if (userToUpdate != null) {
429 writeUserLP(userToUpdate);
430 }
431 }
432 }
433
434 @Override
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700435 public UserInfo getPrimaryUser() {
436 checkManageUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700437 synchronized (mUsersLock) {
Amith Yamasani515d4062015-09-28 11:30:06 -0700438 final int userSize = mUsers.size();
439 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800440 UserInfo ui = mUsers.valueAt(i).info;
Xiaohui Chend3e9e182015-11-18 13:37:32 -0800441 if (ui.isPrimary() && !mRemovingUserIds.get(ui.id)) {
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700442 return ui;
443 }
444 }
445 }
446 return null;
447 }
448
449 @Override
Xiaohui Chen594f2082015-08-18 11:04:20 -0700450 public @NonNull List<UserInfo> getUsers(boolean excludeDying) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700451 checkManageUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700452 synchronized (mUsersLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700453 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasani515d4062015-09-28 11:30:06 -0700454 final int userSize = mUsers.size();
455 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800456 UserInfo ui = mUsers.valueAt(i).info;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700457 if (ui.partial) {
458 continue;
459 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800460 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Amith Yamasani6f48d6e2016-03-23 14:28:25 -0700461 users.add(userWithName(ui));
Amith Yamasani920ace02012-09-20 22:15:37 -0700462 }
Amith Yamasani13593602012-03-22 16:16:17 -0700463 }
464 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700465 }
Amith Yamasani13593602012-03-22 16:16:17 -0700466 }
467
Amith Yamasani258848d2012-08-10 17:06:33 -0700468 @Override
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100469 public List<UserInfo> getProfiles(int userId, boolean enabledOnly) {
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700470 boolean returnFullInfo = true;
Amith Yamasani4f582632014-02-19 14:31:52 -0800471 if (userId != UserHandle.getCallingUserId()) {
472 checkManageUsersPermission("getting profiles related to user " + userId);
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700473 } else {
474 returnFullInfo = hasManageUsersPermission();
Amith Yamasani4f582632014-02-19 14:31:52 -0800475 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700476 final long ident = Binder.clearCallingIdentity();
477 try {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700478 synchronized (mUsersLock) {
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700479 return getProfilesLU(userId, enabledOnly, returnFullInfo);
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100480 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700481 } finally {
482 Binder.restoreCallingIdentity(ident);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000483 }
484 }
485
Amith Yamasanibe465322014-04-24 13:45:17 -0700486 /** Assume permissions already checked and caller's identity cleared */
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700487 private List<UserInfo> getProfilesLU(int userId, boolean enabledOnly, boolean fullInfo) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700488 UserInfo user = getUserInfoLU(userId);
Amith Yamasanibe465322014-04-24 13:45:17 -0700489 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasanidda003f2014-08-28 18:06:51 -0700490 if (user == null) {
491 // Probably a dying user
492 return users;
493 }
Amith Yamasani515d4062015-09-28 11:30:06 -0700494 final int userSize = mUsers.size();
495 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800496 UserInfo profile = mUsers.valueAt(i).info;
Amith Yamasanibe465322014-04-24 13:45:17 -0700497 if (!isProfileOf(user, profile)) {
498 continue;
499 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100500 if (enabledOnly && !profile.isEnabled()) {
501 continue;
Amith Yamasanibe465322014-04-24 13:45:17 -0700502 }
Amith Yamasani70fcf0c2014-07-11 08:40:19 -0700503 if (mRemovingUserIds.get(profile.id)) {
504 continue;
505 }
Tony Mak80189cd2016-04-05 17:21:42 +0100506 if (profile.partial) {
507 continue;
508 }
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700509 UserInfo userInfo = userWithName(profile);
510 // If full info is not required - clear PII data to prevent 3P apps from reading it
511 if (!fullInfo) {
512 userInfo = new UserInfo(userInfo);
513 userInfo.name = null;
514 userInfo.iconPath = null;
515 }
516 users.add(userInfo);
Amith Yamasanibe465322014-04-24 13:45:17 -0700517 }
518 return users;
519 }
520
Jessica Hummelbe81c802014-04-22 15:49:22 +0100521 @Override
Andres Moralesc5548c02015-08-05 10:23:12 -0700522 public int getCredentialOwnerProfile(int userHandle) {
523 checkManageUsersPermission("get the credential owner");
Clara Bayarria1771112015-12-18 16:29:18 +0000524 if (!mLockPatternUtils.isSeparateProfileChallengeEnabled(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700525 synchronized (mUsersLock) {
526 UserInfo profileParent = getProfileParentLU(userHandle);
Andres Moralesc5548c02015-08-05 10:23:12 -0700527 if (profileParent != null) {
528 return profileParent.id;
529 }
530 }
531 }
532
533 return userHandle;
534 }
535
536 @Override
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700537 public boolean isSameProfileGroup(int userId, int otherUserId) {
538 if (userId == otherUserId) return true;
539 checkManageUsersPermission("check if in the same profile group");
540 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700541 return isSameProfileGroupLP(userId, otherUserId);
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700542 }
543 }
544
Fyodor Kupolov82402752015-10-28 14:54:51 -0700545 private boolean isSameProfileGroupLP(int userId, int otherUserId) {
546 synchronized (mUsersLock) {
547 UserInfo userInfo = getUserInfoLU(userId);
548 if (userInfo == null || userInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
549 return false;
550 }
551 UserInfo otherUserInfo = getUserInfoLU(otherUserId);
552 if (otherUserInfo == null
553 || otherUserInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
554 return false;
555 }
556 return userInfo.profileGroupId == otherUserInfo.profileGroupId;
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700557 }
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700558 }
559
560 @Override
Jessica Hummelbe81c802014-04-22 15:49:22 +0100561 public UserInfo getProfileParent(int userHandle) {
562 checkManageUsersPermission("get the profile parent");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700563 synchronized (mUsersLock) {
564 return getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700565 }
566 }
567
Fyodor Kupolov82402752015-10-28 14:54:51 -0700568 private UserInfo getProfileParentLU(int userHandle) {
569 UserInfo profile = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700570 if (profile == null) {
571 return null;
572 }
573 int parentUserId = profile.profileGroupId;
574 if (parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
575 return null;
576 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700577 return getUserInfoLU(parentUserId);
Jessica Hummelbe81c802014-04-22 15:49:22 +0100578 }
579 }
580
Fyodor Kupolov82402752015-10-28 14:54:51 -0700581 private static boolean isProfileOf(UserInfo user, UserInfo profile) {
Kenny Guy2a764942014-04-02 13:29:20 +0100582 return user.id == profile.id ||
583 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
584 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000585 }
586
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000587 private void broadcastProfileAvailabilityChanges(UserHandle profileHandle,
Rubin Xuf13c9802016-01-21 18:06:00 +0000588 UserHandle parentHandle, boolean inQuietMode) {
Rubin Xue95057a2016-04-01 16:49:25 +0100589 Intent intent = new Intent();
590 if (inQuietMode) {
591 intent.setAction(Intent.ACTION_MANAGED_PROFILE_UNAVAILABLE);
592 } else {
593 intent.setAction(Intent.ACTION_MANAGED_PROFILE_AVAILABLE);
594 }
Rubin Xuf13c9802016-01-21 18:06:00 +0000595 intent.putExtra(Intent.EXTRA_QUIET_MODE, inQuietMode);
596 intent.putExtra(Intent.EXTRA_USER, profileHandle);
597 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileHandle.getIdentifier());
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000598 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Rubin Xuf13c9802016-01-21 18:06:00 +0000599 mContext.sendBroadcastAsUser(intent, parentHandle);
Rubin Xue95057a2016-04-01 16:49:25 +0100600
601 //TODO: remove once Launcher3 is updated.
602 Intent oldIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_AVAILABILITY_CHANGED);
603 oldIntent.putExtra(Intent.EXTRA_QUIET_MODE, inQuietMode);
604 oldIntent.putExtra(Intent.EXTRA_USER, profileHandle);
605 oldIntent.putExtra(Intent.EXTRA_USER_HANDLE, profileHandle.getIdentifier());
606 oldIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
607 mContext.sendBroadcastAsUser(oldIntent, parentHandle);
608
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000609 }
610
611 @Override
612 public void setQuietModeEnabled(int userHandle, boolean enableQuietMode) {
613 checkManageUsersPermission("silence profile");
614 boolean changed = false;
615 UserInfo profile, parent;
616 synchronized (mPackagesLock) {
617 synchronized (mUsersLock) {
618 profile = getUserInfoLU(userHandle);
619 parent = getProfileParentLU(userHandle);
620
621 }
622 if (profile == null || !profile.isManagedProfile()) {
623 throw new IllegalArgumentException("User " + userHandle + " is not a profile");
624 }
625 if (profile.isQuietModeEnabled() != enableQuietMode) {
626 profile.flags ^= UserInfo.FLAG_QUIET_MODE;
Amith Yamasani12747872015-12-07 14:19:49 -0800627 writeUserLP(getUserDataLU(profile.id));
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000628 changed = true;
629 }
630 }
631 if (changed) {
Rubin Xuf13c9802016-01-21 18:06:00 +0000632 long identity = Binder.clearCallingIdentity();
633 try {
634 if (enableQuietMode) {
635 ActivityManagerNative.getDefault().stopUser(userHandle, /* force */true, null);
636 } else {
637 ActivityManagerNative.getDefault().startUserInBackground(userHandle);
638 }
639 } catch (RemoteException e) {
640 Slog.e(LOG_TAG, "fail to start/stop user for quiet mode", e);
641 } finally {
642 Binder.restoreCallingIdentity(identity);
643 }
644
645 broadcastProfileAvailabilityChanges(profile.getUserHandle(), parent.getUserHandle(),
646 enableQuietMode);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000647 }
648 }
649
650 @Override
651 public boolean isQuietModeEnabled(int userHandle) {
652 synchronized (mPackagesLock) {
653 UserInfo info;
654 synchronized (mUsersLock) {
655 info = getUserInfoLU(userHandle);
656 }
657 if (info == null || !info.isManagedProfile()) {
Rubin Xuf13c9802016-01-21 18:06:00 +0000658 return false;
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000659 }
660 return info.isQuietModeEnabled();
661 }
662 }
663
Kenny Guya52dc3e2014-02-11 15:33:14 +0000664 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100665 public void setUserEnabled(int userId) {
666 checkManageUsersPermission("enable user");
667 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700668 UserInfo info;
669 synchronized (mUsersLock) {
670 info = getUserInfoLU(userId);
671 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100672 if (info != null && !info.isEnabled()) {
673 info.flags ^= UserInfo.FLAG_DISABLED;
Amith Yamasani12747872015-12-07 14:19:49 -0800674 writeUserLP(getUserDataLU(info.id));
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100675 }
676 }
677 }
678
679 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700680 public UserInfo getUserInfo(int userId) {
Tony Mak8673b282016-03-21 21:10:59 +0000681 checkManageUsersPermission("query user");
682 synchronized (mUsersLock) {
Amith Yamasani6f48d6e2016-03-23 14:28:25 -0700683 return userWithName(getUserInfoLU(userId));
684 }
685 }
686
687 /**
688 * Returns a UserInfo object with the name filled in, for Owner, or the original
689 * if the name is already set.
690 */
691 private UserInfo userWithName(UserInfo orig) {
692 if (orig != null && orig.name == null && orig.id == UserHandle.USER_SYSTEM) {
693 UserInfo withName = new UserInfo(orig);
694 withName.name = getOwnerName();
695 return withName;
696 } else {
697 return orig;
Tony Mak8673b282016-03-21 21:10:59 +0000698 }
699 }
700
701 @Override
702 public boolean isManagedProfile(int userId) {
Tony Makb531d082016-03-16 14:49:52 +0000703 int callingUserId = UserHandle.getCallingUserId();
704 if (callingUserId != userId && !hasManageUsersPermission()) {
705 synchronized (mPackagesLock) {
706 if (!isSameProfileGroupLP(callingUserId, userId)) {
707 throw new SecurityException(
Tony Mak8673b282016-03-21 21:10:59 +0000708 "You need MANAGE_USERS permission to: check if specified user a " +
709 "managed profile outside your profile group");
Tony Makb531d082016-03-16 14:49:52 +0000710 }
711 }
Tony Mak4dc008c2016-03-16 10:46:49 +0000712 }
Fyodor Kupolov82402752015-10-28 14:54:51 -0700713 synchronized (mUsersLock) {
Tony Mak8673b282016-03-21 21:10:59 +0000714 UserInfo userInfo = getUserInfoLU(userId);
715 return userInfo != null && userInfo.isManagedProfile();
Amith Yamasani13593602012-03-22 16:16:17 -0700716 }
717 }
718
Amith Yamasani71e6c692013-03-24 17:39:28 -0700719 @Override
720 public boolean isRestricted() {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700721 synchronized (mUsersLock) {
722 return getUserInfoLU(UserHandle.getCallingUserId()).isRestricted();
Amith Yamasani71e6c692013-03-24 17:39:28 -0700723 }
724 }
725
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700726 @Override
727 public boolean canHaveRestrictedProfile(int userId) {
728 checkManageUsersPermission("canHaveRestrictedProfile");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700729 synchronized (mUsersLock) {
730 final UserInfo userInfo = getUserInfoLU(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700731 if (userInfo == null || !userInfo.canHaveProfile()) {
732 return false;
733 }
734 if (!userInfo.isAdmin()) {
735 return false;
736 }
Makoto Onukie7927da2015-11-25 10:05:17 -0800737 // restricted profile can be created if there is no DO set and the admin user has no PO;
738 return !mIsDeviceManaged && !mIsUserManaged.get(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700739 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700740 }
741
Amith Yamasani195263742012-08-21 15:40:12 -0700742 /*
743 * Should be locked on mUsers before calling this.
744 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700745 private UserInfo getUserInfoLU(int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -0800746 final UserData userData = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -0700747 // If it is partial and not in the process of being removed, return as unknown user.
Amith Yamasani12747872015-12-07 14:19:49 -0800748 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700749 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
750 return null;
751 }
Amith Yamasani12747872015-12-07 14:19:49 -0800752 return userData != null ? userData.info : null;
753 }
754
755 private UserData getUserDataLU(int userId) {
756 final UserData userData = mUsers.get(userId);
757 // If it is partial and not in the process of being removed, return as unknown user.
758 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
759 return null;
760 }
761 return userData;
Amith Yamasani195263742012-08-21 15:40:12 -0700762 }
763
Fyodor Kupolov82402752015-10-28 14:54:51 -0700764 /**
765 * Obtains {@link #mUsersLock} and return UserInfo from mUsers.
766 * <p>No permissions checking or any addition checks are made</p>
767 */
768 private UserInfo getUserInfoNoChecks(int userId) {
769 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800770 final UserData userData = mUsers.get(userId);
771 return userData != null ? userData.info : null;
772 }
773 }
774
775 /**
776 * Obtains {@link #mUsersLock} and return UserData from mUsers.
777 * <p>No permissions checking or any addition checks are made</p>
778 */
779 private UserData getUserDataNoChecks(int userId) {
780 synchronized (mUsersLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700781 return mUsers.get(userId);
782 }
783 }
784
Amith Yamasani236b2b52015-08-18 14:32:14 -0700785 /** Called by PackageManagerService */
Amith Yamasani13593602012-03-22 16:16:17 -0700786 public boolean exists(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700787 return getUserInfoNoChecks(userId) != null;
Amith Yamasani13593602012-03-22 16:16:17 -0700788 }
789
Amith Yamasani258848d2012-08-10 17:06:33 -0700790 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700791 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700792 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700793 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700794 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800795 UserData userData = getUserDataNoChecks(userId);
796 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700797 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
798 return;
799 }
Amith Yamasani12747872015-12-07 14:19:49 -0800800 if (name != null && !name.equals(userData.info.name)) {
801 userData.info.name = name;
802 writeUserLP(userData);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700803 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -0700804 }
805 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700806 if (changed) {
807 sendUserInfoChangedBroadcast(userId);
808 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700809 }
810
Amith Yamasani258848d2012-08-10 17:06:33 -0700811 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700812 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700813 checkManageUsersPermission("update users");
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +0100814 if (hasUserRestriction(UserManager.DISALLOW_SET_USER_ICON, userId)) {
815 Log.w(LOG_TAG, "Cannot set user icon. DISALLOW_SET_USER_ICON is enabled.");
816 return;
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700817 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +0100818 mLocalService.setUserIcon(userId, bitmap);
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700819 }
820
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +0100821
822
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700823 private void sendUserInfoChangedBroadcast(int userId) {
824 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
825 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
826 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -0700827 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700828 }
829
Amith Yamasani258848d2012-08-10 17:06:33 -0700830 @Override
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +0100831 public ParcelFileDescriptor getUserIcon(int targetUserId) {
Adrian Roos1bdff912015-02-17 15:51:35 +0100832 String iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700833 synchronized (mPackagesLock) {
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +0100834 UserInfo targetUserInfo = getUserInfoNoChecks(targetUserId);
835 if (targetUserInfo == null || targetUserInfo.partial) {
836 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + targetUserId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700837 return null;
838 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +0100839
840 final int callingUserId = UserHandle.getCallingUserId();
841 final int callingGroupId = getUserInfoNoChecks(callingUserId).profileGroupId;
842 final int targetGroupId = targetUserInfo.profileGroupId;
843 final boolean sameGroup = (callingGroupId != UserInfo.NO_PROFILE_GROUP_ID
844 && callingGroupId == targetGroupId);
845 if ((callingUserId != targetUserId) && !sameGroup) {
Nicolas Prevot88cc3462014-05-14 14:51:48 +0100846 checkManageUsersPermission("get the icon of a user who is not related");
847 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +0100848
849 if (targetUserInfo.iconPath == null) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700850 return null;
851 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +0100852 iconPath = targetUserInfo.iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700853 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100854
855 try {
856 return ParcelFileDescriptor.open(
857 new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
858 } catch (FileNotFoundException e) {
859 Log.e(LOG_TAG, "Couldn't find icon file", e);
860 }
861 return null;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700862 }
863
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700864 public void makeInitialized(int userId) {
865 checkManageUsersPermission("makeInitialized");
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800866 boolean scheduleWriteUser = false;
Amith Yamasani12747872015-12-07 14:19:49 -0800867 UserData userData;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800868 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800869 userData = mUsers.get(userId);
870 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700871 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800872 return;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700873 }
Amith Yamasani12747872015-12-07 14:19:49 -0800874 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
875 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800876 scheduleWriteUser = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700877 }
878 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800879 if (scheduleWriteUser) {
Amith Yamasani12747872015-12-07 14:19:49 -0800880 scheduleWriteUser(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800881 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700882 }
883
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700884 /**
885 * If default guest restrictions haven't been initialized yet, add the basic
886 * restrictions.
887 */
888 private void initDefaultGuestRestrictions() {
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800889 synchronized (mGuestRestrictions) {
890 if (mGuestRestrictions.isEmpty()) {
Samuel Tand9453b82016-03-14 15:57:02 -0700891 mGuestRestrictions.putBoolean(UserManager.DISALLOW_CONFIG_WIFI, true);
Fyodor Kupolove04462c2015-11-30 15:02:53 -0800892 mGuestRestrictions.putBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, true);
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800893 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
894 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
895 }
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700896 }
897 }
898
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800899 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530900 public Bundle getDefaultGuestRestrictions() {
901 checkManageUsersPermission("getDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800902 synchronized (mGuestRestrictions) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530903 return new Bundle(mGuestRestrictions);
904 }
905 }
906
907 @Override
908 public void setDefaultGuestRestrictions(Bundle restrictions) {
909 checkManageUsersPermission("setDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800910 synchronized (mGuestRestrictions) {
911 mGuestRestrictions.clear();
912 mGuestRestrictions.putAll(restrictions);
913 }
914 synchronized (mPackagesLock) {
915 writeUserListLP();
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530916 }
917 }
918
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800919 /**
920 * See {@link UserManagerInternal#setDevicePolicyUserRestrictions(int, Bundle, Bundle)}
921 */
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800922 void setDevicePolicyUserRestrictionsInner(int userId, @NonNull Bundle local,
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800923 @Nullable Bundle global) {
924 Preconditions.checkNotNull(local);
925 boolean globalChanged = false;
926 boolean localChanged;
927 synchronized (mRestrictionsLock) {
928 if (global != null) {
929 // Update global.
930 globalChanged = !UserRestrictionsUtils.areEqual(
931 mDevicePolicyGlobalUserRestrictions, global);
932 if (globalChanged) {
933 mDevicePolicyGlobalUserRestrictions = global;
934 }
935 }
936 {
937 // Update local.
938 final Bundle prev = mDevicePolicyLocalUserRestrictions.get(userId);
939 localChanged = !UserRestrictionsUtils.areEqual(prev, local);
940 if (localChanged) {
941 mDevicePolicyLocalUserRestrictions.put(userId, local);
942 }
943 }
944 }
945 if (DBG) {
946 Log.d(LOG_TAG, "setDevicePolicyUserRestrictions: userId=" + userId
947 + " global=" + global + (globalChanged ? " (changed)" : "")
948 + " local=" + local + (localChanged ? " (changed)" : "")
949 );
950 }
951 // Don't call them within the mRestrictionsLock.
952 synchronized (mPackagesLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800953 if (localChanged) {
Amith Yamasani12747872015-12-07 14:19:49 -0800954 writeUserLP(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800955 }
Jeff Sharkeycd575992016-03-29 14:12:49 -0600956 if (globalChanged) {
957 writeUserListLP();
958 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800959 }
960
961 synchronized (mRestrictionsLock) {
962 if (globalChanged) {
963 applyUserRestrictionsForAllUsersLR();
964 } else if (localChanged) {
965 applyUserRestrictionsLR(userId);
966 }
967 }
968 }
969
Makoto Onuki068c54a2015-10-13 14:34:03 -0700970 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -0700971 private Bundle computeEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800972 final Bundle baseRestrictions =
973 UserRestrictionsUtils.nonNull(mBaseUserRestrictions.get(userId));
974 final Bundle global = mDevicePolicyGlobalUserRestrictions;
975 final Bundle local = mDevicePolicyLocalUserRestrictions.get(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700976
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800977 if (UserRestrictionsUtils.isEmpty(global) && UserRestrictionsUtils.isEmpty(local)) {
978 // Common case first.
979 return baseRestrictions;
Makoto Onuki068c54a2015-10-13 14:34:03 -0700980 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800981 final Bundle effective = UserRestrictionsUtils.clone(baseRestrictions);
982 UserRestrictionsUtils.merge(effective, global);
983 UserRestrictionsUtils.merge(effective, local);
984
Makoto Onuki068c54a2015-10-13 14:34:03 -0700985 return effective;
986 }
987
988 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -0700989 private void invalidateEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki068c54a2015-10-13 14:34:03 -0700990 if (DBG) {
991 Log.d(LOG_TAG, "invalidateEffectiveUserRestrictions userId=" + userId);
992 }
993 mCachedEffectiveUserRestrictions.remove(userId);
994 }
995
996 private Bundle getEffectiveUserRestrictions(int userId) {
997 synchronized (mRestrictionsLock) {
998 Bundle restrictions = mCachedEffectiveUserRestrictions.get(userId);
999 if (restrictions == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001000 restrictions = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001001 mCachedEffectiveUserRestrictions.put(userId, restrictions);
1002 }
1003 return restrictions;
Amith Yamasani8cd28b52014-06-08 17:54:27 -07001004 }
1005 }
1006
Makoto Onuki068c54a2015-10-13 14:34:03 -07001007 /** @return a specific user restriction that's in effect currently. */
1008 @Override
1009 public boolean hasUserRestriction(String restrictionKey, int userId) {
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001010 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1011 return false;
1012 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001013 Bundle restrictions = getEffectiveUserRestrictions(userId);
1014 return restrictions != null && restrictions.getBoolean(restrictionKey);
1015 }
1016
1017 /**
1018 * @return UserRestrictions that are in effect currently. This always returns a new
1019 * {@link Bundle}.
1020 */
Amith Yamasani8cd28b52014-06-08 17:54:27 -07001021 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001022 public Bundle getUserRestrictions(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001023 return UserRestrictionsUtils.clone(getEffectiveUserRestrictions(userId));
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001024 }
1025
1026 @Override
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +00001027 public boolean hasBaseUserRestriction(String restrictionKey, int userId) {
1028 checkManageUsersPermission("hasBaseUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001029 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1030 return false;
1031 }
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +00001032 synchronized (mRestrictionsLock) {
1033 Bundle bundle = mBaseUserRestrictions.get(userId);
1034 return (bundle != null && bundle.getBoolean(restrictionKey, false));
1035 }
1036 }
1037
1038 @Override
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001039 public void setUserRestriction(String key, boolean value, int userId) {
Fyodor Kupolovd4b26042015-07-27 14:30:59 -07001040 checkManageUsersPermission("setUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001041 if (!UserRestrictionsUtils.isValidRestriction(key)) {
1042 return;
1043 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001044 synchronized (mRestrictionsLock) {
1045 // Note we can't modify Bundles stored in mBaseUserRestrictions directly, so create
1046 // a copy.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001047 final Bundle newRestrictions = UserRestrictionsUtils.clone(
1048 mBaseUserRestrictions.get(userId));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001049 newRestrictions.putBoolean(key, value);
1050
Fyodor Kupolov82402752015-10-28 14:54:51 -07001051 updateUserRestrictionsInternalLR(newRestrictions, userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001052 }
1053 }
1054
Makoto Onuki068c54a2015-10-13 14:34:03 -07001055 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001056 * Optionally updating user restrictions, calculate the effective user restrictions and also
1057 * propagate to other services and system settings.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001058 *
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001059 * @param newRestrictions User restrictions to set.
1060 * If null, will not update user restrictions and only does the propagation.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001061 * @param userId target user ID.
1062 */
1063 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001064 private void updateUserRestrictionsInternalLR(
Makoto Onuki068c54a2015-10-13 14:34:03 -07001065 @Nullable Bundle newRestrictions, int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001066
1067 final Bundle prevAppliedRestrictions = UserRestrictionsUtils.nonNull(
1068 mAppliedUserRestrictions.get(userId));
1069
1070 // Update base restrictions.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001071 if (newRestrictions != null) {
1072 // If newRestrictions == the current one, it's probably a bug.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001073 final Bundle prevBaseRestrictions = mBaseUserRestrictions.get(userId);
1074
1075 Preconditions.checkState(prevBaseRestrictions != newRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001076 Preconditions.checkState(mCachedEffectiveUserRestrictions.get(userId)
1077 != newRestrictions);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001078
1079 if (!UserRestrictionsUtils.areEqual(prevBaseRestrictions, newRestrictions)) {
1080 mBaseUserRestrictions.put(userId, newRestrictions);
Amith Yamasani12747872015-12-07 14:19:49 -08001081 scheduleWriteUser(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001082 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001083 }
1084
Fyodor Kupolov82402752015-10-28 14:54:51 -07001085 final Bundle effective = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001086
Makoto Onuki759a7632015-10-28 16:43:10 -07001087 mCachedEffectiveUserRestrictions.put(userId, effective);
1088
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001089 // Apply the new restrictions.
Makoto Onuki4f160732015-10-27 17:15:38 -07001090 if (DBG) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001091 debug("Applying user restrictions: userId=" + userId
1092 + " new=" + effective + " prev=" + prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001093 }
1094
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001095 if (mAppOpsService != null) { // We skip it until system-ready.
1096 final long token = Binder.clearCallingIdentity();
1097 try {
Svet Ganov9cea80cd2016-02-16 11:47:00 -08001098 mAppOpsService.setUserRestrictions(effective, mUserRestriconToken, userId);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001099 } catch (RemoteException e) {
1100 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
1101 } finally {
1102 Binder.restoreCallingIdentity(token);
1103 }
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001104 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001105
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001106 propagateUserRestrictionsLR(userId, effective, prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001107
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001108 mAppliedUserRestrictions.put(userId, new Bundle(effective));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001109 }
1110
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001111 private void propagateUserRestrictionsLR(final int userId,
Makoto Onukid45a4a22015-11-02 17:17:38 -08001112 Bundle newRestrictions, Bundle prevRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001113 // Note this method doesn't touch any state, meaning it doesn't require mRestrictionsLock
1114 // actually, but we still need some kind of synchronization otherwise we might end up
1115 // calling listeners out-of-order, thus "LR".
1116
1117 if (UserRestrictionsUtils.areEqual(newRestrictions, prevRestrictions)) {
1118 return;
1119 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08001120
1121 final Bundle newRestrictionsFinal = new Bundle(newRestrictions);
1122 final Bundle prevRestrictionsFinal = new Bundle(prevRestrictions);
1123
1124 mHandler.post(new Runnable() {
1125 @Override
1126 public void run() {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07001127 UserRestrictionsUtils.applyUserRestrictions(
1128 mContext, userId, newRestrictionsFinal, prevRestrictionsFinal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001129
Makoto Onukid45a4a22015-11-02 17:17:38 -08001130 final UserRestrictionsListener[] listeners;
1131 synchronized (mUserRestrictionsListeners) {
1132 listeners = new UserRestrictionsListener[mUserRestrictionsListeners.size()];
1133 mUserRestrictionsListeners.toArray(listeners);
1134 }
1135 for (int i = 0; i < listeners.length; i++) {
1136 listeners[i].onUserRestrictionsChanged(userId,
1137 newRestrictionsFinal, prevRestrictionsFinal);
1138 }
1139 }
1140 });
1141 }
1142
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001143 // Package private for the inner class.
1144 void applyUserRestrictionsLR(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001145 updateUserRestrictionsInternalLR(null, userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001146 }
1147
1148 @GuardedBy("mRestrictionsLock")
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001149 // Package private for the inner class.
1150 void applyUserRestrictionsForAllUsersLR() {
1151 if (DBG) {
1152 debug("applyUserRestrictionsForAllUsersLR");
1153 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001154 // First, invalidate all cached values.
Makoto Onuki4f160732015-10-27 17:15:38 -07001155 mCachedEffectiveUserRestrictions.clear();
1156
Makoto Onuki068c54a2015-10-13 14:34:03 -07001157 // We don't want to call into ActivityManagerNative while taking a lock, so we'll call
1158 // it on a handler.
1159 final Runnable r = new Runnable() {
1160 @Override
1161 public void run() {
1162 // Then get the list of running users.
1163 final int[] runningUsers;
1164 try {
1165 runningUsers = ActivityManagerNative.getDefault().getRunningUserIds();
1166 } catch (RemoteException e) {
1167 Log.w(LOG_TAG, "Unable to access ActivityManagerNative");
1168 return;
1169 }
1170 // Then re-calculate the effective restrictions and apply, only for running users.
1171 // It's okay if a new user has started after the getRunningUserIds() call,
1172 // because we'll do the same thing (re-calculate the restrictions and apply)
1173 // when we start a user.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001174 synchronized (mRestrictionsLock) {
1175 for (int i = 0; i < runningUsers.length; i++) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001176 applyUserRestrictionsLR(runningUsers[i]);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001177 }
1178 }
1179 }
1180 };
1181 mHandler.post(r);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001182 }
1183
Amith Yamasani258848d2012-08-10 17:06:33 -07001184 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001185 * Check if we've hit the limit of how many users can be created.
1186 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001187 private boolean isUserLimitReached() {
1188 int count;
1189 synchronized (mUsersLock) {
1190 count = getAliveUsersExcludingGuestsCountLU();
1191 }
1192 return count >= UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001193 }
1194
1195 @Override
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001196 public boolean canAddMoreManagedProfiles(int userId, boolean allowedToRemoveOne) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001197 checkManageUsersPermission("check if more managed profiles can be added.");
1198 if (ActivityManager.isLowRamDeviceStatic()) {
1199 return false;
1200 }
Fyodor Kupolovb6157992015-06-05 15:32:28 -07001201 if (!mContext.getPackageManager().hasSystemFeature(
1202 PackageManager.FEATURE_MANAGED_USERS)) {
1203 return false;
1204 }
Nicolas Prevotb8186812015-08-06 15:00:03 +01001205 // Limit number of managed profiles that can be created
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001206 final int managedProfilesCount = getProfiles(userId, true).size() - 1;
1207 final int profilesRemovedCount = managedProfilesCount > 0 && allowedToRemoveOne ? 1 : 0;
1208 if (managedProfilesCount - profilesRemovedCount >= MAX_MANAGED_PROFILES) {
Nicolas Prevotb8186812015-08-06 15:00:03 +01001209 return false;
1210 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001211 synchronized(mUsersLock) {
1212 UserInfo userInfo = getUserInfoLU(userId);
Nicolas Prevotb8186812015-08-06 15:00:03 +01001213 if (!userInfo.canHaveProfile()) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001214 return false;
1215 }
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001216 int usersCountAfterRemoving = getAliveUsersExcludingGuestsCountLU()
1217 - profilesRemovedCount;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001218 // We allow creating a managed profile in the special case where there is only one user.
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001219 return usersCountAfterRemoving == 1
1220 || usersCountAfterRemoving < UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001221 }
1222 }
1223
Fyodor Kupolov82402752015-10-28 14:54:51 -07001224 private int getAliveUsersExcludingGuestsCountLU() {
Amith Yamasanif584f012014-05-19 17:57:25 -07001225 int aliveUserCount = 0;
1226 final int totalUserCount = mUsers.size();
1227 // Skip over users being removed
1228 for (int i = 0; i < totalUserCount; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001229 UserInfo user = mUsers.valueAt(i).info;
Amith Yamasani95ab7842014-08-11 17:09:26 -07001230 if (!mRemovingUserIds.get(user.id)
Amith Yamasani1df14732014-08-29 21:37:27 -07001231 && !user.isGuest() && !user.partial) {
Amith Yamasanif584f012014-05-19 17:57:25 -07001232 aliveUserCount++;
1233 }
1234 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001235 return aliveUserCount;
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001236 }
1237
1238 /**
Amith Yamasani195263742012-08-21 15:40:12 -07001239 * Enforces that only the system UID or root's UID or apps that have the
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001240 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} and
1241 * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL INTERACT_ACROSS_USERS_FULL}
1242 * permissions can make certain calls to the UserManager.
1243 *
1244 * @param message used as message if SecurityException is thrown
1245 * @throws SecurityException if the caller does not have enough privilege.
1246 */
1247 private static final void checkManageUserAndAcrossUsersFullPermission(String message) {
1248 final int uid = Binder.getCallingUid();
1249 if (uid != Process.SYSTEM_UID && uid != 0
1250 && ActivityManager.checkComponentPermission(
1251 Manifest.permission.MANAGE_USERS,
1252 uid, -1, true) != PackageManager.PERMISSION_GRANTED
1253 && ActivityManager.checkComponentPermission(
1254 Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1255 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
1256 throw new SecurityException(
1257 "You need MANAGE_USERS and INTERACT_ACROSS_USERS_FULL permission to: "
1258 + message);
1259 }
1260 }
1261
1262 /**
1263 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001264 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -07001265 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -07001266 *
1267 * @param message used as message if SecurityException is thrown
1268 * @throws SecurityException if the caller is not system or root
Tony Mak4dc008c2016-03-16 10:46:49 +00001269 * @see #hasManageUsersPermission()
Amith Yamasani258848d2012-08-10 17:06:33 -07001270 */
Amith Yamasanibe465322014-04-24 13:45:17 -07001271 private static final void checkManageUsersPermission(String message) {
Tony Mak4dc008c2016-03-16 10:46:49 +00001272 if (!hasManageUsersPermission()) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001273 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
1274 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -04001275 }
1276
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001277 /**
Tony Mak4dc008c2016-03-16 10:46:49 +00001278 * @return whether the calling UID is system UID or root's UID or the calling app has the
1279 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}.
1280 */
1281 private static final boolean hasManageUsersPermission() {
1282 final int callingUid = Binder.getCallingUid();
1283 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
1284 || callingUid == Process.ROOT_UID
1285 || ActivityManager.checkComponentPermission(
1286 android.Manifest.permission.MANAGE_USERS,
1287 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED;
1288 }
1289
1290 /**
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001291 * Enforces that only the system UID or root's UID (on any user) can make certain calls to the
1292 * UserManager.
1293 *
1294 * @param message used as message if SecurityException is thrown
1295 * @throws SecurityException if the caller is not system or root
1296 */
1297 private static void checkSystemOrRoot(String message) {
1298 final int uid = Binder.getCallingUid();
1299 if (!UserHandle.isSameApp(uid, Process.SYSTEM_UID) && uid != Process.ROOT_UID) {
1300 throw new SecurityException("Only system may: " + message);
1301 }
1302 }
1303
Fyodor Kupolov82402752015-10-28 14:54:51 -07001304 private void writeBitmapLP(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001305 try {
1306 File dir = new File(mUsersDir, Integer.toString(info.id));
1307 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +01001308 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001309 if (!dir.exists()) {
1310 dir.mkdir();
1311 FileUtils.setPermissions(
1312 dir.getPath(),
1313 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
1314 -1, -1);
1315 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001316 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +01001317 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001318 && tmp.renameTo(file) && SELinux.restorecon(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -07001319 info.iconPath = file.getAbsolutePath();
1320 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001321 try {
1322 os.close();
1323 } catch (IOException ioe) {
1324 // What the ... !
1325 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001326 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001327 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001328 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001329 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001330 }
1331
Amith Yamasani0b285492011-04-14 17:35:23 -07001332 /**
1333 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
1334 * cache it elsewhere.
1335 * @return the array of user ids.
1336 */
Dianne Hackborn1676c852012-09-10 14:52:30 -07001337 public int[] getUserIds() {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001338 synchronized (mUsersLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001339 return mUserIds;
1340 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001341 }
1342
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001343 private void readUserListLP() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001344 if (!mUserListFile.exists()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001345 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001346 return;
1347 }
1348 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001349 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001350 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001351 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001352 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001353 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001354 int type;
1355 while ((type = parser.next()) != XmlPullParser.START_TAG
1356 && type != XmlPullParser.END_DOCUMENT) {
Amith Yamasani12747872015-12-07 14:19:49 -08001357 // Skip
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001358 }
1359
1360 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001361 Slog.e(LOG_TAG, "Unable to read user list");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001362 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001363 return;
1364 }
1365
Amith Yamasani2a003292012-08-14 18:25:45 -07001366 mNextSerialNumber = -1;
1367 if (parser.getName().equals(TAG_USERS)) {
1368 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
1369 if (lastSerialNumber != null) {
1370 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
1371 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001372 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
1373 if (versionNumber != null) {
1374 mUserVersion = Integer.parseInt(versionNumber);
1375 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001376 }
1377
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001378 final Bundle newDevicePolicyGlobalUserRestrictions = new Bundle();
1379
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001380 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301381 if (type == XmlPullParser.START_TAG) {
1382 final String name = parser.getName();
1383 if (name.equals(TAG_USER)) {
1384 String id = parser.getAttributeValue(null, ATTR_ID);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001385
Amith Yamasani12747872015-12-07 14:19:49 -08001386 UserData userData = readUserLP(Integer.parseInt(id));
1387
1388 if (userData != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001389 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001390 mUsers.put(userData.info.id, userData);
1391 if (mNextSerialNumber < 0
1392 || mNextSerialNumber <= userData.info.id) {
1393 mNextSerialNumber = userData.info.id + 1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001394 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301395 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001396 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301397 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -08001398 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1399 && type != XmlPullParser.END_TAG) {
1400 if (type == XmlPullParser.START_TAG) {
1401 if (parser.getName().equals(TAG_RESTRICTIONS)) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001402 synchronized (mGuestRestrictions) {
1403 UserRestrictionsUtils
1404 .readRestrictions(parser, mGuestRestrictions);
1405 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001406 } else if (parser.getName().equals(TAG_DEVICE_POLICY_RESTRICTIONS)
1407 ) {
1408 UserRestrictionsUtils.readRestrictions(parser,
1409 newDevicePolicyGlobalUserRestrictions);
Amith Yamasanida0b1682014-11-21 12:58:17 -08001410 }
1411 break;
1412 }
1413 }
Amith Yamasani258848d2012-08-10 17:06:33 -07001414 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001415 }
1416 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001417 synchronized (mRestrictionsLock) {
1418 mDevicePolicyGlobalUserRestrictions = newDevicePolicyGlobalUserRestrictions;
1419 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001420 updateUserIds();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001421 upgradeIfNecessaryLP();
1422 } catch (IOException | XmlPullParserException e) {
1423 fallbackToSingleUserLP();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001424 } finally {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001425 IoUtils.closeQuietly(fis);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001426 }
1427 }
1428
Amith Yamasani6f34b412012-10-22 18:19:27 -07001429 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -08001430 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -07001431 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001432 private void upgradeIfNecessaryLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001433 final int originalVersion = mUserVersion;
Amith Yamasani6f34b412012-10-22 18:19:27 -07001434 int userVersion = mUserVersion;
1435 if (userVersion < 1) {
1436 // Assign a proper name for the owner, if not initialized correctly before
Amith Yamasani12747872015-12-07 14:19:49 -08001437 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
1438 if ("Primary".equals(userData.info.name)) {
1439 userData.info.name =
1440 mContext.getResources().getString(com.android.internal.R.string.owner_name);
1441 scheduleWriteUser(userData);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001442 }
1443 userVersion = 1;
1444 }
1445
Amith Yamasanibc9625052012-11-15 14:39:18 -08001446 if (userVersion < 2) {
1447 // Owner should be marked as initialized
Amith Yamasani12747872015-12-07 14:19:49 -08001448 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
1449 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1450 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
1451 scheduleWriteUser(userData);
Amith Yamasanibc9625052012-11-15 14:39:18 -08001452 }
1453 userVersion = 2;
1454 }
1455
Amith Yamasani350962c2013-08-06 11:18:53 -07001456
Amith Yamasani5e486f52013-08-07 11:06:44 -07001457 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -07001458 userVersion = 4;
1459 }
1460
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001461 if (userVersion < 5) {
1462 initDefaultGuestRestrictions();
1463 userVersion = 5;
1464 }
1465
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001466 if (userVersion < 6) {
1467 final boolean splitSystemUser = UserManager.isSplitSystemUser();
Fyodor Kupolov82402752015-10-28 14:54:51 -07001468 synchronized (mUsersLock) {
1469 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001470 UserData userData = mUsers.valueAt(i);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001471 // In non-split mode, only user 0 can have restricted profiles
Amith Yamasani12747872015-12-07 14:19:49 -08001472 if (!splitSystemUser && userData.info.isRestricted()
1473 && (userData.info.restrictedProfileParentId
1474 == UserInfo.NO_PROFILE_GROUP_ID)) {
1475 userData.info.restrictedProfileParentId = UserHandle.USER_SYSTEM;
1476 scheduleWriteUser(userData);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001477 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001478 }
1479 }
1480 userVersion = 6;
1481 }
1482
Amith Yamasani6f34b412012-10-22 18:19:27 -07001483 if (userVersion < USER_VERSION) {
1484 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
1485 + USER_VERSION);
1486 } else {
1487 mUserVersion = userVersion;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001488
1489 if (originalVersion < mUserVersion) {
1490 writeUserListLP();
1491 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001492 }
1493 }
1494
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001495 private void fallbackToSingleUserLP() {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001496 int flags = UserInfo.FLAG_INITIALIZED;
1497 // In split system user mode, the admin and primary flags are assigned to the first human
1498 // user.
1499 if (!UserManager.isSplitSystemUser()) {
1500 flags |= UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY;
1501 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001502 // Create the system user
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001503 UserInfo system = new UserInfo(UserHandle.USER_SYSTEM, null, null, flags);
Amith Yamasani12747872015-12-07 14:19:49 -08001504 UserData userData = new UserData();
1505 userData.info = system;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001506 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001507 mUsers.put(system.id, userData);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001508 }
Amith Yamasani634cf312012-10-04 17:34:21 -07001509 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -04001510 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -08001511
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001512 Bundle restrictions = new Bundle();
Makoto Onuki068c54a2015-10-13 14:34:03 -07001513 synchronized (mRestrictionsLock) {
1514 mBaseUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions);
1515 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001516
Fyodor Kupolov82402752015-10-28 14:54:51 -07001517 updateUserIds();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001518 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001519
Amith Yamasani12747872015-12-07 14:19:49 -08001520 writeUserLP(userData);
Jeff Sharkeycd575992016-03-29 14:12:49 -06001521 writeUserListLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001522 }
1523
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001524 private String getOwnerName() {
1525 return mContext.getResources().getString(com.android.internal.R.string.owner_name);
1526 }
1527
Amith Yamasani12747872015-12-07 14:19:49 -08001528 private void scheduleWriteUser(UserData UserData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001529 if (DBG) {
1530 debug("scheduleWriteUser");
1531 }
Makoto Onuki9e935a32015-11-06 14:24:24 -08001532 // No need to wrap it within a lock -- worst case, we'll just post the same message
1533 // twice.
Amith Yamasani12747872015-12-07 14:19:49 -08001534 if (!mHandler.hasMessages(WRITE_USER_MSG, UserData)) {
1535 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, UserData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001536 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
1537 }
1538 }
1539
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001540 /*
1541 * Writes the user file in this format:
1542 *
1543 * <user flags="20039023" id="0">
1544 * <name>Primary</name>
1545 * </user>
1546 */
Amith Yamasani12747872015-12-07 14:19:49 -08001547 private void writeUserLP(UserData userData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001548 if (DBG) {
Amith Yamasani12747872015-12-07 14:19:49 -08001549 debug("writeUserLP " + userData);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001550 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001551 FileOutputStream fos = null;
Amith Yamasani12747872015-12-07 14:19:49 -08001552 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userData.info.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001553 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001554 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001555 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1556
1557 // XmlSerializer serializer = XmlUtils.serializerInstance();
1558 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001559 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001560 serializer.startDocument(null, true);
1561 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1562
Amith Yamasani12747872015-12-07 14:19:49 -08001563 final UserInfo userInfo = userData.info;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001564 serializer.startTag(null, TAG_USER);
1565 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
Amith Yamasani2a003292012-08-14 18:25:45 -07001566 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001567 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Amith Yamasani920ace02012-09-20 22:15:37 -07001568 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
1569 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
1570 Long.toString(userInfo.lastLoggedInTime));
Jeff Sharkeycd575992016-03-29 14:12:49 -06001571 if (userInfo.lastLoggedInFingerprint != null) {
1572 serializer.attribute(null, ATTR_LAST_LOGGED_IN_FINGERPRINT,
1573 userInfo.lastLoggedInFingerprint);
1574 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001575 if (userInfo.iconPath != null) {
1576 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
1577 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001578 if (userInfo.partial) {
1579 serializer.attribute(null, ATTR_PARTIAL, "true");
1580 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001581 if (userInfo.guestToRemove) {
1582 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
1583 }
Kenny Guy2a764942014-04-02 13:29:20 +01001584 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
1585 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
1586 Integer.toString(userInfo.profileGroupId));
Kenny Guya52dc3e2014-02-11 15:33:14 +00001587 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001588 if (userInfo.restrictedProfileParentId != UserInfo.NO_PROFILE_GROUP_ID) {
1589 serializer.attribute(null, ATTR_RESTRICTED_PROFILE_PARENT_ID,
1590 Integer.toString(userInfo.restrictedProfileParentId));
1591 }
Amith Yamasani12747872015-12-07 14:19:49 -08001592 // Write seed data
1593 if (userData.persistSeedData) {
1594 if (userData.seedAccountName != null) {
1595 serializer.attribute(null, ATTR_SEED_ACCOUNT_NAME, userData.seedAccountName);
1596 }
1597 if (userData.seedAccountType != null) {
1598 serializer.attribute(null, ATTR_SEED_ACCOUNT_TYPE, userData.seedAccountType);
1599 }
1600 }
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001601 if (userInfo.name != null) {
1602 serializer.startTag(null, TAG_NAME);
1603 serializer.text(userInfo.name);
1604 serializer.endTag(null, TAG_NAME);
1605 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001606 synchronized (mRestrictionsLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001607 UserRestrictionsUtils.writeRestrictions(serializer,
1608 mBaseUserRestrictions.get(userInfo.id), TAG_RESTRICTIONS);
1609 UserRestrictionsUtils.writeRestrictions(serializer,
1610 mDevicePolicyLocalUserRestrictions.get(userInfo.id),
1611 TAG_DEVICE_POLICY_RESTRICTIONS);
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001612 }
Amith Yamasani12747872015-12-07 14:19:49 -08001613
1614 if (userData.account != null) {
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001615 serializer.startTag(null, TAG_ACCOUNT);
Amith Yamasani12747872015-12-07 14:19:49 -08001616 serializer.text(userData.account);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001617 serializer.endTag(null, TAG_ACCOUNT);
1618 }
1619
Amith Yamasani12747872015-12-07 14:19:49 -08001620 if (userData.persistSeedData && userData.seedAccountOptions != null) {
1621 serializer.startTag(null, TAG_SEED_ACCOUNT_OPTIONS);
1622 userData.seedAccountOptions.saveToXml(serializer);
1623 serializer.endTag(null, TAG_SEED_ACCOUNT_OPTIONS);
1624 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001625 serializer.endTag(null, TAG_USER);
1626
1627 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001628 userFile.finishWrite(fos);
1629 } catch (Exception ioe) {
Jeff Sharkeycd575992016-03-29 14:12:49 -06001630 Slog.e(LOG_TAG, "Error writing user info " + userData.info.id, ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -07001631 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001632 }
1633 }
1634
1635 /*
1636 * Writes the user list file in this format:
1637 *
Amith Yamasani2a003292012-08-14 18:25:45 -07001638 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001639 * <user id="0"></user>
1640 * <user id="2"></user>
1641 * </users>
1642 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001643 private void writeUserListLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001644 if (DBG) {
1645 debug("writeUserList");
1646 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001647 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001648 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001649 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001650 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001651 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1652
1653 // XmlSerializer serializer = XmlUtils.serializerInstance();
1654 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001655 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001656 serializer.startDocument(null, true);
1657 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1658
1659 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -07001660 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -07001661 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001662
Adam Lesinskieddeb492014-09-08 17:50:03 -07001663 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001664 synchronized (mGuestRestrictions) {
1665 UserRestrictionsUtils
1666 .writeRestrictions(serializer, mGuestRestrictions, TAG_RESTRICTIONS);
1667 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301668 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001669 synchronized (mRestrictionsLock) {
1670 UserRestrictionsUtils.writeRestrictions(serializer,
1671 mDevicePolicyGlobalUserRestrictions, TAG_DEVICE_POLICY_RESTRICTIONS);
1672 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001673 int[] userIdsToWrite;
1674 synchronized (mUsersLock) {
1675 userIdsToWrite = new int[mUsers.size()];
1676 for (int i = 0; i < userIdsToWrite.length; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001677 UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001678 userIdsToWrite[i] = user.id;
1679 }
1680 }
1681 for (int id : userIdsToWrite) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001682 serializer.startTag(null, TAG_USER);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001683 serializer.attribute(null, ATTR_ID, Integer.toString(id));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001684 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001685 }
1686
1687 serializer.endTag(null, TAG_USERS);
1688
1689 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001690 userListFile.finishWrite(fos);
1691 } catch (Exception e) {
1692 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -07001693 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001694 }
1695 }
1696
Amith Yamasani12747872015-12-07 14:19:49 -08001697 private UserData readUserLP(int id) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001698 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -07001699 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001700 String name = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001701 String account = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001702 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -07001703 long creationTime = 0L;
1704 long lastLoggedInTime = 0L;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06001705 String lastLoggedInFingerprint = null;
Kenny Guy2a764942014-04-02 13:29:20 +01001706 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001707 int restrictedProfileParentId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001708 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001709 boolean guestToRemove = false;
Amith Yamasani12747872015-12-07 14:19:49 -08001710 boolean persistSeedData = false;
1711 String seedAccountName = null;
1712 String seedAccountType = null;
1713 PersistableBundle seedAccountOptions = null;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001714 Bundle baseRestrictions = new Bundle();
1715 Bundle localRestrictions = new Bundle();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001716
1717 FileInputStream fis = null;
1718 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001719 AtomicFile userFile =
Amith Yamasanifc95e702013-09-26 13:20:17 -07001720 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
Amith Yamasani2a003292012-08-14 18:25:45 -07001721 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001722 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001723 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001724 int type;
1725 while ((type = parser.next()) != XmlPullParser.START_TAG
1726 && type != XmlPullParser.END_DOCUMENT) {
Amith Yamasani12747872015-12-07 14:19:49 -08001727 // Skip
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001728 }
1729
1730 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001731 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001732 return null;
1733 }
1734
1735 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001736 int storedId = readIntAttribute(parser, ATTR_ID, -1);
1737 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001738 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001739 return null;
1740 }
Amith Yamasani920ace02012-09-20 22:15:37 -07001741 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
1742 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001743 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -07001744 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
1745 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06001746 lastLoggedInFingerprint = parser.getAttributeValue(null,
1747 ATTR_LAST_LOGGED_IN_FINGERPRINT);
Kenny Guy2a764942014-04-02 13:29:20 +01001748 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
1749 UserInfo.NO_PROFILE_GROUP_ID);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001750 restrictedProfileParentId = readIntAttribute(parser,
1751 ATTR_RESTRICTED_PROFILE_PARENT_ID, UserInfo.NO_PROFILE_GROUP_ID);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001752 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
1753 if ("true".equals(valueString)) {
1754 partial = true;
1755 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001756 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
1757 if ("true".equals(valueString)) {
1758 guestToRemove = true;
1759 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001760
Amith Yamasani12747872015-12-07 14:19:49 -08001761 seedAccountName = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_NAME);
1762 seedAccountType = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_TYPE);
1763 if (seedAccountName != null || seedAccountType != null) {
1764 persistSeedData = true;
1765 }
1766
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001767 int outerDepth = parser.getDepth();
1768 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1769 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1770 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1771 continue;
1772 }
1773 String tag = parser.getName();
1774 if (TAG_NAME.equals(tag)) {
1775 type = parser.next();
1776 if (type == XmlPullParser.TEXT) {
1777 name = parser.getText();
1778 }
1779 } else if (TAG_RESTRICTIONS.equals(tag)) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001780 UserRestrictionsUtils.readRestrictions(parser, baseRestrictions);
1781 } else if (TAG_DEVICE_POLICY_RESTRICTIONS.equals(tag)) {
1782 UserRestrictionsUtils.readRestrictions(parser, localRestrictions);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001783 } else if (TAG_ACCOUNT.equals(tag)) {
1784 type = parser.next();
1785 if (type == XmlPullParser.TEXT) {
1786 account = parser.getText();
1787 }
Amith Yamasani12747872015-12-07 14:19:49 -08001788 } else if (TAG_SEED_ACCOUNT_OPTIONS.equals(tag)) {
1789 seedAccountOptions = PersistableBundle.restoreFromXml(parser);
1790 persistSeedData = true;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001791 }
1792 }
1793 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001794
Amith Yamasani12747872015-12-07 14:19:49 -08001795 // Create the UserInfo object that gets passed around
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001796 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -07001797 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -07001798 userInfo.creationTime = creationTime;
1799 userInfo.lastLoggedInTime = lastLoggedInTime;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06001800 userInfo.lastLoggedInFingerprint = lastLoggedInFingerprint;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001801 userInfo.partial = partial;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001802 userInfo.guestToRemove = guestToRemove;
Kenny Guy2a764942014-04-02 13:29:20 +01001803 userInfo.profileGroupId = profileGroupId;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001804 userInfo.restrictedProfileParentId = restrictedProfileParentId;
Amith Yamasani12747872015-12-07 14:19:49 -08001805
1806 // Create the UserData object that's internal to this class
1807 UserData userData = new UserData();
1808 userData.info = userInfo;
1809 userData.account = account;
1810 userData.seedAccountName = seedAccountName;
1811 userData.seedAccountType = seedAccountType;
1812 userData.persistSeedData = persistSeedData;
1813 userData.seedAccountOptions = seedAccountOptions;
1814
Makoto Onuki068c54a2015-10-13 14:34:03 -07001815 synchronized (mRestrictionsLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001816 mBaseUserRestrictions.put(id, baseRestrictions);
1817 mDevicePolicyLocalUserRestrictions.put(id, localRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001818 }
Amith Yamasani12747872015-12-07 14:19:49 -08001819 return userData;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001820 } catch (IOException ioe) {
1821 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001822 } finally {
1823 if (fis != null) {
1824 try {
1825 fis.close();
1826 } catch (IOException e) {
1827 }
1828 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001829 }
1830 return null;
1831 }
1832
Amith Yamasani920ace02012-09-20 22:15:37 -07001833 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
1834 String valueString = parser.getAttributeValue(null, attr);
1835 if (valueString == null) return defaultValue;
1836 try {
1837 return Integer.parseInt(valueString);
1838 } catch (NumberFormatException nfe) {
1839 return defaultValue;
1840 }
1841 }
1842
1843 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
1844 String valueString = parser.getAttributeValue(null, attr);
1845 if (valueString == null) return defaultValue;
1846 try {
1847 return Long.parseLong(valueString);
1848 } catch (NumberFormatException nfe) {
1849 return defaultValue;
1850 }
1851 }
1852
Amith Yamasanib82add22013-07-09 11:24:44 -07001853 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001854 * Removes the app restrictions file for a specific package and user id, if it exists.
1855 */
1856 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
1857 synchronized (mPackagesLock) {
1858 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07001859 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001860 if (resFile.exists()) {
1861 resFile.delete();
1862 }
1863 }
1864 }
1865
Kenny Guya52dc3e2014-02-11 15:33:14 +00001866 @Override
Kenny Guy2a764942014-04-02 13:29:20 +01001867 public UserInfo createProfileForUser(String name, int flags, int userId) {
Kenny Guya52dc3e2014-02-11 15:33:14 +00001868 checkManageUsersPermission("Only the system can create users");
Kenny Guy2a764942014-04-02 13:29:20 +01001869 return createUserInternal(name, flags, userId);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001870 }
1871
Amith Yamasani258848d2012-08-10 17:06:33 -07001872 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07001873 public UserInfo createUser(String name, int flags) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001874 checkManageUsersPermission("Only the system can create users");
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001875 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001876 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001877
Jessica Hummelbe81c802014-04-22 15:49:22 +01001878 private UserInfo createUserInternal(String name, int flags, int parentId) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001879 if (hasUserRestriction(UserManager.DISALLOW_ADD_USER, UserHandle.getCallingUserId())) {
Julia Reynolds75175022014-06-26 16:35:00 -04001880 Log.w(LOG_TAG, "Cannot add user. DISALLOW_ADD_USER is enabled.");
1881 return null;
1882 }
phweisse9c44062016-02-10 12:57:38 +01001883 return createUserInternalUnchecked(name, flags, parentId);
1884 }
1885
1886 private UserInfo createUserInternalUnchecked(String name, int flags, int parentId) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001887 if (ActivityManager.isLowRamDeviceStatic()) {
1888 return null;
1889 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07001890 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001891 final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001892 final boolean isRestricted = (flags & UserInfo.FLAG_RESTRICTED) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001893 final long ident = Binder.clearCallingIdentity();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001894 UserInfo userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08001895 UserData userData;
Amith Yamasanibb054c92015-07-09 14:16:27 -07001896 final int userId;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001897 try {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001898 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001899 UserData parent = null;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001900 if (parentId != UserHandle.USER_NULL) {
1901 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001902 parent = getUserDataLU(parentId);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001903 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001904 if (parent == null) return null;
1905 }
1906 if (isManagedProfile && !canAddMoreManagedProfiles(parentId, false)) {
1907 Log.e(LOG_TAG, "Cannot add more managed profiles for user " + parentId);
1908 return null;
1909 }
1910 if (!isGuest && !isManagedProfile && isUserLimitReached()) {
1911 // If we're not adding a guest user or a managed profile and the limit has
1912 // been reached, cannot add a user.
1913 return null;
1914 }
1915 // If we're adding a guest and there already exists one, bail.
1916 if (isGuest && findCurrentGuestUser() != null) {
1917 return null;
1918 }
1919 // In legacy mode, restricted profile's parent can only be the owner user
1920 if (isRestricted && !UserManager.isSplitSystemUser()
1921 && (parentId != UserHandle.USER_SYSTEM)) {
1922 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
1923 return null;
1924 }
1925 if (isRestricted && UserManager.isSplitSystemUser()) {
1926 if (parent == null) {
1927 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be "
1928 + "specified");
Nicolas Prevot12678a92015-05-13 12:15:03 -07001929 return null;
1930 }
Amith Yamasani12747872015-12-07 14:19:49 -08001931 if (!parent.info.canHaveProfile()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001932 Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be "
1933 + "created for the specified parent user id " + parentId);
Amith Yamasani95ab7842014-08-11 17:09:26 -07001934 return null;
1935 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001936 }
Lenka Trochtova024f9792016-02-17 13:55:17 +01001937 if (!UserManager.isSplitSystemUser() && (flags & UserInfo.FLAG_EPHEMERAL) != 0) {
1938 Log.e(LOG_TAG,
1939 "Ephemeral users are supported on split-system-user systems only.");
1940 return null;
1941 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001942 // In split system user mode, we assign the first human user the primary flag.
1943 // And if there is no device owner, we also assign the admin flag to primary user.
1944 if (UserManager.isSplitSystemUser()
1945 && !isGuest && !isManagedProfile && getPrimaryUser() == null) {
1946 flags |= UserInfo.FLAG_PRIMARY;
Makoto Onukie7927da2015-11-25 10:05:17 -08001947 synchronized (mUsersLock) {
1948 if (!mIsDeviceManaged) {
1949 flags |= UserInfo.FLAG_ADMIN;
1950 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07001951 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001952 }
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01001953
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01001954 userId = getNextAvailableId();
1955 Environment.getUserSystemDirectory(userId).mkdirs();
Lenka Trochtova02fee152015-12-22 14:26:18 +01001956 boolean ephemeralGuests = Resources.getSystem()
1957 .getBoolean(com.android.internal.R.bool.config_guestUserEphemeral);
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01001958
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001959 synchronized (mUsersLock) {
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01001960 // Add ephemeral flag to guests/users if required. Also inherit it from parent.
1961 if ((isGuest && ephemeralGuests) || mForceEphemeralUsers
1962 || (parent != null && parent.info.isEphemeral())) {
1963 flags |= UserInfo.FLAG_EPHEMERAL;
1964 }
1965
1966 userInfo = new UserInfo(userId, name, null, flags);
1967 userInfo.serialNumber = mNextSerialNumber++;
1968 long now = System.currentTimeMillis();
1969 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
1970 userInfo.partial = true;
Fyodor Kupolov83c24242016-03-31 13:30:42 -07001971 userInfo.lastLoggedInFingerprint = Build.FINGERPRINT;
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01001972 userData = new UserData();
1973 userData.info = userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08001974 mUsers.put(userId, userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001975 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06001976 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001977 writeUserListLP();
1978 if (parent != null) {
1979 if (isManagedProfile) {
Amith Yamasani12747872015-12-07 14:19:49 -08001980 if (parent.info.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
1981 parent.info.profileGroupId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001982 writeUserLP(parent);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001983 }
Amith Yamasani12747872015-12-07 14:19:49 -08001984 userInfo.profileGroupId = parent.info.profileGroupId;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001985 } else if (isRestricted) {
Amith Yamasani12747872015-12-07 14:19:49 -08001986 if (parent.info.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) {
1987 parent.info.restrictedProfileParentId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001988 writeUserLP(parent);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07001989 }
Amith Yamasani12747872015-12-07 14:19:49 -08001990 userInfo.restrictedProfileParentId = parent.info.restrictedProfileParentId;
Makoto Onuki068c54a2015-10-13 14:34:03 -07001991 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001992 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07001993 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001994 final StorageManager storage = mContext.getSystemService(StorageManager.class);
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01001995 storage.createUserKey(userId, userInfo.serialNumber, userInfo.isEphemeral());
Jeff Sharkey47f71082016-02-01 17:03:54 -07001996 prepareUserStorage(userId, userInfo.serialNumber,
1997 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001998 mPm.createNewUser(userId);
1999 userInfo.partial = false;
2000 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002001 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002002 }
2003 updateUserIds();
2004 Bundle restrictions = new Bundle();
Fyodor Kupolove04462c2015-11-30 15:02:53 -08002005 if (isGuest) {
2006 synchronized (mGuestRestrictions) {
2007 restrictions.putAll(mGuestRestrictions);
2008 }
2009 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002010 synchronized (mRestrictionsLock) {
2011 mBaseUserRestrictions.append(userId, restrictions);
2012 }
2013 mPm.newUserCreated(userId);
2014 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
2015 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
2016 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
2017 android.Manifest.permission.MANAGE_USERS);
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -08002018 MetricsLogger.count(mContext, isGuest ? TRON_GUEST_CREATED : TRON_USER_CREATED, 1);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002019 } finally {
2020 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07002021 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002022 return userInfo;
2023 }
2024
Amith Yamasani0b285492011-04-14 17:35:23 -07002025 /**
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002026 * @hide
2027 */
Amith Yamasani12747872015-12-07 14:19:49 -08002028 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002029 public UserInfo createRestrictedProfile(String name, int parentUserId) {
2030 checkManageUsersPermission("setupRestrictedProfile");
2031 final UserInfo user = createProfileForUser(name, UserInfo.FLAG_RESTRICTED, parentUserId);
2032 if (user == null) {
2033 return null;
2034 }
Fyodor Kupolov9e912ba2016-02-09 18:29:43 -08002035 long identity = Binder.clearCallingIdentity();
2036 try {
2037 setUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, true, user.id);
2038 // Change the setting before applying the DISALLOW_SHARE_LOCATION restriction, otherwise
2039 // the putIntForUser() will fail.
2040 android.provider.Settings.Secure.putIntForUser(mContext.getContentResolver(),
2041 android.provider.Settings.Secure.LOCATION_MODE,
2042 android.provider.Settings.Secure.LOCATION_MODE_OFF, user.id);
2043 setUserRestriction(UserManager.DISALLOW_SHARE_LOCATION, true, user.id);
2044 } finally {
2045 Binder.restoreCallingIdentity(identity);
2046 }
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002047 return user;
2048 }
2049
2050 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07002051 * Find the current guest user. If the Guest user is partial,
2052 * then do not include it in the results as it is about to die.
Adam Lesinskieddeb492014-09-08 17:50:03 -07002053 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002054 private UserInfo findCurrentGuestUser() {
2055 synchronized (mUsersLock) {
2056 final int size = mUsers.size();
2057 for (int i = 0; i < size; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002058 final UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002059 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
2060 return user;
2061 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002062 }
2063 }
2064 return null;
2065 }
2066
2067 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07002068 * Mark this guest user for deletion to allow us to create another guest
2069 * and switch to that user before actually removing this guest.
2070 * @param userHandle the userid of the current guest
2071 * @return whether the user could be marked for deletion
2072 */
Amith Yamasani12747872015-12-07 14:19:49 -08002073 @Override
Amith Yamasani1df14732014-08-29 21:37:27 -07002074 public boolean markGuestForDeletion(int userHandle) {
2075 checkManageUsersPermission("Only the system can remove users");
2076 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
2077 UserManager.DISALLOW_REMOVE_USER, false)) {
2078 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
2079 return false;
2080 }
2081
2082 long ident = Binder.clearCallingIdentity();
2083 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002084 final UserData userData;
Amith Yamasani1df14732014-08-29 21:37:27 -07002085 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002086 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002087 userData = mUsers.get(userHandle);
2088 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002089 return false;
2090 }
Amith Yamasani1df14732014-08-29 21:37:27 -07002091 }
Amith Yamasani12747872015-12-07 14:19:49 -08002092 if (!userData.info.isGuest()) {
Amith Yamasani1df14732014-08-29 21:37:27 -07002093 return false;
2094 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002095 // We set this to a guest user that is to be removed. This is a temporary state
2096 // where we are allowed to add new Guest users, even if this one is still not
2097 // removed. This user will still show up in getUserInfo() calls.
2098 // If we don't get around to removing this Guest user, it will be purged on next
2099 // startup.
Amith Yamasani12747872015-12-07 14:19:49 -08002100 userData.info.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07002101 // Mark it as disabled, so that it isn't returned any more when
2102 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002103 userData.info.flags |= UserInfo.FLAG_DISABLED;
2104 writeUserLP(userData);
Amith Yamasani1df14732014-08-29 21:37:27 -07002105 }
2106 } finally {
2107 Binder.restoreCallingIdentity(ident);
2108 }
2109 return true;
2110 }
2111
2112 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002113 * Removes a user and all data directories created for that user. This method should be called
2114 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07002115 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07002116 */
Amith Yamasani12747872015-12-07 14:19:49 -08002117 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -07002118 public boolean removeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002119 checkManageUsersPermission("Only the system can remove users");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04002120 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
2121 UserManager.DISALLOW_REMOVE_USER, false)) {
2122 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
2123 return false;
2124 }
2125
Kenny Guyee58b4f2014-05-23 15:19:53 +01002126 long ident = Binder.clearCallingIdentity();
2127 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002128 final UserData userData;
Fyodor Kupolov0df68cd2015-10-01 13:54:22 -07002129 int currentUser = ActivityManager.getCurrentUser();
2130 if (currentUser == userHandle) {
2131 Log.w(LOG_TAG, "Current user cannot be removed");
2132 return false;
2133 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002134 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002135 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002136 userData = mUsers.get(userHandle);
2137 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002138 return false;
2139 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002140
Fyodor Kupolov82402752015-10-28 14:54:51 -07002141 // We remember deleted user IDs to prevent them from being
2142 // reused during the current boot; they can still be reused
2143 // after a reboot.
2144 mRemovingUserIds.put(userHandle, true);
2145 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002146
Kenny Guyee58b4f2014-05-23 15:19:53 +01002147 try {
2148 mAppOpsService.removeUser(userHandle);
2149 } catch (RemoteException e) {
2150 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
2151 }
2152 // Set this to a partially created user, so that the user will be purged
2153 // on next startup, in case the runtime stops now before stopping and
2154 // removing the user completely.
Amith Yamasani12747872015-12-07 14:19:49 -08002155 userData.info.partial = true;
Kenny Guyee58b4f2014-05-23 15:19:53 +01002156 // Mark it as disabled, so that it isn't returned any more when
2157 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002158 userData.info.flags |= UserInfo.FLAG_DISABLED;
2159 writeUserLP(userData);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002160 }
2161
Amith Yamasani12747872015-12-07 14:19:49 -08002162 if (userData.info.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
2163 && userData.info.isManagedProfile()) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002164 // Send broadcast to notify system that the user removed was a
2165 // managed user.
Amith Yamasani12747872015-12-07 14:19:49 -08002166 sendProfileRemovedBroadcast(userData.info.profileGroupId, userData.info.id);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002167 }
2168
2169 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
2170 int res;
2171 try {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07002172 res = ActivityManagerNative.getDefault().stopUser(userHandle, /* force= */ true,
2173 new IStopUserCallback.Stub() {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002174 @Override
2175 public void userStopped(int userId) {
2176 finishRemoveUser(userId);
2177 }
2178 @Override
2179 public void userStopAborted(int userId) {
2180 }
2181 });
2182 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002183 return false;
2184 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002185 return res == ActivityManager.USER_OP_SUCCESS;
2186 } finally {
2187 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002188 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002189 }
2190
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002191 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07002192 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002193 // Let other services shutdown any activity and clean up their state before completely
2194 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002195 long ident = Binder.clearCallingIdentity();
2196 try {
2197 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
2198 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002199 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
2200 android.Manifest.permission.MANAGE_USERS,
2201
2202 new BroadcastReceiver() {
2203 @Override
2204 public void onReceive(Context context, Intent intent) {
2205 if (DBG) {
2206 Slog.i(LOG_TAG,
2207 "USER_REMOVED broadcast sent, cleaning up user data "
2208 + userHandle);
2209 }
2210 new Thread() {
Amith Yamasani12747872015-12-07 14:19:49 -08002211 @Override
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002212 public void run() {
Amith Yamasani515d4062015-09-28 11:30:06 -07002213 // Clean up any ActivityManager state
2214 LocalServices.getService(ActivityManagerInternal.class)
2215 .onUserRemoved(userHandle);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002216 removeUserState(userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002217 }
2218 }.start();
2219 }
2220 },
2221
2222 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002223 } finally {
2224 Binder.restoreCallingIdentity(ident);
2225 }
Amith Yamasani2a003292012-08-14 18:25:45 -07002226 }
2227
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002228 private void removeUserState(final int userHandle) {
Paul Crowley91293792016-03-25 15:23:07 -07002229 try {
2230 mContext.getSystemService(StorageManager.class).destroyUserKey(userHandle);
2231 } catch (IllegalStateException e) {
2232 // This may be simply because the user was partially created.
2233 Slog.i(LOG_TAG,
2234 "Destroying key for user " + userHandle + " failed, continuing anyway", e);
2235 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002236 // Cleanup package manager settings
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002237 mPm.cleanUpUser(this, userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002238
2239 // Remove this user from the list
Fyodor Kupolov82402752015-10-28 14:54:51 -07002240 synchronized (mUsersLock) {
2241 mUsers.remove(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08002242 mIsUserManaged.delete(userHandle);
2243 }
2244 synchronized (mRestrictionsLock) {
2245 mBaseUserRestrictions.remove(userHandle);
2246 mAppliedUserRestrictions.remove(userHandle);
2247 mCachedEffectiveUserRestrictions.remove(userHandle);
2248 mDevicePolicyLocalUserRestrictions.remove(userHandle);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002249 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002250 // Update the user list
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002251 synchronized (mPackagesLock) {
2252 writeUserListLP();
2253 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06002254 // Remove user file
2255 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
2256 userFile.delete();
Fyodor Kupolov82402752015-10-28 14:54:51 -07002257 updateUserIds();
Amith Yamasani12747872015-12-07 14:19:49 -08002258 File userDir = Environment.getUserSystemDirectory(userHandle);
2259 File renamedUserDir = Environment.getUserSystemDirectory(UserHandle.USER_NULL - userHandle);
2260 if (userDir.renameTo(renamedUserDir)) {
2261 removeDirectoryRecursive(renamedUserDir);
2262 } else {
2263 removeDirectoryRecursive(userDir);
2264 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002265 }
2266
Amith Yamasani61f57372012-08-31 12:12:28 -07002267 private void removeDirectoryRecursive(File parent) {
2268 if (parent.isDirectory()) {
2269 String[] files = parent.list();
2270 for (String filename : files) {
2271 File child = new File(parent, filename);
2272 removeDirectoryRecursive(child);
2273 }
2274 }
2275 parent.delete();
2276 }
2277
Kenny Guyf8d3a232014-05-15 16:09:52 +01002278 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01002279 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01002280 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
2281 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002282 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
Jeff Sharkeyaf6ec292015-12-17 11:19:00 -07002283 managedProfileIntent.putExtra(Intent.EXTRA_USER_HANDLE, removedUserId);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002284 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01002285 }
2286
Amith Yamasani2a003292012-08-14 18:25:45 -07002287 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002288 public Bundle getApplicationRestrictions(String packageName) {
2289 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
2290 }
2291
2292 @Override
2293 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002294 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07002295 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00002296 checkSystemOrRoot("get application restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002297 }
2298 synchronized (mPackagesLock) {
2299 // Read the restrictions from XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07002300 return readApplicationRestrictionsLP(packageName, userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002301 }
2302 }
2303
2304 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002305 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002306 int userId) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00002307 checkSystemOrRoot("set application restrictions");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002308 synchronized (mPackagesLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01002309 if (restrictions == null || restrictions.isEmpty()) {
2310 cleanAppRestrictionsForPackage(packageName, userId);
2311 } else {
Amith Yamasani23879322016-03-30 16:51:26 -07002312 restrictions.setDefusable(true);
Kenny Guyd21b2182014-07-17 16:38:55 +01002313 // Write the restrictions to XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07002314 writeApplicationRestrictionsLP(packageName, restrictions, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01002315 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002316 }
Robin Lee66e5d962014-04-09 16:44:21 +01002317
Fyodor Kupolovd2846122016-02-11 18:06:34 -08002318 // Notify package of changes via an intent - only sent to explicitly registered receivers.
2319 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
2320 changeIntent.setPackage(packageName);
2321 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
2322 mContext.sendBroadcastAsUser(changeIntent, UserHandle.of(userId));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002323 }
2324
2325 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07002326 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002327 try {
2328 return mContext.getPackageManager().getApplicationInfo(packageName,
Fyodor Kupolovd2846122016-02-11 18:06:34 -08002329 PackageManager.MATCH_UNINSTALLED_PACKAGES).uid;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002330 } catch (NameNotFoundException nnfe) {
2331 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07002332 } finally {
2333 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002334 }
2335 }
2336
Fyodor Kupolov82402752015-10-28 14:54:51 -07002337 private Bundle readApplicationRestrictionsLP(String packageName, int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002338 AtomicFile restrictionsFile =
2339 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
2340 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002341 return readApplicationRestrictionsLP(restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002342 }
2343
2344 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002345 static Bundle readApplicationRestrictionsLP(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002346 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002347 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002348 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07002349 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002350 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002351
2352 FileInputStream fis = null;
2353 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002354 fis = restrictionsFile.openRead();
2355 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002356 parser.setInput(fis, StandardCharsets.UTF_8.name());
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002357 XmlUtils.nextElement(parser);
2358 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002359 Slog.e(LOG_TAG, "Unable to read restrictions file "
2360 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002361 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002362 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002363 while (parser.next() != XmlPullParser.END_DOCUMENT) {
2364 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002365 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002366 } catch (IOException|XmlPullParserException e) {
2367 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002368 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002369 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002370 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002371 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002372 }
2373
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002374 private static void readEntry(Bundle restrictions, ArrayList<String> values,
2375 XmlPullParser parser) throws XmlPullParserException, IOException {
2376 int type = parser.getEventType();
2377 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
2378 String key = parser.getAttributeValue(null, ATTR_KEY);
2379 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
2380 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
2381 if (multiple != null) {
2382 values.clear();
2383 int count = Integer.parseInt(multiple);
2384 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
2385 if (type == XmlPullParser.START_TAG
2386 && parser.getName().equals(TAG_VALUE)) {
2387 values.add(parser.nextText().trim());
2388 count--;
2389 }
2390 }
2391 String [] valueStrings = new String[values.size()];
2392 values.toArray(valueStrings);
2393 restrictions.putStringArray(key, valueStrings);
2394 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
2395 restrictions.putBundle(key, readBundleEntry(parser, values));
2396 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
2397 final int outerDepth = parser.getDepth();
2398 ArrayList<Bundle> bundleList = new ArrayList<>();
2399 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2400 Bundle childBundle = readBundleEntry(parser, values);
2401 bundleList.add(childBundle);
2402 }
2403 restrictions.putParcelableArray(key,
2404 bundleList.toArray(new Bundle[bundleList.size()]));
2405 } else {
2406 String value = parser.nextText().trim();
2407 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
2408 restrictions.putBoolean(key, Boolean.parseBoolean(value));
2409 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
2410 restrictions.putInt(key, Integer.parseInt(value));
2411 } else {
2412 restrictions.putString(key, value);
2413 }
2414 }
2415 }
2416 }
2417
2418 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
2419 throws IOException, XmlPullParserException {
2420 Bundle childBundle = new Bundle();
2421 final int outerDepth = parser.getDepth();
2422 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2423 readEntry(childBundle, values, parser);
2424 }
2425 return childBundle;
2426 }
2427
Fyodor Kupolov82402752015-10-28 14:54:51 -07002428 private void writeApplicationRestrictionsLP(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002429 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002430 AtomicFile restrictionsFile = new AtomicFile(
2431 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07002432 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002433 writeApplicationRestrictionsLP(restrictions, restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002434 }
2435
2436 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002437 static void writeApplicationRestrictionsLP(Bundle restrictions, AtomicFile restrictionsFile) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002438 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002439 try {
2440 fos = restrictionsFile.startWrite();
2441 final BufferedOutputStream bos = new BufferedOutputStream(fos);
2442
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002443 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002444 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002445 serializer.startDocument(null, true);
2446 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2447
2448 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002449 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002450 serializer.endTag(null, TAG_RESTRICTIONS);
2451
2452 serializer.endDocument();
2453 restrictionsFile.finishWrite(fos);
2454 } catch (Exception e) {
2455 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002456 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
2457 }
2458 }
2459
2460 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
2461 throws IOException {
2462 for (String key : restrictions.keySet()) {
2463 Object value = restrictions.get(key);
2464 serializer.startTag(null, TAG_ENTRY);
2465 serializer.attribute(null, ATTR_KEY, key);
2466
2467 if (value instanceof Boolean) {
2468 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
2469 serializer.text(value.toString());
2470 } else if (value instanceof Integer) {
2471 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
2472 serializer.text(value.toString());
2473 } else if (value == null || value instanceof String) {
2474 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
2475 serializer.text(value != null ? (String) value : "");
2476 } else if (value instanceof Bundle) {
2477 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2478 writeBundle((Bundle) value, serializer);
2479 } else if (value instanceof Parcelable[]) {
2480 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
2481 Parcelable[] array = (Parcelable[]) value;
2482 for (Parcelable parcelable : array) {
2483 if (!(parcelable instanceof Bundle)) {
2484 throw new IllegalArgumentException("bundle-array can only hold Bundles");
2485 }
2486 serializer.startTag(null, TAG_ENTRY);
2487 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2488 writeBundle((Bundle) parcelable, serializer);
2489 serializer.endTag(null, TAG_ENTRY);
2490 }
2491 } else {
2492 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
2493 String[] values = (String[]) value;
2494 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
2495 for (String choice : values) {
2496 serializer.startTag(null, TAG_VALUE);
2497 serializer.text(choice != null ? choice : "");
2498 serializer.endTag(null, TAG_VALUE);
2499 }
2500 }
2501 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002502 }
2503 }
2504
2505 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07002506 public int getUserSerialNumber(int userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002507 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002508 if (!exists(userHandle)) return -1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002509 return getUserInfoLU(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07002510 }
2511 }
2512
2513 @Override
2514 public int getUserHandle(int userSerialNumber) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002515 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002516 for (int userId : mUserIds) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002517 UserInfo info = getUserInfoLU(userId);
Kenny Guy945f8832015-02-10 15:17:26 +00002518 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07002519 }
2520 // Not found
2521 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07002522 }
2523 }
2524
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002525 @Override
2526 public long getUserCreationTime(int userHandle) {
2527 int callingUserId = UserHandle.getCallingUserId();
2528 UserInfo userInfo = null;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002529 synchronized (mUsersLock) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002530 if (callingUserId == userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002531 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002532 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002533 UserInfo parent = getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002534 if (parent != null && parent.id == callingUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002535 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002536 }
2537 }
2538 }
2539 if (userInfo == null) {
2540 throw new SecurityException("userHandle can only be the calling user or a managed "
2541 + "profile associated with this user");
2542 }
2543 return userInfo.creationTime;
2544 }
2545
Amith Yamasani0b285492011-04-14 17:35:23 -07002546 /**
2547 * Caches the list of user ids in an array, adjusting the array size when necessary.
2548 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002549 private void updateUserIds() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002550 int num = 0;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002551 synchronized (mUsersLock) {
2552 final int userSize = mUsers.size();
2553 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002554 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002555 num++;
2556 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002557 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002558 final int[] newUsers = new int[num];
2559 int n = 0;
2560 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002561 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002562 newUsers[n++] = mUsers.keyAt(i);
2563 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002564 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002565 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07002566 }
2567 }
2568
2569 /**
Jeff Sharkey47f71082016-02-01 17:03:54 -07002570 * Prepare storage areas for given user on all mounted devices.
2571 */
2572 private void prepareUserStorage(int userId, int userSerial, int flags) {
2573 final StorageManager storage = mContext.getSystemService(StorageManager.class);
2574 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
2575 final String volumeUuid = vol.getFsUuid();
2576 storage.prepareUserStorage(volumeUuid, userId, userSerial, flags);
2577 }
2578 }
2579
2580 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002581 * Called right before a user is started. This gives us a chance to prepare
2582 * app storage and apply any user restrictions.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002583 */
2584 public void onBeforeStartUser(int userId) {
Jeff Sharkey47f71082016-02-01 17:03:54 -07002585 final int userSerial = getUserSerialNumber(userId);
2586 prepareUserStorage(userId, userSerial, StorageManager.FLAG_STORAGE_DE);
2587 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_DE);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002588
2589 if (userId != UserHandle.USER_SYSTEM) {
2590 synchronized (mRestrictionsLock) {
2591 applyUserRestrictionsLR(userId);
2592 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002593 }
2594 }
2595
2596 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002597 * Called right before a user is unlocked. This gives us a chance to prepare
2598 * app storage.
2599 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002600 public void onBeforeUnlockUser(@UserIdInt int userId) {
Jeff Sharkey47f71082016-02-01 17:03:54 -07002601 final int userSerial = getUserSerialNumber(userId);
2602 prepareUserStorage(userId, userSerial, StorageManager.FLAG_STORAGE_CE);
2603 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_CE);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002604 }
2605
2606 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002607 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasani920ace02012-09-20 22:15:37 -07002608 * @param userId the user that was just foregrounded
2609 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002610 public void onUserLoggedIn(@UserIdInt int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -08002611 UserData userData = getUserDataNoChecks(userId);
2612 if (userData == null || userData.info.partial) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002613 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
2614 return;
2615 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002616
2617 final long now = System.currentTimeMillis();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002618 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani12747872015-12-07 14:19:49 -08002619 userData.info.lastLoggedInTime = now;
Amith Yamasani920ace02012-09-20 22:15:37 -07002620 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002621 userData.info.lastLoggedInFingerprint = Build.FINGERPRINT;
2622 scheduleWriteUser(userData);
Amith Yamasani920ace02012-09-20 22:15:37 -07002623 }
2624
2625 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002626 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani742a6712011-05-04 14:49:28 -07002627 * TODO: May not be a good idea to recycle ids, in case it results in confusion
2628 * for data and battery stats collection, or unexpected cross-talk.
Amith Yamasani0b285492011-04-14 17:35:23 -07002629 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002630 private int getNextAvailableId() {
2631 synchronized (mUsersLock) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002632 int i = MIN_USER_ID;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002633 while (i < MAX_USER_ID) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002634 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002635 return i;
Amith Yamasani195263742012-08-21 15:40:12 -07002636 }
2637 i++;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002638 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002639 }
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002640 throw new IllegalStateException("No user id available!");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002641 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002642
Amith Yamasanifc95e702013-09-26 13:20:17 -07002643 private String packageToRestrictionsFileName(String packageName) {
2644 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
2645 }
2646
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002647 /**
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002648 * Enforce that serial number stored in user directory inode matches the
2649 * given expected value. Gracefully sets the serial number if currently
2650 * undefined.
2651 *
2652 * @throws IOException when problem extracting serial number, or serial
2653 * number is mismatched.
2654 */
2655 public static void enforceSerialNumber(File file, int serialNumber) throws IOException {
2656 final int foundSerial = getSerialNumber(file);
2657 Slog.v(LOG_TAG, "Found " + file + " with serial number " + foundSerial);
2658
2659 if (foundSerial == -1) {
2660 Slog.d(LOG_TAG, "Serial number missing on " + file + "; assuming current is valid");
2661 try {
2662 setSerialNumber(file, serialNumber);
2663 } catch (IOException e) {
2664 Slog.w(LOG_TAG, "Failed to set serial number on " + file, e);
2665 }
2666
2667 } else if (foundSerial != serialNumber) {
2668 throw new IOException("Found serial number " + foundSerial
2669 + " doesn't match expected " + serialNumber);
2670 }
2671 }
2672
2673 /**
2674 * Set serial number stored in user directory inode.
2675 *
2676 * @throws IOException if serial number was already set
2677 */
2678 private static void setSerialNumber(File file, int serialNumber)
2679 throws IOException {
2680 try {
2681 final byte[] buf = Integer.toString(serialNumber).getBytes(StandardCharsets.UTF_8);
2682 Os.setxattr(file.getAbsolutePath(), XATTR_SERIAL, buf, OsConstants.XATTR_CREATE);
2683 } catch (ErrnoException e) {
2684 throw e.rethrowAsIOException();
2685 }
2686 }
2687
2688 /**
2689 * Return serial number stored in user directory inode.
2690 *
2691 * @return parsed serial number, or -1 if not set
2692 */
2693 private static int getSerialNumber(File file) throws IOException {
2694 try {
2695 final byte[] buf = new byte[256];
2696 final int len = Os.getxattr(file.getAbsolutePath(), XATTR_SERIAL, buf);
2697 final String serial = new String(buf, 0, len);
2698 try {
2699 return Integer.parseInt(serial);
2700 } catch (NumberFormatException e) {
2701 throw new IOException("Bad serial number: " + serial);
2702 }
2703 } catch (ErrnoException e) {
2704 if (e.errno == OsConstants.ENODATA) {
2705 return -1;
2706 } else {
2707 throw e.rethrowAsIOException();
2708 }
2709 }
2710 }
2711
Amith Yamasani920ace02012-09-20 22:15:37 -07002712 @Override
Amith Yamasani12747872015-12-07 14:19:49 -08002713 public void setSeedAccountData(int userId, String accountName, String accountType,
2714 PersistableBundle accountOptions, boolean persist) {
2715 checkManageUsersPermission("Require MANAGE_USERS permission to set user seed data");
2716 synchronized (mPackagesLock) {
2717 final UserData userData;
2718 synchronized (mUsersLock) {
2719 userData = getUserDataLU(userId);
2720 if (userData == null) {
2721 Slog.e(LOG_TAG, "No such user for settings seed data u=" + userId);
2722 return;
2723 }
2724 userData.seedAccountName = accountName;
2725 userData.seedAccountType = accountType;
2726 userData.seedAccountOptions = accountOptions;
2727 userData.persistSeedData = persist;
2728 }
2729 if (persist) {
2730 writeUserLP(userData);
2731 }
2732 }
2733 }
2734
2735 @Override
2736 public String getSeedAccountName() throws RemoteException {
2737 checkManageUsersPermission("Cannot get seed account information");
2738 synchronized (mUsersLock) {
2739 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
2740 return userData.seedAccountName;
2741 }
2742 }
2743
2744 @Override
2745 public String getSeedAccountType() throws RemoteException {
2746 checkManageUsersPermission("Cannot get seed account information");
2747 synchronized (mUsersLock) {
2748 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
2749 return userData.seedAccountType;
2750 }
2751 }
2752
2753 @Override
2754 public PersistableBundle getSeedAccountOptions() throws RemoteException {
2755 checkManageUsersPermission("Cannot get seed account information");
2756 synchronized (mUsersLock) {
2757 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
2758 return userData.seedAccountOptions;
2759 }
2760 }
2761
2762 @Override
2763 public void clearSeedAccountData() throws RemoteException {
2764 checkManageUsersPermission("Cannot clear seed account information");
2765 synchronized (mPackagesLock) {
2766 UserData userData;
2767 synchronized (mUsersLock) {
2768 userData = getUserDataLU(UserHandle.getCallingUserId());
2769 if (userData == null) return;
2770 userData.clearSeedAccountData();
2771 }
2772 writeUserLP(userData);
2773 }
2774 }
2775
2776 @Override
2777 public boolean someUserHasSeedAccount(String accountName, String accountType)
2778 throws RemoteException {
2779 checkManageUsersPermission("Cannot check seed account information");
2780 synchronized (mUsersLock) {
2781 final int userSize = mUsers.size();
2782 for (int i = 0; i < userSize; i++) {
2783 final UserData data = mUsers.valueAt(i);
2784 if (data.info.isInitialized()) continue;
2785 if (data.seedAccountName == null || !data.seedAccountName.equals(accountName)) {
2786 continue;
2787 }
2788 if (data.seedAccountType == null || !data.seedAccountType.equals(accountType)) {
2789 continue;
2790 }
2791 return true;
2792 }
2793 }
2794 return false;
2795 }
2796
2797 @Override
Todd Kennedy60459ab2015-10-30 11:32:16 -07002798 public void onShellCommand(FileDescriptor in, FileDescriptor out,
2799 FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
2800 (new Shell()).exec(this, in, out, err, args, resultReceiver);
2801 }
2802
2803 int onShellCommand(Shell shell, String cmd) {
2804 if (cmd == null) {
2805 return shell.handleDefaultCommands(cmd);
2806 }
2807
2808 final PrintWriter pw = shell.getOutPrintWriter();
2809 try {
2810 switch(cmd) {
2811 case "list":
2812 return runList(pw);
2813 }
2814 } catch (RemoteException e) {
2815 pw.println("Remote exception: " + e);
2816 }
2817 return -1;
2818 }
2819
2820 private int runList(PrintWriter pw) throws RemoteException {
2821 final IActivityManager am = ActivityManagerNative.getDefault();
2822 final List<UserInfo> users = getUsers(false);
2823 if (users == null) {
2824 pw.println("Error: couldn't get users");
2825 return 1;
2826 } else {
2827 pw.println("Users:");
2828 for (int i = 0; i < users.size(); i++) {
Jeff Sharkeye17ac152015-11-06 22:40:29 -08002829 String running = am.isUserRunning(users.get(i).id, 0) ? " running" : "";
Todd Kennedy60459ab2015-10-30 11:32:16 -07002830 pw.println("\t" + users.get(i).toString() + running);
2831 }
2832 return 0;
2833 }
2834 }
2835
2836 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -07002837 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2838 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2839 != PackageManager.PERMISSION_GRANTED) {
2840 pw.println("Permission Denial: can't dump UserManager from from pid="
2841 + Binder.getCallingPid()
2842 + ", uid=" + Binder.getCallingUid()
2843 + " without permission "
2844 + android.Manifest.permission.DUMP);
2845 return;
2846 }
2847
2848 long now = System.currentTimeMillis();
2849 StringBuilder sb = new StringBuilder();
2850 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002851 synchronized (mUsersLock) {
2852 pw.println("Users:");
2853 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002854 UserData userData = mUsers.valueAt(i);
2855 if (userData == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002856 continue;
2857 }
Amith Yamasani12747872015-12-07 14:19:49 -08002858 UserInfo userInfo = userData.info;
2859 final int userId = userInfo.id;
2860 pw.print(" "); pw.print(userInfo);
2861 pw.print(" serialNo="); pw.print(userInfo.serialNumber);
Makoto Onukie7927da2015-11-25 10:05:17 -08002862 if (mRemovingUserIds.get(userId)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002863 pw.print(" <removing> ");
2864 }
Amith Yamasani12747872015-12-07 14:19:49 -08002865 if (userInfo.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002866 pw.print(" <partial>");
2867 }
2868 pw.println();
2869 pw.print(" Created: ");
Amith Yamasani12747872015-12-07 14:19:49 -08002870 if (userInfo.creationTime == 0) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002871 pw.println("<unknown>");
2872 } else {
2873 sb.setLength(0);
Amith Yamasani12747872015-12-07 14:19:49 -08002874 TimeUtils.formatDuration(now - userInfo.creationTime, sb);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002875 sb.append(" ago");
2876 pw.println(sb);
2877 }
2878 pw.print(" Last logged in: ");
Amith Yamasani12747872015-12-07 14:19:49 -08002879 if (userInfo.lastLoggedInTime == 0) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002880 pw.println("<unknown>");
2881 } else {
2882 sb.setLength(0);
Amith Yamasani12747872015-12-07 14:19:49 -08002883 TimeUtils.formatDuration(now - userInfo.lastLoggedInTime, sb);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002884 sb.append(" ago");
2885 pw.println(sb);
2886 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002887 pw.print(" Last logged in fingerprint: ");
2888 pw.println(userInfo.lastLoggedInFingerprint);
Makoto Onukie7927da2015-11-25 10:05:17 -08002889 pw.print(" Has profile owner: ");
2890 pw.println(mIsUserManaged.get(userId));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002891 pw.println(" Restrictions:");
2892 synchronized (mRestrictionsLock) {
2893 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08002894 pw, " ", mBaseUserRestrictions.get(userInfo.id));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002895 pw.println(" Device policy local restrictions:");
2896 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08002897 pw, " ", mDevicePolicyLocalUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002898 pw.println(" Effective restrictions:");
2899 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08002900 pw, " ", mCachedEffectiveUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002901 }
Amith Yamasani12747872015-12-07 14:19:49 -08002902
2903 if (userData.account != null) {
2904 pw.print(" Account name: " + userData.account);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08002905 pw.println();
2906 }
Amith Yamasani12747872015-12-07 14:19:49 -08002907
2908 if (userData.seedAccountName != null) {
2909 pw.print(" Seed account name: " + userData.seedAccountName);
2910 pw.println();
2911 if (userData.seedAccountType != null) {
2912 pw.print(" account type: " + userData.seedAccountType);
2913 pw.println();
2914 }
2915 if (userData.seedAccountOptions != null) {
2916 pw.print(" account options exist");
2917 pw.println();
2918 }
2919 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002920 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002921 }
Amith Yamasani12747872015-12-07 14:19:49 -08002922 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002923 pw.println(" Device policy global restrictions:");
2924 synchronized (mRestrictionsLock) {
2925 UserRestrictionsUtils
2926 .dumpRestrictions(pw, " ", mDevicePolicyGlobalUserRestrictions);
2927 }
Makoto Onukia4f11972015-10-01 13:19:58 -07002928 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002929 pw.println(" Guest restrictions:");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002930 synchronized (mGuestRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002931 UserRestrictionsUtils.dumpRestrictions(pw, " ", mGuestRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002932 }
Makoto Onukie7927da2015-11-25 10:05:17 -08002933 synchronized (mUsersLock) {
2934 pw.println();
2935 pw.println(" Device managed: " + mIsDeviceManaged);
2936 }
Amith Yamasani12747872015-12-07 14:19:49 -08002937 // Dump some capabilities
2938 pw.println();
2939 pw.println(" Max users: " + UserManager.getMaxSupportedUsers());
2940 pw.println(" Supports switchable users: " + UserManager.supportsMultipleUsers());
Lenka Trochtova02fee152015-12-22 14:26:18 +01002941 pw.println(" All guests ephemeral: " + Resources.getSystem().getBoolean(
2942 com.android.internal.R.bool.config_guestUserEphemeral));
Amith Yamasani920ace02012-09-20 22:15:37 -07002943 }
2944 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002945
2946 final class MainHandler extends Handler {
2947
2948 @Override
2949 public void handleMessage(Message msg) {
2950 switch (msg.what) {
2951 case WRITE_USER_MSG:
2952 removeMessages(WRITE_USER_MSG, msg.obj);
2953 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002954 int userId = ((UserData) msg.obj).info.id;
2955 UserData userData = getUserDataNoChecks(userId);
2956 if (userData != null) {
2957 writeUserLP(userData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002958 }
2959 }
2960 }
2961 }
2962 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07002963
2964 /**
2965 * @param userId
2966 * @return whether the user has been initialized yet
2967 */
2968 boolean isInitialized(int userId) {
2969 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
2970 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07002971
2972 private class LocalService extends UserManagerInternal {
Makoto Onuki068c54a2015-10-13 14:34:03 -07002973 @Override
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002974 public void setDevicePolicyUserRestrictions(int userId, @NonNull Bundle localRestrictions,
2975 @Nullable Bundle globalRestrictions) {
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002976 UserManagerService.this.setDevicePolicyUserRestrictionsInner(userId, localRestrictions,
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002977 globalRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002978 }
2979
2980 @Override
2981 public Bundle getBaseUserRestrictions(int userId) {
2982 synchronized (mRestrictionsLock) {
2983 return mBaseUserRestrictions.get(userId);
2984 }
2985 }
2986
2987 @Override
2988 public void setBaseUserRestrictionsByDpmsForMigration(
2989 int userId, Bundle baseRestrictions) {
2990 synchronized (mRestrictionsLock) {
2991 mBaseUserRestrictions.put(userId, new Bundle(baseRestrictions));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002992 invalidateEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002993 }
2994
Amith Yamasani12747872015-12-07 14:19:49 -08002995 final UserData userData = getUserDataNoChecks(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002996 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002997 if (userData != null) {
2998 writeUserLP(userData);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002999 } else {
3000 Slog.w(LOG_TAG, "UserInfo not found for " + userId);
3001 }
3002 }
3003 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08003004
3005 @Override
3006 public boolean getUserRestriction(int userId, String key) {
3007 return getUserRestrictions(userId).getBoolean(key);
3008 }
3009
3010 @Override
3011 public void addUserRestrictionsListener(UserRestrictionsListener listener) {
3012 synchronized (mUserRestrictionsListeners) {
3013 mUserRestrictionsListeners.add(listener);
3014 }
3015 }
3016
3017 @Override
3018 public void removeUserRestrictionsListener(UserRestrictionsListener listener) {
3019 synchronized (mUserRestrictionsListeners) {
3020 mUserRestrictionsListeners.remove(listener);
3021 }
3022 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003023
3024 @Override
3025 public void setDeviceManaged(boolean isManaged) {
3026 synchronized (mUsersLock) {
3027 mIsDeviceManaged = isManaged;
3028 }
3029 }
3030
3031 @Override
3032 public void setUserManaged(int userId, boolean isManaged) {
3033 synchronized (mUsersLock) {
3034 mIsUserManaged.put(userId, isManaged);
3035 }
3036 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01003037
3038 @Override
3039 public void setUserIcon(int userId, Bitmap bitmap) {
3040 long ident = Binder.clearCallingIdentity();
3041 try {
3042 synchronized (mPackagesLock) {
3043 UserData userData = getUserDataNoChecks(userId);
3044 if (userData == null || userData.info.partial) {
3045 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
3046 return;
3047 }
3048 writeBitmapLP(userData.info, bitmap);
3049 writeUserLP(userData);
3050 }
3051 sendUserInfoChangedBroadcast(userId);
3052 } finally {
3053 Binder.restoreCallingIdentity(ident);
3054 }
3055 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01003056
3057 @Override
3058 public void setForceEphemeralUsers(boolean forceEphemeralUsers) {
3059 synchronized (mUsersLock) {
3060 mForceEphemeralUsers = forceEphemeralUsers;
3061 }
3062 }
3063
3064 @Override
3065 public void removeAllUsers() {
3066 if (UserHandle.USER_SYSTEM == ActivityManager.getCurrentUser()) {
3067 // Remove the non-system users straight away.
3068 removeNonSystemUsers();
3069 } else {
3070 // Switch to the system user first and then remove the other users.
3071 BroadcastReceiver userSwitchedReceiver = new BroadcastReceiver() {
3072 @Override
3073 public void onReceive(Context context, Intent intent) {
3074 int userId =
3075 intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3076 if (userId != UserHandle.USER_SYSTEM) {
3077 return;
3078 }
3079 mContext.unregisterReceiver(this);
3080 removeNonSystemUsers();
3081 }
3082 };
3083 IntentFilter userSwitchedFilter = new IntentFilter();
3084 userSwitchedFilter.addAction(Intent.ACTION_USER_SWITCHED);
3085 mContext.registerReceiver(
3086 userSwitchedReceiver, userSwitchedFilter, null, mHandler);
3087
3088 // Switch to the system user.
3089 ActivityManager am =
3090 (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
3091 am.switchUser(UserHandle.USER_SYSTEM);
3092 }
3093 }
phweisse9c44062016-02-10 12:57:38 +01003094
3095 @Override
Lenka Trochtova1ddda472016-02-12 10:42:12 +01003096 public void onEphemeralUserStop(int userId) {
3097 synchronized (mUsersLock) {
3098 UserInfo userInfo = getUserInfoLU(userId);
3099 if (userInfo != null && userInfo.isEphemeral()) {
3100 // Do not allow switching back to the ephemeral user again as the user is going
3101 // to be deleted.
3102 userInfo.flags |= UserInfo.FLAG_DISABLED;
3103 if (userInfo.isGuest()) {
3104 // Indicate that the guest will be deleted after it stops.
3105 userInfo.guestToRemove = true;
3106 }
3107 }
3108 }
3109 }
3110
3111 @Override
phweisse9c44062016-02-10 12:57:38 +01003112 public UserInfo createUserEvenWhenDisallowed(String name, int flags) {
3113 UserInfo user = createUserInternalUnchecked(name, flags, UserHandle.USER_NULL);
3114 // Keep this in sync with UserManager.createUser
3115 if (user != null && !user.isAdmin()) {
3116 setUserRestriction(UserManager.DISALLOW_SMS, true, user.id);
3117 setUserRestriction(UserManager.DISALLOW_OUTGOING_CALLS, true, user.id);
3118 }
3119 return user;
3120 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01003121 }
3122
3123 /* Remove all the users except of the system one. */
3124 private void removeNonSystemUsers() {
3125 ArrayList<UserInfo> usersToRemove = new ArrayList<>();
3126 synchronized (mUsersLock) {
3127 final int userSize = mUsers.size();
3128 for (int i = 0; i < userSize; i++) {
3129 UserInfo ui = mUsers.valueAt(i).info;
3130 if (ui.id != UserHandle.USER_SYSTEM) {
3131 usersToRemove.add(ui);
3132 }
3133 }
3134 }
3135 for (UserInfo ui: usersToRemove) {
3136 removeUser(ui.id);
3137 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003138 }
Todd Kennedy60459ab2015-10-30 11:32:16 -07003139
3140 private class Shell extends ShellCommand {
3141 @Override
3142 public int onCommand(String cmd) {
3143 return onShellCommand(this, cmd);
3144 }
3145
3146 @Override
3147 public void onHelp() {
3148 final PrintWriter pw = getOutPrintWriter();
3149 pw.println("User manager (user) commands:");
3150 pw.println(" help");
3151 pw.println(" Print this help text.");
3152 pw.println("");
3153 pw.println(" list");
3154 pw.println(" Prints all users on the system.");
3155 }
3156 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003157
3158 private static void debug(String message) {
3159 Log.d(LOG_TAG, message +
3160 (DBG_WITH_STACKTRACE ? " called at\n" + Debug.getCallers(10, " ") : ""));
3161 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003162}