blob: 3ff46acb5d312f94855f1766b44f2e0cbeb5c15a [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) {
Amith Yamasani4f582632014-02-19 14:31:52 -0800470 if (userId != UserHandle.getCallingUserId()) {
471 checkManageUsersPermission("getting profiles related to user " + userId);
472 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700473 final long ident = Binder.clearCallingIdentity();
474 try {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700475 synchronized (mUsersLock) {
476 return getProfilesLU(userId, enabledOnly);
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100477 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700478 } finally {
479 Binder.restoreCallingIdentity(ident);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000480 }
481 }
482
Amith Yamasanibe465322014-04-24 13:45:17 -0700483 /** Assume permissions already checked and caller's identity cleared */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700484 private List<UserInfo> getProfilesLU(int userId, boolean enabledOnly) {
485 UserInfo user = getUserInfoLU(userId);
Amith Yamasanibe465322014-04-24 13:45:17 -0700486 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasanidda003f2014-08-28 18:06:51 -0700487 if (user == null) {
488 // Probably a dying user
489 return users;
490 }
Amith Yamasani515d4062015-09-28 11:30:06 -0700491 final int userSize = mUsers.size();
492 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800493 UserInfo profile = mUsers.valueAt(i).info;
Amith Yamasanibe465322014-04-24 13:45:17 -0700494 if (!isProfileOf(user, profile)) {
495 continue;
496 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100497 if (enabledOnly && !profile.isEnabled()) {
498 continue;
Amith Yamasanibe465322014-04-24 13:45:17 -0700499 }
Amith Yamasani70fcf0c2014-07-11 08:40:19 -0700500 if (mRemovingUserIds.get(profile.id)) {
501 continue;
502 }
Amith Yamasani6f48d6e2016-03-23 14:28:25 -0700503 users.add(userWithName(profile));
Amith Yamasanibe465322014-04-24 13:45:17 -0700504 }
505 return users;
506 }
507
Jessica Hummelbe81c802014-04-22 15:49:22 +0100508 @Override
Andres Moralesc5548c02015-08-05 10:23:12 -0700509 public int getCredentialOwnerProfile(int userHandle) {
510 checkManageUsersPermission("get the credential owner");
Clara Bayarria1771112015-12-18 16:29:18 +0000511 if (!mLockPatternUtils.isSeparateProfileChallengeEnabled(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700512 synchronized (mUsersLock) {
513 UserInfo profileParent = getProfileParentLU(userHandle);
Andres Moralesc5548c02015-08-05 10:23:12 -0700514 if (profileParent != null) {
515 return profileParent.id;
516 }
517 }
518 }
519
520 return userHandle;
521 }
522
523 @Override
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700524 public boolean isSameProfileGroup(int userId, int otherUserId) {
525 if (userId == otherUserId) return true;
526 checkManageUsersPermission("check if in the same profile group");
527 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700528 return isSameProfileGroupLP(userId, otherUserId);
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700529 }
530 }
531
Fyodor Kupolov82402752015-10-28 14:54:51 -0700532 private boolean isSameProfileGroupLP(int userId, int otherUserId) {
533 synchronized (mUsersLock) {
534 UserInfo userInfo = getUserInfoLU(userId);
535 if (userInfo == null || userInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
536 return false;
537 }
538 UserInfo otherUserInfo = getUserInfoLU(otherUserId);
539 if (otherUserInfo == null
540 || otherUserInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
541 return false;
542 }
543 return userInfo.profileGroupId == otherUserInfo.profileGroupId;
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700544 }
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700545 }
546
547 @Override
Jessica Hummelbe81c802014-04-22 15:49:22 +0100548 public UserInfo getProfileParent(int userHandle) {
549 checkManageUsersPermission("get the profile parent");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700550 synchronized (mUsersLock) {
551 return getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700552 }
553 }
554
Fyodor Kupolov82402752015-10-28 14:54:51 -0700555 private UserInfo getProfileParentLU(int userHandle) {
556 UserInfo profile = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700557 if (profile == null) {
558 return null;
559 }
560 int parentUserId = profile.profileGroupId;
561 if (parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
562 return null;
563 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700564 return getUserInfoLU(parentUserId);
Jessica Hummelbe81c802014-04-22 15:49:22 +0100565 }
566 }
567
Fyodor Kupolov82402752015-10-28 14:54:51 -0700568 private static boolean isProfileOf(UserInfo user, UserInfo profile) {
Kenny Guy2a764942014-04-02 13:29:20 +0100569 return user.id == profile.id ||
570 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
571 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000572 }
573
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000574 private void broadcastProfileAvailabilityChanges(UserHandle profileHandle,
Rubin Xuf13c9802016-01-21 18:06:00 +0000575 UserHandle parentHandle, boolean inQuietMode) {
576 Intent intent = new Intent(Intent.ACTION_MANAGED_PROFILE_AVAILABILITY_CHANGED);
577 intent.putExtra(Intent.EXTRA_QUIET_MODE, inQuietMode);
578 intent.putExtra(Intent.EXTRA_USER, profileHandle);
579 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileHandle.getIdentifier());
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000580 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Rubin Xuf13c9802016-01-21 18:06:00 +0000581 mContext.sendBroadcastAsUser(intent, parentHandle);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000582 }
583
584 @Override
585 public void setQuietModeEnabled(int userHandle, boolean enableQuietMode) {
586 checkManageUsersPermission("silence profile");
587 boolean changed = false;
588 UserInfo profile, parent;
589 synchronized (mPackagesLock) {
590 synchronized (mUsersLock) {
591 profile = getUserInfoLU(userHandle);
592 parent = getProfileParentLU(userHandle);
593
594 }
595 if (profile == null || !profile.isManagedProfile()) {
596 throw new IllegalArgumentException("User " + userHandle + " is not a profile");
597 }
598 if (profile.isQuietModeEnabled() != enableQuietMode) {
599 profile.flags ^= UserInfo.FLAG_QUIET_MODE;
Amith Yamasani12747872015-12-07 14:19:49 -0800600 writeUserLP(getUserDataLU(profile.id));
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000601 changed = true;
602 }
603 }
604 if (changed) {
Rubin Xuf13c9802016-01-21 18:06:00 +0000605 long identity = Binder.clearCallingIdentity();
606 try {
607 if (enableQuietMode) {
608 ActivityManagerNative.getDefault().stopUser(userHandle, /* force */true, null);
609 } else {
610 ActivityManagerNative.getDefault().startUserInBackground(userHandle);
611 }
612 } catch (RemoteException e) {
613 Slog.e(LOG_TAG, "fail to start/stop user for quiet mode", e);
614 } finally {
615 Binder.restoreCallingIdentity(identity);
616 }
617
618 broadcastProfileAvailabilityChanges(profile.getUserHandle(), parent.getUserHandle(),
619 enableQuietMode);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000620 }
621 }
622
623 @Override
624 public boolean isQuietModeEnabled(int userHandle) {
625 synchronized (mPackagesLock) {
626 UserInfo info;
627 synchronized (mUsersLock) {
628 info = getUserInfoLU(userHandle);
629 }
630 if (info == null || !info.isManagedProfile()) {
Rubin Xuf13c9802016-01-21 18:06:00 +0000631 return false;
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000632 }
633 return info.isQuietModeEnabled();
634 }
635 }
636
Kenny Guya52dc3e2014-02-11 15:33:14 +0000637 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100638 public void setUserEnabled(int userId) {
639 checkManageUsersPermission("enable user");
640 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700641 UserInfo info;
642 synchronized (mUsersLock) {
643 info = getUserInfoLU(userId);
644 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100645 if (info != null && !info.isEnabled()) {
646 info.flags ^= UserInfo.FLAG_DISABLED;
Amith Yamasani12747872015-12-07 14:19:49 -0800647 writeUserLP(getUserDataLU(info.id));
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100648 }
649 }
650 }
651
652 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700653 public UserInfo getUserInfo(int userId) {
Tony Mak8673b282016-03-21 21:10:59 +0000654 checkManageUsersPermission("query user");
655 synchronized (mUsersLock) {
Amith Yamasani6f48d6e2016-03-23 14:28:25 -0700656 return userWithName(getUserInfoLU(userId));
657 }
658 }
659
660 /**
661 * Returns a UserInfo object with the name filled in, for Owner, or the original
662 * if the name is already set.
663 */
664 private UserInfo userWithName(UserInfo orig) {
665 if (orig != null && orig.name == null && orig.id == UserHandle.USER_SYSTEM) {
666 UserInfo withName = new UserInfo(orig);
667 withName.name = getOwnerName();
668 return withName;
669 } else {
670 return orig;
Tony Mak8673b282016-03-21 21:10:59 +0000671 }
672 }
673
674 @Override
675 public boolean isManagedProfile(int userId) {
Tony Makb531d082016-03-16 14:49:52 +0000676 int callingUserId = UserHandle.getCallingUserId();
677 if (callingUserId != userId && !hasManageUsersPermission()) {
678 synchronized (mPackagesLock) {
679 if (!isSameProfileGroupLP(callingUserId, userId)) {
680 throw new SecurityException(
Tony Mak8673b282016-03-21 21:10:59 +0000681 "You need MANAGE_USERS permission to: check if specified user a " +
682 "managed profile outside your profile group");
Tony Makb531d082016-03-16 14:49:52 +0000683 }
684 }
Tony Mak4dc008c2016-03-16 10:46:49 +0000685 }
Fyodor Kupolov82402752015-10-28 14:54:51 -0700686 synchronized (mUsersLock) {
Tony Mak8673b282016-03-21 21:10:59 +0000687 UserInfo userInfo = getUserInfoLU(userId);
688 return userInfo != null && userInfo.isManagedProfile();
Amith Yamasani13593602012-03-22 16:16:17 -0700689 }
690 }
691
Amith Yamasani71e6c692013-03-24 17:39:28 -0700692 @Override
693 public boolean isRestricted() {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700694 synchronized (mUsersLock) {
695 return getUserInfoLU(UserHandle.getCallingUserId()).isRestricted();
Amith Yamasani71e6c692013-03-24 17:39:28 -0700696 }
697 }
698
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700699 @Override
700 public boolean canHaveRestrictedProfile(int userId) {
701 checkManageUsersPermission("canHaveRestrictedProfile");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700702 synchronized (mUsersLock) {
703 final UserInfo userInfo = getUserInfoLU(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700704 if (userInfo == null || !userInfo.canHaveProfile()) {
705 return false;
706 }
707 if (!userInfo.isAdmin()) {
708 return false;
709 }
Makoto Onukie7927da2015-11-25 10:05:17 -0800710 // restricted profile can be created if there is no DO set and the admin user has no PO;
711 return !mIsDeviceManaged && !mIsUserManaged.get(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700712 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700713 }
714
Amith Yamasani195263742012-08-21 15:40:12 -0700715 /*
716 * Should be locked on mUsers before calling this.
717 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700718 private UserInfo getUserInfoLU(int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -0800719 final UserData userData = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -0700720 // If it is partial and not in the process of being removed, return as unknown user.
Amith Yamasani12747872015-12-07 14:19:49 -0800721 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700722 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
723 return null;
724 }
Amith Yamasani12747872015-12-07 14:19:49 -0800725 return userData != null ? userData.info : null;
726 }
727
728 private UserData getUserDataLU(int userId) {
729 final UserData userData = mUsers.get(userId);
730 // If it is partial and not in the process of being removed, return as unknown user.
731 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
732 return null;
733 }
734 return userData;
Amith Yamasani195263742012-08-21 15:40:12 -0700735 }
736
Fyodor Kupolov82402752015-10-28 14:54:51 -0700737 /**
738 * Obtains {@link #mUsersLock} and return UserInfo from mUsers.
739 * <p>No permissions checking or any addition checks are made</p>
740 */
741 private UserInfo getUserInfoNoChecks(int userId) {
742 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800743 final UserData userData = mUsers.get(userId);
744 return userData != null ? userData.info : null;
745 }
746 }
747
748 /**
749 * Obtains {@link #mUsersLock} and return UserData from mUsers.
750 * <p>No permissions checking or any addition checks are made</p>
751 */
752 private UserData getUserDataNoChecks(int userId) {
753 synchronized (mUsersLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700754 return mUsers.get(userId);
755 }
756 }
757
Amith Yamasani236b2b52015-08-18 14:32:14 -0700758 /** Called by PackageManagerService */
Amith Yamasani13593602012-03-22 16:16:17 -0700759 public boolean exists(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700760 return getUserInfoNoChecks(userId) != null;
Amith Yamasani13593602012-03-22 16:16:17 -0700761 }
762
Amith Yamasani258848d2012-08-10 17:06:33 -0700763 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700764 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700765 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700766 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700767 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800768 UserData userData = getUserDataNoChecks(userId);
769 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700770 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
771 return;
772 }
Amith Yamasani12747872015-12-07 14:19:49 -0800773 if (name != null && !name.equals(userData.info.name)) {
774 userData.info.name = name;
775 writeUserLP(userData);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700776 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -0700777 }
778 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700779 if (changed) {
780 sendUserInfoChangedBroadcast(userId);
781 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700782 }
783
Amith Yamasani258848d2012-08-10 17:06:33 -0700784 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700785 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700786 checkManageUsersPermission("update users");
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +0100787 if (hasUserRestriction(UserManager.DISALLOW_SET_USER_ICON, userId)) {
788 Log.w(LOG_TAG, "Cannot set user icon. DISALLOW_SET_USER_ICON is enabled.");
789 return;
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700790 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +0100791 mLocalService.setUserIcon(userId, bitmap);
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700792 }
793
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +0100794
795
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700796 private void sendUserInfoChangedBroadcast(int userId) {
797 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
798 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
799 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -0700800 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700801 }
802
Amith Yamasani258848d2012-08-10 17:06:33 -0700803 @Override
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +0100804 public ParcelFileDescriptor getUserIcon(int targetUserId) {
Adrian Roos1bdff912015-02-17 15:51:35 +0100805 String iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700806 synchronized (mPackagesLock) {
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +0100807 UserInfo targetUserInfo = getUserInfoNoChecks(targetUserId);
808 if (targetUserInfo == null || targetUserInfo.partial) {
809 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + targetUserId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700810 return null;
811 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +0100812
813 final int callingUserId = UserHandle.getCallingUserId();
814 final int callingGroupId = getUserInfoNoChecks(callingUserId).profileGroupId;
815 final int targetGroupId = targetUserInfo.profileGroupId;
816 final boolean sameGroup = (callingGroupId != UserInfo.NO_PROFILE_GROUP_ID
817 && callingGroupId == targetGroupId);
818 if ((callingUserId != targetUserId) && !sameGroup) {
Nicolas Prevot88cc3462014-05-14 14:51:48 +0100819 checkManageUsersPermission("get the icon of a user who is not related");
820 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +0100821
822 if (targetUserInfo.iconPath == null) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700823 return null;
824 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +0100825 iconPath = targetUserInfo.iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700826 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100827
828 try {
829 return ParcelFileDescriptor.open(
830 new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
831 } catch (FileNotFoundException e) {
832 Log.e(LOG_TAG, "Couldn't find icon file", e);
833 }
834 return null;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700835 }
836
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700837 public void makeInitialized(int userId) {
838 checkManageUsersPermission("makeInitialized");
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800839 boolean scheduleWriteUser = false;
Amith Yamasani12747872015-12-07 14:19:49 -0800840 UserData userData;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800841 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800842 userData = mUsers.get(userId);
843 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700844 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800845 return;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700846 }
Amith Yamasani12747872015-12-07 14:19:49 -0800847 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
848 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800849 scheduleWriteUser = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700850 }
851 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800852 if (scheduleWriteUser) {
Amith Yamasani12747872015-12-07 14:19:49 -0800853 scheduleWriteUser(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800854 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700855 }
856
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700857 /**
858 * If default guest restrictions haven't been initialized yet, add the basic
859 * restrictions.
860 */
861 private void initDefaultGuestRestrictions() {
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800862 synchronized (mGuestRestrictions) {
863 if (mGuestRestrictions.isEmpty()) {
Samuel Tand9453b82016-03-14 15:57:02 -0700864 mGuestRestrictions.putBoolean(UserManager.DISALLOW_CONFIG_WIFI, true);
Fyodor Kupolove04462c2015-11-30 15:02:53 -0800865 mGuestRestrictions.putBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, true);
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800866 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
867 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
868 }
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700869 }
870 }
871
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800872 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530873 public Bundle getDefaultGuestRestrictions() {
874 checkManageUsersPermission("getDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800875 synchronized (mGuestRestrictions) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530876 return new Bundle(mGuestRestrictions);
877 }
878 }
879
880 @Override
881 public void setDefaultGuestRestrictions(Bundle restrictions) {
882 checkManageUsersPermission("setDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800883 synchronized (mGuestRestrictions) {
884 mGuestRestrictions.clear();
885 mGuestRestrictions.putAll(restrictions);
886 }
887 synchronized (mPackagesLock) {
888 writeUserListLP();
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530889 }
890 }
891
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800892 /**
893 * See {@link UserManagerInternal#setDevicePolicyUserRestrictions(int, Bundle, Bundle)}
894 */
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800895 void setDevicePolicyUserRestrictionsInner(int userId, @NonNull Bundle local,
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800896 @Nullable Bundle global) {
897 Preconditions.checkNotNull(local);
898 boolean globalChanged = false;
899 boolean localChanged;
900 synchronized (mRestrictionsLock) {
901 if (global != null) {
902 // Update global.
903 globalChanged = !UserRestrictionsUtils.areEqual(
904 mDevicePolicyGlobalUserRestrictions, global);
905 if (globalChanged) {
906 mDevicePolicyGlobalUserRestrictions = global;
907 }
908 }
909 {
910 // Update local.
911 final Bundle prev = mDevicePolicyLocalUserRestrictions.get(userId);
912 localChanged = !UserRestrictionsUtils.areEqual(prev, local);
913 if (localChanged) {
914 mDevicePolicyLocalUserRestrictions.put(userId, local);
915 }
916 }
917 }
918 if (DBG) {
919 Log.d(LOG_TAG, "setDevicePolicyUserRestrictions: userId=" + userId
920 + " global=" + global + (globalChanged ? " (changed)" : "")
921 + " local=" + local + (localChanged ? " (changed)" : "")
922 );
923 }
924 // Don't call them within the mRestrictionsLock.
925 synchronized (mPackagesLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800926 if (localChanged) {
Amith Yamasani12747872015-12-07 14:19:49 -0800927 writeUserLP(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800928 }
Jeff Sharkeycd575992016-03-29 14:12:49 -0600929 if (globalChanged) {
930 writeUserListLP();
931 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800932 }
933
934 synchronized (mRestrictionsLock) {
935 if (globalChanged) {
936 applyUserRestrictionsForAllUsersLR();
937 } else if (localChanged) {
938 applyUserRestrictionsLR(userId);
939 }
940 }
941 }
942
Makoto Onuki068c54a2015-10-13 14:34:03 -0700943 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -0700944 private Bundle computeEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800945 final Bundle baseRestrictions =
946 UserRestrictionsUtils.nonNull(mBaseUserRestrictions.get(userId));
947 final Bundle global = mDevicePolicyGlobalUserRestrictions;
948 final Bundle local = mDevicePolicyLocalUserRestrictions.get(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700949
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800950 if (UserRestrictionsUtils.isEmpty(global) && UserRestrictionsUtils.isEmpty(local)) {
951 // Common case first.
952 return baseRestrictions;
Makoto Onuki068c54a2015-10-13 14:34:03 -0700953 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800954 final Bundle effective = UserRestrictionsUtils.clone(baseRestrictions);
955 UserRestrictionsUtils.merge(effective, global);
956 UserRestrictionsUtils.merge(effective, local);
957
Makoto Onuki068c54a2015-10-13 14:34:03 -0700958 return effective;
959 }
960
961 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -0700962 private void invalidateEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki068c54a2015-10-13 14:34:03 -0700963 if (DBG) {
964 Log.d(LOG_TAG, "invalidateEffectiveUserRestrictions userId=" + userId);
965 }
966 mCachedEffectiveUserRestrictions.remove(userId);
967 }
968
969 private Bundle getEffectiveUserRestrictions(int userId) {
970 synchronized (mRestrictionsLock) {
971 Bundle restrictions = mCachedEffectiveUserRestrictions.get(userId);
972 if (restrictions == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700973 restrictions = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700974 mCachedEffectiveUserRestrictions.put(userId, restrictions);
975 }
976 return restrictions;
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700977 }
978 }
979
Makoto Onuki068c54a2015-10-13 14:34:03 -0700980 /** @return a specific user restriction that's in effect currently. */
981 @Override
982 public boolean hasUserRestriction(String restrictionKey, int userId) {
Makoto Onuki1f1ceef2016-01-28 11:32:32 -0800983 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
984 return false;
985 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700986 Bundle restrictions = getEffectiveUserRestrictions(userId);
987 return restrictions != null && restrictions.getBoolean(restrictionKey);
988 }
989
990 /**
991 * @return UserRestrictions that are in effect currently. This always returns a new
992 * {@link Bundle}.
993 */
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700994 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800995 public Bundle getUserRestrictions(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800996 return UserRestrictionsUtils.clone(getEffectiveUserRestrictions(userId));
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800997 }
998
999 @Override
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +00001000 public boolean hasBaseUserRestriction(String restrictionKey, int userId) {
1001 checkManageUsersPermission("hasBaseUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001002 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1003 return false;
1004 }
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +00001005 synchronized (mRestrictionsLock) {
1006 Bundle bundle = mBaseUserRestrictions.get(userId);
1007 return (bundle != null && bundle.getBoolean(restrictionKey, false));
1008 }
1009 }
1010
1011 @Override
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001012 public void setUserRestriction(String key, boolean value, int userId) {
Fyodor Kupolovd4b26042015-07-27 14:30:59 -07001013 checkManageUsersPermission("setUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001014 if (!UserRestrictionsUtils.isValidRestriction(key)) {
1015 return;
1016 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001017 synchronized (mRestrictionsLock) {
1018 // Note we can't modify Bundles stored in mBaseUserRestrictions directly, so create
1019 // a copy.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001020 final Bundle newRestrictions = UserRestrictionsUtils.clone(
1021 mBaseUserRestrictions.get(userId));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001022 newRestrictions.putBoolean(key, value);
1023
Fyodor Kupolov82402752015-10-28 14:54:51 -07001024 updateUserRestrictionsInternalLR(newRestrictions, userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001025 }
1026 }
1027
Makoto Onuki068c54a2015-10-13 14:34:03 -07001028 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001029 * Optionally updating user restrictions, calculate the effective user restrictions and also
1030 * propagate to other services and system settings.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001031 *
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001032 * @param newRestrictions User restrictions to set.
1033 * If null, will not update user restrictions and only does the propagation.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001034 * @param userId target user ID.
1035 */
1036 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001037 private void updateUserRestrictionsInternalLR(
Makoto Onuki068c54a2015-10-13 14:34:03 -07001038 @Nullable Bundle newRestrictions, int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001039
1040 final Bundle prevAppliedRestrictions = UserRestrictionsUtils.nonNull(
1041 mAppliedUserRestrictions.get(userId));
1042
1043 // Update base restrictions.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001044 if (newRestrictions != null) {
1045 // If newRestrictions == the current one, it's probably a bug.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001046 final Bundle prevBaseRestrictions = mBaseUserRestrictions.get(userId);
1047
1048 Preconditions.checkState(prevBaseRestrictions != newRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001049 Preconditions.checkState(mCachedEffectiveUserRestrictions.get(userId)
1050 != newRestrictions);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001051
1052 if (!UserRestrictionsUtils.areEqual(prevBaseRestrictions, newRestrictions)) {
1053 mBaseUserRestrictions.put(userId, newRestrictions);
Amith Yamasani12747872015-12-07 14:19:49 -08001054 scheduleWriteUser(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001055 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001056 }
1057
Fyodor Kupolov82402752015-10-28 14:54:51 -07001058 final Bundle effective = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001059
Makoto Onuki759a7632015-10-28 16:43:10 -07001060 mCachedEffectiveUserRestrictions.put(userId, effective);
1061
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001062 // Apply the new restrictions.
Makoto Onuki4f160732015-10-27 17:15:38 -07001063 if (DBG) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001064 debug("Applying user restrictions: userId=" + userId
1065 + " new=" + effective + " prev=" + prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001066 }
1067
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001068 if (mAppOpsService != null) { // We skip it until system-ready.
1069 final long token = Binder.clearCallingIdentity();
1070 try {
Svet Ganov9cea80cd2016-02-16 11:47:00 -08001071 mAppOpsService.setUserRestrictions(effective, mUserRestriconToken, userId);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001072 } catch (RemoteException e) {
1073 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
1074 } finally {
1075 Binder.restoreCallingIdentity(token);
1076 }
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001077 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001078
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001079 propagateUserRestrictionsLR(userId, effective, prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001080
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001081 mAppliedUserRestrictions.put(userId, new Bundle(effective));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001082 }
1083
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001084 private void propagateUserRestrictionsLR(final int userId,
Makoto Onukid45a4a22015-11-02 17:17:38 -08001085 Bundle newRestrictions, Bundle prevRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001086 // Note this method doesn't touch any state, meaning it doesn't require mRestrictionsLock
1087 // actually, but we still need some kind of synchronization otherwise we might end up
1088 // calling listeners out-of-order, thus "LR".
1089
1090 if (UserRestrictionsUtils.areEqual(newRestrictions, prevRestrictions)) {
1091 return;
1092 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08001093
1094 final Bundle newRestrictionsFinal = new Bundle(newRestrictions);
1095 final Bundle prevRestrictionsFinal = new Bundle(prevRestrictions);
1096
1097 mHandler.post(new Runnable() {
1098 @Override
1099 public void run() {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07001100 UserRestrictionsUtils.applyUserRestrictions(
1101 mContext, userId, newRestrictionsFinal, prevRestrictionsFinal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001102
Makoto Onukid45a4a22015-11-02 17:17:38 -08001103 final UserRestrictionsListener[] listeners;
1104 synchronized (mUserRestrictionsListeners) {
1105 listeners = new UserRestrictionsListener[mUserRestrictionsListeners.size()];
1106 mUserRestrictionsListeners.toArray(listeners);
1107 }
1108 for (int i = 0; i < listeners.length; i++) {
1109 listeners[i].onUserRestrictionsChanged(userId,
1110 newRestrictionsFinal, prevRestrictionsFinal);
1111 }
1112 }
1113 });
1114 }
1115
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001116 // Package private for the inner class.
1117 void applyUserRestrictionsLR(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001118 updateUserRestrictionsInternalLR(null, userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001119 }
1120
1121 @GuardedBy("mRestrictionsLock")
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001122 // Package private for the inner class.
1123 void applyUserRestrictionsForAllUsersLR() {
1124 if (DBG) {
1125 debug("applyUserRestrictionsForAllUsersLR");
1126 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001127 // First, invalidate all cached values.
Makoto Onuki4f160732015-10-27 17:15:38 -07001128 mCachedEffectiveUserRestrictions.clear();
1129
Makoto Onuki068c54a2015-10-13 14:34:03 -07001130 // We don't want to call into ActivityManagerNative while taking a lock, so we'll call
1131 // it on a handler.
1132 final Runnable r = new Runnable() {
1133 @Override
1134 public void run() {
1135 // Then get the list of running users.
1136 final int[] runningUsers;
1137 try {
1138 runningUsers = ActivityManagerNative.getDefault().getRunningUserIds();
1139 } catch (RemoteException e) {
1140 Log.w(LOG_TAG, "Unable to access ActivityManagerNative");
1141 return;
1142 }
1143 // Then re-calculate the effective restrictions and apply, only for running users.
1144 // It's okay if a new user has started after the getRunningUserIds() call,
1145 // because we'll do the same thing (re-calculate the restrictions and apply)
1146 // when we start a user.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001147 synchronized (mRestrictionsLock) {
1148 for (int i = 0; i < runningUsers.length; i++) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001149 applyUserRestrictionsLR(runningUsers[i]);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001150 }
1151 }
1152 }
1153 };
1154 mHandler.post(r);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001155 }
1156
Amith Yamasani258848d2012-08-10 17:06:33 -07001157 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001158 * Check if we've hit the limit of how many users can be created.
1159 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001160 private boolean isUserLimitReached() {
1161 int count;
1162 synchronized (mUsersLock) {
1163 count = getAliveUsersExcludingGuestsCountLU();
1164 }
1165 return count >= UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001166 }
1167
1168 @Override
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001169 public boolean canAddMoreManagedProfiles(int userId, boolean allowedToRemoveOne) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001170 checkManageUsersPermission("check if more managed profiles can be added.");
1171 if (ActivityManager.isLowRamDeviceStatic()) {
1172 return false;
1173 }
Fyodor Kupolovb6157992015-06-05 15:32:28 -07001174 if (!mContext.getPackageManager().hasSystemFeature(
1175 PackageManager.FEATURE_MANAGED_USERS)) {
1176 return false;
1177 }
Nicolas Prevotb8186812015-08-06 15:00:03 +01001178 // Limit number of managed profiles that can be created
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001179 final int managedProfilesCount = getProfiles(userId, true).size() - 1;
1180 final int profilesRemovedCount = managedProfilesCount > 0 && allowedToRemoveOne ? 1 : 0;
1181 if (managedProfilesCount - profilesRemovedCount >= MAX_MANAGED_PROFILES) {
Nicolas Prevotb8186812015-08-06 15:00:03 +01001182 return false;
1183 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001184 synchronized(mUsersLock) {
1185 UserInfo userInfo = getUserInfoLU(userId);
Nicolas Prevotb8186812015-08-06 15:00:03 +01001186 if (!userInfo.canHaveProfile()) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001187 return false;
1188 }
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001189 int usersCountAfterRemoving = getAliveUsersExcludingGuestsCountLU()
1190 - profilesRemovedCount;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001191 // We allow creating a managed profile in the special case where there is only one user.
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001192 return usersCountAfterRemoving == 1
1193 || usersCountAfterRemoving < UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001194 }
1195 }
1196
Fyodor Kupolov82402752015-10-28 14:54:51 -07001197 private int getAliveUsersExcludingGuestsCountLU() {
Amith Yamasanif584f012014-05-19 17:57:25 -07001198 int aliveUserCount = 0;
1199 final int totalUserCount = mUsers.size();
1200 // Skip over users being removed
1201 for (int i = 0; i < totalUserCount; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001202 UserInfo user = mUsers.valueAt(i).info;
Amith Yamasani95ab7842014-08-11 17:09:26 -07001203 if (!mRemovingUserIds.get(user.id)
Amith Yamasani1df14732014-08-29 21:37:27 -07001204 && !user.isGuest() && !user.partial) {
Amith Yamasanif584f012014-05-19 17:57:25 -07001205 aliveUserCount++;
1206 }
1207 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001208 return aliveUserCount;
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001209 }
1210
1211 /**
Amith Yamasani195263742012-08-21 15:40:12 -07001212 * Enforces that only the system UID or root's UID or apps that have the
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001213 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} and
1214 * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL INTERACT_ACROSS_USERS_FULL}
1215 * permissions can make certain calls to the UserManager.
1216 *
1217 * @param message used as message if SecurityException is thrown
1218 * @throws SecurityException if the caller does not have enough privilege.
1219 */
1220 private static final void checkManageUserAndAcrossUsersFullPermission(String message) {
1221 final int uid = Binder.getCallingUid();
1222 if (uid != Process.SYSTEM_UID && uid != 0
1223 && ActivityManager.checkComponentPermission(
1224 Manifest.permission.MANAGE_USERS,
1225 uid, -1, true) != PackageManager.PERMISSION_GRANTED
1226 && ActivityManager.checkComponentPermission(
1227 Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1228 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
1229 throw new SecurityException(
1230 "You need MANAGE_USERS and INTERACT_ACROSS_USERS_FULL permission to: "
1231 + message);
1232 }
1233 }
1234
1235 /**
1236 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001237 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -07001238 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -07001239 *
1240 * @param message used as message if SecurityException is thrown
1241 * @throws SecurityException if the caller is not system or root
Tony Mak4dc008c2016-03-16 10:46:49 +00001242 * @see #hasManageUsersPermission()
Amith Yamasani258848d2012-08-10 17:06:33 -07001243 */
Amith Yamasanibe465322014-04-24 13:45:17 -07001244 private static final void checkManageUsersPermission(String message) {
Tony Mak4dc008c2016-03-16 10:46:49 +00001245 if (!hasManageUsersPermission()) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001246 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
1247 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -04001248 }
1249
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001250 /**
Tony Mak4dc008c2016-03-16 10:46:49 +00001251 * @return whether the calling UID is system UID or root's UID or the calling app has the
1252 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}.
1253 */
1254 private static final boolean hasManageUsersPermission() {
1255 final int callingUid = Binder.getCallingUid();
1256 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
1257 || callingUid == Process.ROOT_UID
1258 || ActivityManager.checkComponentPermission(
1259 android.Manifest.permission.MANAGE_USERS,
1260 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED;
1261 }
1262
1263 /**
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001264 * Enforces that only the system UID or root's UID (on any user) can make certain calls to the
1265 * UserManager.
1266 *
1267 * @param message used as message if SecurityException is thrown
1268 * @throws SecurityException if the caller is not system or root
1269 */
1270 private static void checkSystemOrRoot(String message) {
1271 final int uid = Binder.getCallingUid();
1272 if (!UserHandle.isSameApp(uid, Process.SYSTEM_UID) && uid != Process.ROOT_UID) {
1273 throw new SecurityException("Only system may: " + message);
1274 }
1275 }
1276
Fyodor Kupolov82402752015-10-28 14:54:51 -07001277 private void writeBitmapLP(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001278 try {
1279 File dir = new File(mUsersDir, Integer.toString(info.id));
1280 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +01001281 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001282 if (!dir.exists()) {
1283 dir.mkdir();
1284 FileUtils.setPermissions(
1285 dir.getPath(),
1286 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
1287 -1, -1);
1288 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001289 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +01001290 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001291 && tmp.renameTo(file) && SELinux.restorecon(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -07001292 info.iconPath = file.getAbsolutePath();
1293 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001294 try {
1295 os.close();
1296 } catch (IOException ioe) {
1297 // What the ... !
1298 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001299 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001300 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001301 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001302 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001303 }
1304
Amith Yamasani0b285492011-04-14 17:35:23 -07001305 /**
1306 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
1307 * cache it elsewhere.
1308 * @return the array of user ids.
1309 */
Dianne Hackborn1676c852012-09-10 14:52:30 -07001310 public int[] getUserIds() {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001311 synchronized (mUsersLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001312 return mUserIds;
1313 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001314 }
1315
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001316 private void readUserListLP() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001317 if (!mUserListFile.exists()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001318 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001319 return;
1320 }
1321 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001322 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001323 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001324 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001325 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001326 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001327 int type;
1328 while ((type = parser.next()) != XmlPullParser.START_TAG
1329 && type != XmlPullParser.END_DOCUMENT) {
Amith Yamasani12747872015-12-07 14:19:49 -08001330 // Skip
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001331 }
1332
1333 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001334 Slog.e(LOG_TAG, "Unable to read user list");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001335 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001336 return;
1337 }
1338
Amith Yamasani2a003292012-08-14 18:25:45 -07001339 mNextSerialNumber = -1;
1340 if (parser.getName().equals(TAG_USERS)) {
1341 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
1342 if (lastSerialNumber != null) {
1343 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
1344 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001345 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
1346 if (versionNumber != null) {
1347 mUserVersion = Integer.parseInt(versionNumber);
1348 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001349 }
1350
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001351 final Bundle newDevicePolicyGlobalUserRestrictions = new Bundle();
1352
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001353 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301354 if (type == XmlPullParser.START_TAG) {
1355 final String name = parser.getName();
1356 if (name.equals(TAG_USER)) {
1357 String id = parser.getAttributeValue(null, ATTR_ID);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001358
Amith Yamasani12747872015-12-07 14:19:49 -08001359 UserData userData = readUserLP(Integer.parseInt(id));
1360
1361 if (userData != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001362 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001363 mUsers.put(userData.info.id, userData);
1364 if (mNextSerialNumber < 0
1365 || mNextSerialNumber <= userData.info.id) {
1366 mNextSerialNumber = userData.info.id + 1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001367 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301368 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001369 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301370 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -08001371 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1372 && type != XmlPullParser.END_TAG) {
1373 if (type == XmlPullParser.START_TAG) {
1374 if (parser.getName().equals(TAG_RESTRICTIONS)) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001375 synchronized (mGuestRestrictions) {
1376 UserRestrictionsUtils
1377 .readRestrictions(parser, mGuestRestrictions);
1378 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001379 } else if (parser.getName().equals(TAG_DEVICE_POLICY_RESTRICTIONS)
1380 ) {
1381 UserRestrictionsUtils.readRestrictions(parser,
1382 newDevicePolicyGlobalUserRestrictions);
Amith Yamasanida0b1682014-11-21 12:58:17 -08001383 }
1384 break;
1385 }
1386 }
Amith Yamasani258848d2012-08-10 17:06:33 -07001387 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001388 }
1389 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001390 synchronized (mRestrictionsLock) {
1391 mDevicePolicyGlobalUserRestrictions = newDevicePolicyGlobalUserRestrictions;
1392 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001393 updateUserIds();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001394 upgradeIfNecessaryLP();
1395 } catch (IOException | XmlPullParserException e) {
1396 fallbackToSingleUserLP();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001397 } finally {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001398 IoUtils.closeQuietly(fis);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001399 }
1400 }
1401
Amith Yamasani6f34b412012-10-22 18:19:27 -07001402 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -08001403 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -07001404 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001405 private void upgradeIfNecessaryLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001406 final int originalVersion = mUserVersion;
Amith Yamasani6f34b412012-10-22 18:19:27 -07001407 int userVersion = mUserVersion;
1408 if (userVersion < 1) {
1409 // Assign a proper name for the owner, if not initialized correctly before
Amith Yamasani12747872015-12-07 14:19:49 -08001410 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
1411 if ("Primary".equals(userData.info.name)) {
1412 userData.info.name =
1413 mContext.getResources().getString(com.android.internal.R.string.owner_name);
1414 scheduleWriteUser(userData);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001415 }
1416 userVersion = 1;
1417 }
1418
Amith Yamasanibc9625052012-11-15 14:39:18 -08001419 if (userVersion < 2) {
1420 // Owner should be marked as initialized
Amith Yamasani12747872015-12-07 14:19:49 -08001421 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
1422 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1423 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
1424 scheduleWriteUser(userData);
Amith Yamasanibc9625052012-11-15 14:39:18 -08001425 }
1426 userVersion = 2;
1427 }
1428
Amith Yamasani350962c2013-08-06 11:18:53 -07001429
Amith Yamasani5e486f52013-08-07 11:06:44 -07001430 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -07001431 userVersion = 4;
1432 }
1433
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001434 if (userVersion < 5) {
1435 initDefaultGuestRestrictions();
1436 userVersion = 5;
1437 }
1438
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001439 if (userVersion < 6) {
1440 final boolean splitSystemUser = UserManager.isSplitSystemUser();
Fyodor Kupolov82402752015-10-28 14:54:51 -07001441 synchronized (mUsersLock) {
1442 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001443 UserData userData = mUsers.valueAt(i);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001444 // In non-split mode, only user 0 can have restricted profiles
Amith Yamasani12747872015-12-07 14:19:49 -08001445 if (!splitSystemUser && userData.info.isRestricted()
1446 && (userData.info.restrictedProfileParentId
1447 == UserInfo.NO_PROFILE_GROUP_ID)) {
1448 userData.info.restrictedProfileParentId = UserHandle.USER_SYSTEM;
1449 scheduleWriteUser(userData);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001450 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001451 }
1452 }
1453 userVersion = 6;
1454 }
1455
Amith Yamasani6f34b412012-10-22 18:19:27 -07001456 if (userVersion < USER_VERSION) {
1457 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
1458 + USER_VERSION);
1459 } else {
1460 mUserVersion = userVersion;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001461
1462 if (originalVersion < mUserVersion) {
1463 writeUserListLP();
1464 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001465 }
1466 }
1467
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001468 private void fallbackToSingleUserLP() {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001469 int flags = UserInfo.FLAG_INITIALIZED;
1470 // In split system user mode, the admin and primary flags are assigned to the first human
1471 // user.
1472 if (!UserManager.isSplitSystemUser()) {
1473 flags |= UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY;
1474 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001475 // Create the system user
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001476 UserInfo system = new UserInfo(UserHandle.USER_SYSTEM, null, null, flags);
Amith Yamasani12747872015-12-07 14:19:49 -08001477 UserData userData = new UserData();
1478 userData.info = system;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001479 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001480 mUsers.put(system.id, userData);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001481 }
Amith Yamasani634cf312012-10-04 17:34:21 -07001482 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -04001483 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -08001484
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001485 Bundle restrictions = new Bundle();
Makoto Onuki068c54a2015-10-13 14:34:03 -07001486 synchronized (mRestrictionsLock) {
1487 mBaseUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions);
1488 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001489
Fyodor Kupolov82402752015-10-28 14:54:51 -07001490 updateUserIds();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001491 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001492
Amith Yamasani12747872015-12-07 14:19:49 -08001493 writeUserLP(userData);
Jeff Sharkeycd575992016-03-29 14:12:49 -06001494 writeUserListLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001495 }
1496
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001497 private String getOwnerName() {
1498 return mContext.getResources().getString(com.android.internal.R.string.owner_name);
1499 }
1500
Amith Yamasani12747872015-12-07 14:19:49 -08001501 private void scheduleWriteUser(UserData UserData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001502 if (DBG) {
1503 debug("scheduleWriteUser");
1504 }
Makoto Onuki9e935a32015-11-06 14:24:24 -08001505 // No need to wrap it within a lock -- worst case, we'll just post the same message
1506 // twice.
Amith Yamasani12747872015-12-07 14:19:49 -08001507 if (!mHandler.hasMessages(WRITE_USER_MSG, UserData)) {
1508 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, UserData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001509 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
1510 }
1511 }
1512
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001513 /*
1514 * Writes the user file in this format:
1515 *
1516 * <user flags="20039023" id="0">
1517 * <name>Primary</name>
1518 * </user>
1519 */
Amith Yamasani12747872015-12-07 14:19:49 -08001520 private void writeUserLP(UserData userData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001521 if (DBG) {
Amith Yamasani12747872015-12-07 14:19:49 -08001522 debug("writeUserLP " + userData);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001523 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001524 FileOutputStream fos = null;
Amith Yamasani12747872015-12-07 14:19:49 -08001525 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userData.info.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001526 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001527 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001528 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1529
1530 // XmlSerializer serializer = XmlUtils.serializerInstance();
1531 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001532 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001533 serializer.startDocument(null, true);
1534 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1535
Amith Yamasani12747872015-12-07 14:19:49 -08001536 final UserInfo userInfo = userData.info;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001537 serializer.startTag(null, TAG_USER);
1538 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
Amith Yamasani2a003292012-08-14 18:25:45 -07001539 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001540 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Amith Yamasani920ace02012-09-20 22:15:37 -07001541 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
1542 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
1543 Long.toString(userInfo.lastLoggedInTime));
Jeff Sharkeycd575992016-03-29 14:12:49 -06001544 if (userInfo.lastLoggedInFingerprint != null) {
1545 serializer.attribute(null, ATTR_LAST_LOGGED_IN_FINGERPRINT,
1546 userInfo.lastLoggedInFingerprint);
1547 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001548 if (userInfo.iconPath != null) {
1549 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
1550 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001551 if (userInfo.partial) {
1552 serializer.attribute(null, ATTR_PARTIAL, "true");
1553 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001554 if (userInfo.guestToRemove) {
1555 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
1556 }
Kenny Guy2a764942014-04-02 13:29:20 +01001557 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
1558 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
1559 Integer.toString(userInfo.profileGroupId));
Kenny Guya52dc3e2014-02-11 15:33:14 +00001560 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001561 if (userInfo.restrictedProfileParentId != UserInfo.NO_PROFILE_GROUP_ID) {
1562 serializer.attribute(null, ATTR_RESTRICTED_PROFILE_PARENT_ID,
1563 Integer.toString(userInfo.restrictedProfileParentId));
1564 }
Amith Yamasani12747872015-12-07 14:19:49 -08001565 // Write seed data
1566 if (userData.persistSeedData) {
1567 if (userData.seedAccountName != null) {
1568 serializer.attribute(null, ATTR_SEED_ACCOUNT_NAME, userData.seedAccountName);
1569 }
1570 if (userData.seedAccountType != null) {
1571 serializer.attribute(null, ATTR_SEED_ACCOUNT_TYPE, userData.seedAccountType);
1572 }
1573 }
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001574 if (userInfo.name != null) {
1575 serializer.startTag(null, TAG_NAME);
1576 serializer.text(userInfo.name);
1577 serializer.endTag(null, TAG_NAME);
1578 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001579 synchronized (mRestrictionsLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001580 UserRestrictionsUtils.writeRestrictions(serializer,
1581 mBaseUserRestrictions.get(userInfo.id), TAG_RESTRICTIONS);
1582 UserRestrictionsUtils.writeRestrictions(serializer,
1583 mDevicePolicyLocalUserRestrictions.get(userInfo.id),
1584 TAG_DEVICE_POLICY_RESTRICTIONS);
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001585 }
Amith Yamasani12747872015-12-07 14:19:49 -08001586
1587 if (userData.account != null) {
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001588 serializer.startTag(null, TAG_ACCOUNT);
Amith Yamasani12747872015-12-07 14:19:49 -08001589 serializer.text(userData.account);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001590 serializer.endTag(null, TAG_ACCOUNT);
1591 }
1592
Amith Yamasani12747872015-12-07 14:19:49 -08001593 if (userData.persistSeedData && userData.seedAccountOptions != null) {
1594 serializer.startTag(null, TAG_SEED_ACCOUNT_OPTIONS);
1595 userData.seedAccountOptions.saveToXml(serializer);
1596 serializer.endTag(null, TAG_SEED_ACCOUNT_OPTIONS);
1597 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001598 serializer.endTag(null, TAG_USER);
1599
1600 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001601 userFile.finishWrite(fos);
1602 } catch (Exception ioe) {
Jeff Sharkeycd575992016-03-29 14:12:49 -06001603 Slog.e(LOG_TAG, "Error writing user info " + userData.info.id, ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -07001604 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001605 }
1606 }
1607
1608 /*
1609 * Writes the user list file in this format:
1610 *
Amith Yamasani2a003292012-08-14 18:25:45 -07001611 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001612 * <user id="0"></user>
1613 * <user id="2"></user>
1614 * </users>
1615 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001616 private void writeUserListLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001617 if (DBG) {
1618 debug("writeUserList");
1619 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001620 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001621 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001622 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001623 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001624 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1625
1626 // XmlSerializer serializer = XmlUtils.serializerInstance();
1627 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001628 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001629 serializer.startDocument(null, true);
1630 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1631
1632 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -07001633 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -07001634 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001635
Adam Lesinskieddeb492014-09-08 17:50:03 -07001636 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001637 synchronized (mGuestRestrictions) {
1638 UserRestrictionsUtils
1639 .writeRestrictions(serializer, mGuestRestrictions, TAG_RESTRICTIONS);
1640 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301641 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001642 synchronized (mRestrictionsLock) {
1643 UserRestrictionsUtils.writeRestrictions(serializer,
1644 mDevicePolicyGlobalUserRestrictions, TAG_DEVICE_POLICY_RESTRICTIONS);
1645 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001646 int[] userIdsToWrite;
1647 synchronized (mUsersLock) {
1648 userIdsToWrite = new int[mUsers.size()];
1649 for (int i = 0; i < userIdsToWrite.length; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001650 UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001651 userIdsToWrite[i] = user.id;
1652 }
1653 }
1654 for (int id : userIdsToWrite) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001655 serializer.startTag(null, TAG_USER);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001656 serializer.attribute(null, ATTR_ID, Integer.toString(id));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001657 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001658 }
1659
1660 serializer.endTag(null, TAG_USERS);
1661
1662 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001663 userListFile.finishWrite(fos);
1664 } catch (Exception e) {
1665 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -07001666 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001667 }
1668 }
1669
Amith Yamasani12747872015-12-07 14:19:49 -08001670 private UserData readUserLP(int id) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001671 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -07001672 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001673 String name = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001674 String account = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001675 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -07001676 long creationTime = 0L;
1677 long lastLoggedInTime = 0L;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06001678 String lastLoggedInFingerprint = null;
Kenny Guy2a764942014-04-02 13:29:20 +01001679 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001680 int restrictedProfileParentId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001681 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001682 boolean guestToRemove = false;
Amith Yamasani12747872015-12-07 14:19:49 -08001683 boolean persistSeedData = false;
1684 String seedAccountName = null;
1685 String seedAccountType = null;
1686 PersistableBundle seedAccountOptions = null;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001687 Bundle baseRestrictions = new Bundle();
1688 Bundle localRestrictions = new Bundle();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001689
1690 FileInputStream fis = null;
1691 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001692 AtomicFile userFile =
Amith Yamasanifc95e702013-09-26 13:20:17 -07001693 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
Amith Yamasani2a003292012-08-14 18:25:45 -07001694 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001695 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001696 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001697 int type;
1698 while ((type = parser.next()) != XmlPullParser.START_TAG
1699 && type != XmlPullParser.END_DOCUMENT) {
Amith Yamasani12747872015-12-07 14:19:49 -08001700 // Skip
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001701 }
1702
1703 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001704 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001705 return null;
1706 }
1707
1708 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001709 int storedId = readIntAttribute(parser, ATTR_ID, -1);
1710 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001711 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001712 return null;
1713 }
Amith Yamasani920ace02012-09-20 22:15:37 -07001714 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
1715 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001716 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -07001717 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
1718 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06001719 lastLoggedInFingerprint = parser.getAttributeValue(null,
1720 ATTR_LAST_LOGGED_IN_FINGERPRINT);
Kenny Guy2a764942014-04-02 13:29:20 +01001721 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
1722 UserInfo.NO_PROFILE_GROUP_ID);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001723 restrictedProfileParentId = readIntAttribute(parser,
1724 ATTR_RESTRICTED_PROFILE_PARENT_ID, UserInfo.NO_PROFILE_GROUP_ID);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001725 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
1726 if ("true".equals(valueString)) {
1727 partial = true;
1728 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001729 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
1730 if ("true".equals(valueString)) {
1731 guestToRemove = true;
1732 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001733
Amith Yamasani12747872015-12-07 14:19:49 -08001734 seedAccountName = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_NAME);
1735 seedAccountType = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_TYPE);
1736 if (seedAccountName != null || seedAccountType != null) {
1737 persistSeedData = true;
1738 }
1739
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001740 int outerDepth = parser.getDepth();
1741 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1742 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1743 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1744 continue;
1745 }
1746 String tag = parser.getName();
1747 if (TAG_NAME.equals(tag)) {
1748 type = parser.next();
1749 if (type == XmlPullParser.TEXT) {
1750 name = parser.getText();
1751 }
1752 } else if (TAG_RESTRICTIONS.equals(tag)) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001753 UserRestrictionsUtils.readRestrictions(parser, baseRestrictions);
1754 } else if (TAG_DEVICE_POLICY_RESTRICTIONS.equals(tag)) {
1755 UserRestrictionsUtils.readRestrictions(parser, localRestrictions);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001756 } else if (TAG_ACCOUNT.equals(tag)) {
1757 type = parser.next();
1758 if (type == XmlPullParser.TEXT) {
1759 account = parser.getText();
1760 }
Amith Yamasani12747872015-12-07 14:19:49 -08001761 } else if (TAG_SEED_ACCOUNT_OPTIONS.equals(tag)) {
1762 seedAccountOptions = PersistableBundle.restoreFromXml(parser);
1763 persistSeedData = true;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001764 }
1765 }
1766 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001767
Amith Yamasani12747872015-12-07 14:19:49 -08001768 // Create the UserInfo object that gets passed around
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001769 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -07001770 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -07001771 userInfo.creationTime = creationTime;
1772 userInfo.lastLoggedInTime = lastLoggedInTime;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06001773 userInfo.lastLoggedInFingerprint = lastLoggedInFingerprint;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001774 userInfo.partial = partial;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001775 userInfo.guestToRemove = guestToRemove;
Kenny Guy2a764942014-04-02 13:29:20 +01001776 userInfo.profileGroupId = profileGroupId;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001777 userInfo.restrictedProfileParentId = restrictedProfileParentId;
Amith Yamasani12747872015-12-07 14:19:49 -08001778
1779 // Create the UserData object that's internal to this class
1780 UserData userData = new UserData();
1781 userData.info = userInfo;
1782 userData.account = account;
1783 userData.seedAccountName = seedAccountName;
1784 userData.seedAccountType = seedAccountType;
1785 userData.persistSeedData = persistSeedData;
1786 userData.seedAccountOptions = seedAccountOptions;
1787
Makoto Onuki068c54a2015-10-13 14:34:03 -07001788 synchronized (mRestrictionsLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001789 mBaseUserRestrictions.put(id, baseRestrictions);
1790 mDevicePolicyLocalUserRestrictions.put(id, localRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001791 }
Amith Yamasani12747872015-12-07 14:19:49 -08001792 return userData;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001793 } catch (IOException ioe) {
1794 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001795 } finally {
1796 if (fis != null) {
1797 try {
1798 fis.close();
1799 } catch (IOException e) {
1800 }
1801 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001802 }
1803 return null;
1804 }
1805
Amith Yamasani920ace02012-09-20 22:15:37 -07001806 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
1807 String valueString = parser.getAttributeValue(null, attr);
1808 if (valueString == null) return defaultValue;
1809 try {
1810 return Integer.parseInt(valueString);
1811 } catch (NumberFormatException nfe) {
1812 return defaultValue;
1813 }
1814 }
1815
1816 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
1817 String valueString = parser.getAttributeValue(null, attr);
1818 if (valueString == null) return defaultValue;
1819 try {
1820 return Long.parseLong(valueString);
1821 } catch (NumberFormatException nfe) {
1822 return defaultValue;
1823 }
1824 }
1825
Amith Yamasanib82add22013-07-09 11:24:44 -07001826 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001827 * Removes the app restrictions file for a specific package and user id, if it exists.
1828 */
1829 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
1830 synchronized (mPackagesLock) {
1831 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07001832 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001833 if (resFile.exists()) {
1834 resFile.delete();
1835 }
1836 }
1837 }
1838
Kenny Guya52dc3e2014-02-11 15:33:14 +00001839 @Override
Kenny Guy2a764942014-04-02 13:29:20 +01001840 public UserInfo createProfileForUser(String name, int flags, int userId) {
Kenny Guya52dc3e2014-02-11 15:33:14 +00001841 checkManageUsersPermission("Only the system can create users");
Kenny Guy2a764942014-04-02 13:29:20 +01001842 return createUserInternal(name, flags, userId);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001843 }
1844
Amith Yamasani258848d2012-08-10 17:06:33 -07001845 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07001846 public UserInfo createUser(String name, int flags) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001847 checkManageUsersPermission("Only the system can create users");
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001848 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001849 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001850
Jessica Hummelbe81c802014-04-22 15:49:22 +01001851 private UserInfo createUserInternal(String name, int flags, int parentId) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001852 if (hasUserRestriction(UserManager.DISALLOW_ADD_USER, UserHandle.getCallingUserId())) {
Julia Reynolds75175022014-06-26 16:35:00 -04001853 Log.w(LOG_TAG, "Cannot add user. DISALLOW_ADD_USER is enabled.");
1854 return null;
1855 }
phweisse9c44062016-02-10 12:57:38 +01001856 return createUserInternalUnchecked(name, flags, parentId);
1857 }
1858
1859 private UserInfo createUserInternalUnchecked(String name, int flags, int parentId) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001860 if (ActivityManager.isLowRamDeviceStatic()) {
1861 return null;
1862 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07001863 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001864 final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001865 final boolean isRestricted = (flags & UserInfo.FLAG_RESTRICTED) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001866 final long ident = Binder.clearCallingIdentity();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001867 UserInfo userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08001868 UserData userData;
Amith Yamasanibb054c92015-07-09 14:16:27 -07001869 final int userId;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001870 try {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001871 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001872 UserData parent = null;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001873 if (parentId != UserHandle.USER_NULL) {
1874 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001875 parent = getUserDataLU(parentId);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001876 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001877 if (parent == null) return null;
1878 }
1879 if (isManagedProfile && !canAddMoreManagedProfiles(parentId, false)) {
1880 Log.e(LOG_TAG, "Cannot add more managed profiles for user " + parentId);
1881 return null;
1882 }
1883 if (!isGuest && !isManagedProfile && isUserLimitReached()) {
1884 // If we're not adding a guest user or a managed profile and the limit has
1885 // been reached, cannot add a user.
1886 return null;
1887 }
1888 // If we're adding a guest and there already exists one, bail.
1889 if (isGuest && findCurrentGuestUser() != null) {
1890 return null;
1891 }
1892 // In legacy mode, restricted profile's parent can only be the owner user
1893 if (isRestricted && !UserManager.isSplitSystemUser()
1894 && (parentId != UserHandle.USER_SYSTEM)) {
1895 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
1896 return null;
1897 }
1898 if (isRestricted && UserManager.isSplitSystemUser()) {
1899 if (parent == null) {
1900 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be "
1901 + "specified");
Nicolas Prevot12678a92015-05-13 12:15:03 -07001902 return null;
1903 }
Amith Yamasani12747872015-12-07 14:19:49 -08001904 if (!parent.info.canHaveProfile()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001905 Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be "
1906 + "created for the specified parent user id " + parentId);
Amith Yamasani95ab7842014-08-11 17:09:26 -07001907 return null;
1908 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001909 }
Lenka Trochtova024f9792016-02-17 13:55:17 +01001910 if (!UserManager.isSplitSystemUser() && (flags & UserInfo.FLAG_EPHEMERAL) != 0) {
1911 Log.e(LOG_TAG,
1912 "Ephemeral users are supported on split-system-user systems only.");
1913 return null;
1914 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001915 // In split system user mode, we assign the first human user the primary flag.
1916 // And if there is no device owner, we also assign the admin flag to primary user.
1917 if (UserManager.isSplitSystemUser()
1918 && !isGuest && !isManagedProfile && getPrimaryUser() == null) {
1919 flags |= UserInfo.FLAG_PRIMARY;
Makoto Onukie7927da2015-11-25 10:05:17 -08001920 synchronized (mUsersLock) {
1921 if (!mIsDeviceManaged) {
1922 flags |= UserInfo.FLAG_ADMIN;
1923 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07001924 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001925 }
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01001926
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01001927 userId = getNextAvailableId();
1928 Environment.getUserSystemDirectory(userId).mkdirs();
Lenka Trochtova02fee152015-12-22 14:26:18 +01001929 boolean ephemeralGuests = Resources.getSystem()
1930 .getBoolean(com.android.internal.R.bool.config_guestUserEphemeral);
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01001931
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001932 synchronized (mUsersLock) {
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01001933 // Add ephemeral flag to guests/users if required. Also inherit it from parent.
1934 if ((isGuest && ephemeralGuests) || mForceEphemeralUsers
1935 || (parent != null && parent.info.isEphemeral())) {
1936 flags |= UserInfo.FLAG_EPHEMERAL;
1937 }
1938
1939 userInfo = new UserInfo(userId, name, null, flags);
1940 userInfo.serialNumber = mNextSerialNumber++;
1941 long now = System.currentTimeMillis();
1942 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
1943 userInfo.partial = true;
Fyodor Kupolov83c24242016-03-31 13:30:42 -07001944 userInfo.lastLoggedInFingerprint = Build.FINGERPRINT;
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01001945 userData = new UserData();
1946 userData.info = userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08001947 mUsers.put(userId, userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001948 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06001949 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001950 writeUserListLP();
1951 if (parent != null) {
1952 if (isManagedProfile) {
Amith Yamasani12747872015-12-07 14:19:49 -08001953 if (parent.info.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
1954 parent.info.profileGroupId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001955 writeUserLP(parent);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001956 }
Amith Yamasani12747872015-12-07 14:19:49 -08001957 userInfo.profileGroupId = parent.info.profileGroupId;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001958 } else if (isRestricted) {
Amith Yamasani12747872015-12-07 14:19:49 -08001959 if (parent.info.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) {
1960 parent.info.restrictedProfileParentId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001961 writeUserLP(parent);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07001962 }
Amith Yamasani12747872015-12-07 14:19:49 -08001963 userInfo.restrictedProfileParentId = parent.info.restrictedProfileParentId;
Makoto Onuki068c54a2015-10-13 14:34:03 -07001964 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001965 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07001966 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001967 final StorageManager storage = mContext.getSystemService(StorageManager.class);
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01001968 storage.createUserKey(userId, userInfo.serialNumber, userInfo.isEphemeral());
Jeff Sharkey47f71082016-02-01 17:03:54 -07001969 prepareUserStorage(userId, userInfo.serialNumber,
1970 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001971 mPm.createNewUser(userId);
1972 userInfo.partial = false;
1973 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001974 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001975 }
1976 updateUserIds();
1977 Bundle restrictions = new Bundle();
Fyodor Kupolove04462c2015-11-30 15:02:53 -08001978 if (isGuest) {
1979 synchronized (mGuestRestrictions) {
1980 restrictions.putAll(mGuestRestrictions);
1981 }
1982 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001983 synchronized (mRestrictionsLock) {
1984 mBaseUserRestrictions.append(userId, restrictions);
1985 }
1986 mPm.newUserCreated(userId);
1987 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
1988 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
1989 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
1990 android.Manifest.permission.MANAGE_USERS);
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -08001991 MetricsLogger.count(mContext, isGuest ? TRON_GUEST_CREATED : TRON_USER_CREATED, 1);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001992 } finally {
1993 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07001994 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001995 return userInfo;
1996 }
1997
Amith Yamasani0b285492011-04-14 17:35:23 -07001998 /**
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07001999 * @hide
2000 */
Amith Yamasani12747872015-12-07 14:19:49 -08002001 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002002 public UserInfo createRestrictedProfile(String name, int parentUserId) {
2003 checkManageUsersPermission("setupRestrictedProfile");
2004 final UserInfo user = createProfileForUser(name, UserInfo.FLAG_RESTRICTED, parentUserId);
2005 if (user == null) {
2006 return null;
2007 }
Fyodor Kupolov9e912ba2016-02-09 18:29:43 -08002008 long identity = Binder.clearCallingIdentity();
2009 try {
2010 setUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, true, user.id);
2011 // Change the setting before applying the DISALLOW_SHARE_LOCATION restriction, otherwise
2012 // the putIntForUser() will fail.
2013 android.provider.Settings.Secure.putIntForUser(mContext.getContentResolver(),
2014 android.provider.Settings.Secure.LOCATION_MODE,
2015 android.provider.Settings.Secure.LOCATION_MODE_OFF, user.id);
2016 setUserRestriction(UserManager.DISALLOW_SHARE_LOCATION, true, user.id);
2017 } finally {
2018 Binder.restoreCallingIdentity(identity);
2019 }
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002020 return user;
2021 }
2022
2023 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07002024 * Find the current guest user. If the Guest user is partial,
2025 * then do not include it in the results as it is about to die.
Adam Lesinskieddeb492014-09-08 17:50:03 -07002026 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002027 private UserInfo findCurrentGuestUser() {
2028 synchronized (mUsersLock) {
2029 final int size = mUsers.size();
2030 for (int i = 0; i < size; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002031 final UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002032 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
2033 return user;
2034 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002035 }
2036 }
2037 return null;
2038 }
2039
2040 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07002041 * Mark this guest user for deletion to allow us to create another guest
2042 * and switch to that user before actually removing this guest.
2043 * @param userHandle the userid of the current guest
2044 * @return whether the user could be marked for deletion
2045 */
Amith Yamasani12747872015-12-07 14:19:49 -08002046 @Override
Amith Yamasani1df14732014-08-29 21:37:27 -07002047 public boolean markGuestForDeletion(int userHandle) {
2048 checkManageUsersPermission("Only the system can remove users");
2049 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
2050 UserManager.DISALLOW_REMOVE_USER, false)) {
2051 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
2052 return false;
2053 }
2054
2055 long ident = Binder.clearCallingIdentity();
2056 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002057 final UserData userData;
Amith Yamasani1df14732014-08-29 21:37:27 -07002058 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002059 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002060 userData = mUsers.get(userHandle);
2061 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002062 return false;
2063 }
Amith Yamasani1df14732014-08-29 21:37:27 -07002064 }
Amith Yamasani12747872015-12-07 14:19:49 -08002065 if (!userData.info.isGuest()) {
Amith Yamasani1df14732014-08-29 21:37:27 -07002066 return false;
2067 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002068 // We set this to a guest user that is to be removed. This is a temporary state
2069 // where we are allowed to add new Guest users, even if this one is still not
2070 // removed. This user will still show up in getUserInfo() calls.
2071 // If we don't get around to removing this Guest user, it will be purged on next
2072 // startup.
Amith Yamasani12747872015-12-07 14:19:49 -08002073 userData.info.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07002074 // Mark it as disabled, so that it isn't returned any more when
2075 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002076 userData.info.flags |= UserInfo.FLAG_DISABLED;
2077 writeUserLP(userData);
Amith Yamasani1df14732014-08-29 21:37:27 -07002078 }
2079 } finally {
2080 Binder.restoreCallingIdentity(ident);
2081 }
2082 return true;
2083 }
2084
2085 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002086 * Removes a user and all data directories created for that user. This method should be called
2087 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07002088 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07002089 */
Amith Yamasani12747872015-12-07 14:19:49 -08002090 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -07002091 public boolean removeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002092 checkManageUsersPermission("Only the system can remove users");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04002093 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
2094 UserManager.DISALLOW_REMOVE_USER, false)) {
2095 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
2096 return false;
2097 }
2098
Kenny Guyee58b4f2014-05-23 15:19:53 +01002099 long ident = Binder.clearCallingIdentity();
2100 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002101 final UserData userData;
Fyodor Kupolov0df68cd2015-10-01 13:54:22 -07002102 int currentUser = ActivityManager.getCurrentUser();
2103 if (currentUser == userHandle) {
2104 Log.w(LOG_TAG, "Current user cannot be removed");
2105 return false;
2106 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002107 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002108 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002109 userData = mUsers.get(userHandle);
2110 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002111 return false;
2112 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002113
Fyodor Kupolov82402752015-10-28 14:54:51 -07002114 // We remember deleted user IDs to prevent them from being
2115 // reused during the current boot; they can still be reused
2116 // after a reboot.
2117 mRemovingUserIds.put(userHandle, true);
2118 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002119
Kenny Guyee58b4f2014-05-23 15:19:53 +01002120 try {
2121 mAppOpsService.removeUser(userHandle);
2122 } catch (RemoteException e) {
2123 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
2124 }
2125 // Set this to a partially created user, so that the user will be purged
2126 // on next startup, in case the runtime stops now before stopping and
2127 // removing the user completely.
Amith Yamasani12747872015-12-07 14:19:49 -08002128 userData.info.partial = true;
Kenny Guyee58b4f2014-05-23 15:19:53 +01002129 // Mark it as disabled, so that it isn't returned any more when
2130 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002131 userData.info.flags |= UserInfo.FLAG_DISABLED;
2132 writeUserLP(userData);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002133 }
2134
Amith Yamasani12747872015-12-07 14:19:49 -08002135 if (userData.info.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
2136 && userData.info.isManagedProfile()) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002137 // Send broadcast to notify system that the user removed was a
2138 // managed user.
Amith Yamasani12747872015-12-07 14:19:49 -08002139 sendProfileRemovedBroadcast(userData.info.profileGroupId, userData.info.id);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002140 }
2141
2142 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
2143 int res;
2144 try {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07002145 res = ActivityManagerNative.getDefault().stopUser(userHandle, /* force= */ true,
2146 new IStopUserCallback.Stub() {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002147 @Override
2148 public void userStopped(int userId) {
2149 finishRemoveUser(userId);
2150 }
2151 @Override
2152 public void userStopAborted(int userId) {
2153 }
2154 });
2155 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002156 return false;
2157 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002158 return res == ActivityManager.USER_OP_SUCCESS;
2159 } finally {
2160 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002161 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002162 }
2163
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002164 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07002165 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002166 // Let other services shutdown any activity and clean up their state before completely
2167 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002168 long ident = Binder.clearCallingIdentity();
2169 try {
2170 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
2171 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002172 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
2173 android.Manifest.permission.MANAGE_USERS,
2174
2175 new BroadcastReceiver() {
2176 @Override
2177 public void onReceive(Context context, Intent intent) {
2178 if (DBG) {
2179 Slog.i(LOG_TAG,
2180 "USER_REMOVED broadcast sent, cleaning up user data "
2181 + userHandle);
2182 }
2183 new Thread() {
Amith Yamasani12747872015-12-07 14:19:49 -08002184 @Override
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002185 public void run() {
Amith Yamasani515d4062015-09-28 11:30:06 -07002186 // Clean up any ActivityManager state
2187 LocalServices.getService(ActivityManagerInternal.class)
2188 .onUserRemoved(userHandle);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002189 removeUserState(userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002190 }
2191 }.start();
2192 }
2193 },
2194
2195 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002196 } finally {
2197 Binder.restoreCallingIdentity(ident);
2198 }
Amith Yamasani2a003292012-08-14 18:25:45 -07002199 }
2200
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002201 private void removeUserState(final int userHandle) {
Paul Crowley91293792016-03-25 15:23:07 -07002202 try {
2203 mContext.getSystemService(StorageManager.class).destroyUserKey(userHandle);
2204 } catch (IllegalStateException e) {
2205 // This may be simply because the user was partially created.
2206 Slog.i(LOG_TAG,
2207 "Destroying key for user " + userHandle + " failed, continuing anyway", e);
2208 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002209 // Cleanup package manager settings
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002210 mPm.cleanUpUser(this, userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002211
2212 // Remove this user from the list
Fyodor Kupolov82402752015-10-28 14:54:51 -07002213 synchronized (mUsersLock) {
2214 mUsers.remove(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08002215 mIsUserManaged.delete(userHandle);
2216 }
2217 synchronized (mRestrictionsLock) {
2218 mBaseUserRestrictions.remove(userHandle);
2219 mAppliedUserRestrictions.remove(userHandle);
2220 mCachedEffectiveUserRestrictions.remove(userHandle);
2221 mDevicePolicyLocalUserRestrictions.remove(userHandle);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002222 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002223 // Update the user list
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002224 synchronized (mPackagesLock) {
2225 writeUserListLP();
2226 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06002227 // Remove user file
2228 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
2229 userFile.delete();
Fyodor Kupolov82402752015-10-28 14:54:51 -07002230 updateUserIds();
Amith Yamasani12747872015-12-07 14:19:49 -08002231 File userDir = Environment.getUserSystemDirectory(userHandle);
2232 File renamedUserDir = Environment.getUserSystemDirectory(UserHandle.USER_NULL - userHandle);
2233 if (userDir.renameTo(renamedUserDir)) {
2234 removeDirectoryRecursive(renamedUserDir);
2235 } else {
2236 removeDirectoryRecursive(userDir);
2237 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002238 }
2239
Amith Yamasani61f57372012-08-31 12:12:28 -07002240 private void removeDirectoryRecursive(File parent) {
2241 if (parent.isDirectory()) {
2242 String[] files = parent.list();
2243 for (String filename : files) {
2244 File child = new File(parent, filename);
2245 removeDirectoryRecursive(child);
2246 }
2247 }
2248 parent.delete();
2249 }
2250
Kenny Guyf8d3a232014-05-15 16:09:52 +01002251 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01002252 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01002253 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
2254 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002255 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
Jeff Sharkeyaf6ec292015-12-17 11:19:00 -07002256 managedProfileIntent.putExtra(Intent.EXTRA_USER_HANDLE, removedUserId);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002257 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01002258 }
2259
Amith Yamasani2a003292012-08-14 18:25:45 -07002260 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002261 public Bundle getApplicationRestrictions(String packageName) {
2262 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
2263 }
2264
2265 @Override
2266 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002267 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07002268 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00002269 checkSystemOrRoot("get application restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002270 }
2271 synchronized (mPackagesLock) {
2272 // Read the restrictions from XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07002273 return readApplicationRestrictionsLP(packageName, userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002274 }
2275 }
2276
2277 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002278 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002279 int userId) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00002280 checkSystemOrRoot("set application restrictions");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002281 synchronized (mPackagesLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01002282 if (restrictions == null || restrictions.isEmpty()) {
2283 cleanAppRestrictionsForPackage(packageName, userId);
2284 } else {
Amith Yamasani23879322016-03-30 16:51:26 -07002285 restrictions.setDefusable(true);
Kenny Guyd21b2182014-07-17 16:38:55 +01002286 // Write the restrictions to XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07002287 writeApplicationRestrictionsLP(packageName, restrictions, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01002288 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002289 }
Robin Lee66e5d962014-04-09 16:44:21 +01002290
Fyodor Kupolovd2846122016-02-11 18:06:34 -08002291 // Notify package of changes via an intent - only sent to explicitly registered receivers.
2292 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
2293 changeIntent.setPackage(packageName);
2294 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
2295 mContext.sendBroadcastAsUser(changeIntent, UserHandle.of(userId));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002296 }
2297
2298 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07002299 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002300 try {
2301 return mContext.getPackageManager().getApplicationInfo(packageName,
Fyodor Kupolovd2846122016-02-11 18:06:34 -08002302 PackageManager.MATCH_UNINSTALLED_PACKAGES).uid;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002303 } catch (NameNotFoundException nnfe) {
2304 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07002305 } finally {
2306 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002307 }
2308 }
2309
Fyodor Kupolov82402752015-10-28 14:54:51 -07002310 private Bundle readApplicationRestrictionsLP(String packageName, int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002311 AtomicFile restrictionsFile =
2312 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
2313 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002314 return readApplicationRestrictionsLP(restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002315 }
2316
2317 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002318 static Bundle readApplicationRestrictionsLP(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002319 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002320 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002321 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07002322 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002323 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002324
2325 FileInputStream fis = null;
2326 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002327 fis = restrictionsFile.openRead();
2328 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002329 parser.setInput(fis, StandardCharsets.UTF_8.name());
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002330 XmlUtils.nextElement(parser);
2331 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002332 Slog.e(LOG_TAG, "Unable to read restrictions file "
2333 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002334 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002335 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002336 while (parser.next() != XmlPullParser.END_DOCUMENT) {
2337 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002338 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002339 } catch (IOException|XmlPullParserException e) {
2340 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002341 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002342 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002343 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002344 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002345 }
2346
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002347 private static void readEntry(Bundle restrictions, ArrayList<String> values,
2348 XmlPullParser parser) throws XmlPullParserException, IOException {
2349 int type = parser.getEventType();
2350 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
2351 String key = parser.getAttributeValue(null, ATTR_KEY);
2352 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
2353 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
2354 if (multiple != null) {
2355 values.clear();
2356 int count = Integer.parseInt(multiple);
2357 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
2358 if (type == XmlPullParser.START_TAG
2359 && parser.getName().equals(TAG_VALUE)) {
2360 values.add(parser.nextText().trim());
2361 count--;
2362 }
2363 }
2364 String [] valueStrings = new String[values.size()];
2365 values.toArray(valueStrings);
2366 restrictions.putStringArray(key, valueStrings);
2367 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
2368 restrictions.putBundle(key, readBundleEntry(parser, values));
2369 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
2370 final int outerDepth = parser.getDepth();
2371 ArrayList<Bundle> bundleList = new ArrayList<>();
2372 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2373 Bundle childBundle = readBundleEntry(parser, values);
2374 bundleList.add(childBundle);
2375 }
2376 restrictions.putParcelableArray(key,
2377 bundleList.toArray(new Bundle[bundleList.size()]));
2378 } else {
2379 String value = parser.nextText().trim();
2380 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
2381 restrictions.putBoolean(key, Boolean.parseBoolean(value));
2382 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
2383 restrictions.putInt(key, Integer.parseInt(value));
2384 } else {
2385 restrictions.putString(key, value);
2386 }
2387 }
2388 }
2389 }
2390
2391 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
2392 throws IOException, XmlPullParserException {
2393 Bundle childBundle = new Bundle();
2394 final int outerDepth = parser.getDepth();
2395 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2396 readEntry(childBundle, values, parser);
2397 }
2398 return childBundle;
2399 }
2400
Fyodor Kupolov82402752015-10-28 14:54:51 -07002401 private void writeApplicationRestrictionsLP(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002402 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002403 AtomicFile restrictionsFile = new AtomicFile(
2404 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07002405 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002406 writeApplicationRestrictionsLP(restrictions, restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002407 }
2408
2409 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002410 static void writeApplicationRestrictionsLP(Bundle restrictions, AtomicFile restrictionsFile) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002411 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002412 try {
2413 fos = restrictionsFile.startWrite();
2414 final BufferedOutputStream bos = new BufferedOutputStream(fos);
2415
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002416 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002417 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002418 serializer.startDocument(null, true);
2419 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2420
2421 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002422 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002423 serializer.endTag(null, TAG_RESTRICTIONS);
2424
2425 serializer.endDocument();
2426 restrictionsFile.finishWrite(fos);
2427 } catch (Exception e) {
2428 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002429 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
2430 }
2431 }
2432
2433 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
2434 throws IOException {
2435 for (String key : restrictions.keySet()) {
2436 Object value = restrictions.get(key);
2437 serializer.startTag(null, TAG_ENTRY);
2438 serializer.attribute(null, ATTR_KEY, key);
2439
2440 if (value instanceof Boolean) {
2441 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
2442 serializer.text(value.toString());
2443 } else if (value instanceof Integer) {
2444 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
2445 serializer.text(value.toString());
2446 } else if (value == null || value instanceof String) {
2447 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
2448 serializer.text(value != null ? (String) value : "");
2449 } else if (value instanceof Bundle) {
2450 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2451 writeBundle((Bundle) value, serializer);
2452 } else if (value instanceof Parcelable[]) {
2453 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
2454 Parcelable[] array = (Parcelable[]) value;
2455 for (Parcelable parcelable : array) {
2456 if (!(parcelable instanceof Bundle)) {
2457 throw new IllegalArgumentException("bundle-array can only hold Bundles");
2458 }
2459 serializer.startTag(null, TAG_ENTRY);
2460 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2461 writeBundle((Bundle) parcelable, serializer);
2462 serializer.endTag(null, TAG_ENTRY);
2463 }
2464 } else {
2465 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
2466 String[] values = (String[]) value;
2467 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
2468 for (String choice : values) {
2469 serializer.startTag(null, TAG_VALUE);
2470 serializer.text(choice != null ? choice : "");
2471 serializer.endTag(null, TAG_VALUE);
2472 }
2473 }
2474 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002475 }
2476 }
2477
2478 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07002479 public int getUserSerialNumber(int userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002480 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002481 if (!exists(userHandle)) return -1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002482 return getUserInfoLU(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07002483 }
2484 }
2485
2486 @Override
2487 public int getUserHandle(int userSerialNumber) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002488 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002489 for (int userId : mUserIds) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002490 UserInfo info = getUserInfoLU(userId);
Kenny Guy945f8832015-02-10 15:17:26 +00002491 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07002492 }
2493 // Not found
2494 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07002495 }
2496 }
2497
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002498 @Override
2499 public long getUserCreationTime(int userHandle) {
2500 int callingUserId = UserHandle.getCallingUserId();
2501 UserInfo userInfo = null;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002502 synchronized (mUsersLock) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002503 if (callingUserId == userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002504 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002505 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002506 UserInfo parent = getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002507 if (parent != null && parent.id == callingUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002508 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002509 }
2510 }
2511 }
2512 if (userInfo == null) {
2513 throw new SecurityException("userHandle can only be the calling user or a managed "
2514 + "profile associated with this user");
2515 }
2516 return userInfo.creationTime;
2517 }
2518
Amith Yamasani0b285492011-04-14 17:35:23 -07002519 /**
2520 * Caches the list of user ids in an array, adjusting the array size when necessary.
2521 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002522 private void updateUserIds() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002523 int num = 0;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002524 synchronized (mUsersLock) {
2525 final int userSize = mUsers.size();
2526 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002527 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002528 num++;
2529 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002530 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002531 final int[] newUsers = new int[num];
2532 int n = 0;
2533 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002534 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002535 newUsers[n++] = mUsers.keyAt(i);
2536 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002537 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002538 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07002539 }
2540 }
2541
2542 /**
Jeff Sharkey47f71082016-02-01 17:03:54 -07002543 * Prepare storage areas for given user on all mounted devices.
2544 */
2545 private void prepareUserStorage(int userId, int userSerial, int flags) {
2546 final StorageManager storage = mContext.getSystemService(StorageManager.class);
2547 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
2548 final String volumeUuid = vol.getFsUuid();
2549 storage.prepareUserStorage(volumeUuid, userId, userSerial, flags);
2550 }
2551 }
2552
2553 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002554 * Called right before a user is started. This gives us a chance to prepare
2555 * app storage and apply any user restrictions.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002556 */
2557 public void onBeforeStartUser(int userId) {
Jeff Sharkey47f71082016-02-01 17:03:54 -07002558 final int userSerial = getUserSerialNumber(userId);
2559 prepareUserStorage(userId, userSerial, StorageManager.FLAG_STORAGE_DE);
2560 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_DE);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002561
2562 if (userId != UserHandle.USER_SYSTEM) {
2563 synchronized (mRestrictionsLock) {
2564 applyUserRestrictionsLR(userId);
2565 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002566 }
2567 }
2568
2569 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002570 * Called right before a user is unlocked. This gives us a chance to prepare
2571 * app storage.
2572 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002573 public void onBeforeUnlockUser(@UserIdInt int userId) {
Jeff Sharkey47f71082016-02-01 17:03:54 -07002574 final int userSerial = getUserSerialNumber(userId);
2575 prepareUserStorage(userId, userSerial, StorageManager.FLAG_STORAGE_CE);
2576 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_CE);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002577 }
2578
2579 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002580 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasani920ace02012-09-20 22:15:37 -07002581 * @param userId the user that was just foregrounded
2582 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002583 public void onUserLoggedIn(@UserIdInt int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -08002584 UserData userData = getUserDataNoChecks(userId);
2585 if (userData == null || userData.info.partial) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002586 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
2587 return;
2588 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002589
2590 final long now = System.currentTimeMillis();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002591 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani12747872015-12-07 14:19:49 -08002592 userData.info.lastLoggedInTime = now;
Amith Yamasani920ace02012-09-20 22:15:37 -07002593 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002594 userData.info.lastLoggedInFingerprint = Build.FINGERPRINT;
2595 scheduleWriteUser(userData);
Amith Yamasani920ace02012-09-20 22:15:37 -07002596 }
2597
2598 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002599 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani742a6712011-05-04 14:49:28 -07002600 * TODO: May not be a good idea to recycle ids, in case it results in confusion
2601 * for data and battery stats collection, or unexpected cross-talk.
Amith Yamasani0b285492011-04-14 17:35:23 -07002602 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002603 private int getNextAvailableId() {
2604 synchronized (mUsersLock) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002605 int i = MIN_USER_ID;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002606 while (i < MAX_USER_ID) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002607 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002608 return i;
Amith Yamasani195263742012-08-21 15:40:12 -07002609 }
2610 i++;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002611 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002612 }
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002613 throw new IllegalStateException("No user id available!");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002614 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002615
Amith Yamasanifc95e702013-09-26 13:20:17 -07002616 private String packageToRestrictionsFileName(String packageName) {
2617 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
2618 }
2619
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002620 /**
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002621 * Enforce that serial number stored in user directory inode matches the
2622 * given expected value. Gracefully sets the serial number if currently
2623 * undefined.
2624 *
2625 * @throws IOException when problem extracting serial number, or serial
2626 * number is mismatched.
2627 */
2628 public static void enforceSerialNumber(File file, int serialNumber) throws IOException {
2629 final int foundSerial = getSerialNumber(file);
2630 Slog.v(LOG_TAG, "Found " + file + " with serial number " + foundSerial);
2631
2632 if (foundSerial == -1) {
2633 Slog.d(LOG_TAG, "Serial number missing on " + file + "; assuming current is valid");
2634 try {
2635 setSerialNumber(file, serialNumber);
2636 } catch (IOException e) {
2637 Slog.w(LOG_TAG, "Failed to set serial number on " + file, e);
2638 }
2639
2640 } else if (foundSerial != serialNumber) {
2641 throw new IOException("Found serial number " + foundSerial
2642 + " doesn't match expected " + serialNumber);
2643 }
2644 }
2645
2646 /**
2647 * Set serial number stored in user directory inode.
2648 *
2649 * @throws IOException if serial number was already set
2650 */
2651 private static void setSerialNumber(File file, int serialNumber)
2652 throws IOException {
2653 try {
2654 final byte[] buf = Integer.toString(serialNumber).getBytes(StandardCharsets.UTF_8);
2655 Os.setxattr(file.getAbsolutePath(), XATTR_SERIAL, buf, OsConstants.XATTR_CREATE);
2656 } catch (ErrnoException e) {
2657 throw e.rethrowAsIOException();
2658 }
2659 }
2660
2661 /**
2662 * Return serial number stored in user directory inode.
2663 *
2664 * @return parsed serial number, or -1 if not set
2665 */
2666 private static int getSerialNumber(File file) throws IOException {
2667 try {
2668 final byte[] buf = new byte[256];
2669 final int len = Os.getxattr(file.getAbsolutePath(), XATTR_SERIAL, buf);
2670 final String serial = new String(buf, 0, len);
2671 try {
2672 return Integer.parseInt(serial);
2673 } catch (NumberFormatException e) {
2674 throw new IOException("Bad serial number: " + serial);
2675 }
2676 } catch (ErrnoException e) {
2677 if (e.errno == OsConstants.ENODATA) {
2678 return -1;
2679 } else {
2680 throw e.rethrowAsIOException();
2681 }
2682 }
2683 }
2684
Amith Yamasani920ace02012-09-20 22:15:37 -07002685 @Override
Amith Yamasani12747872015-12-07 14:19:49 -08002686 public void setSeedAccountData(int userId, String accountName, String accountType,
2687 PersistableBundle accountOptions, boolean persist) {
2688 checkManageUsersPermission("Require MANAGE_USERS permission to set user seed data");
2689 synchronized (mPackagesLock) {
2690 final UserData userData;
2691 synchronized (mUsersLock) {
2692 userData = getUserDataLU(userId);
2693 if (userData == null) {
2694 Slog.e(LOG_TAG, "No such user for settings seed data u=" + userId);
2695 return;
2696 }
2697 userData.seedAccountName = accountName;
2698 userData.seedAccountType = accountType;
2699 userData.seedAccountOptions = accountOptions;
2700 userData.persistSeedData = persist;
2701 }
2702 if (persist) {
2703 writeUserLP(userData);
2704 }
2705 }
2706 }
2707
2708 @Override
2709 public String getSeedAccountName() throws RemoteException {
2710 checkManageUsersPermission("Cannot get seed account information");
2711 synchronized (mUsersLock) {
2712 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
2713 return userData.seedAccountName;
2714 }
2715 }
2716
2717 @Override
2718 public String getSeedAccountType() throws RemoteException {
2719 checkManageUsersPermission("Cannot get seed account information");
2720 synchronized (mUsersLock) {
2721 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
2722 return userData.seedAccountType;
2723 }
2724 }
2725
2726 @Override
2727 public PersistableBundle getSeedAccountOptions() throws RemoteException {
2728 checkManageUsersPermission("Cannot get seed account information");
2729 synchronized (mUsersLock) {
2730 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
2731 return userData.seedAccountOptions;
2732 }
2733 }
2734
2735 @Override
2736 public void clearSeedAccountData() throws RemoteException {
2737 checkManageUsersPermission("Cannot clear seed account information");
2738 synchronized (mPackagesLock) {
2739 UserData userData;
2740 synchronized (mUsersLock) {
2741 userData = getUserDataLU(UserHandle.getCallingUserId());
2742 if (userData == null) return;
2743 userData.clearSeedAccountData();
2744 }
2745 writeUserLP(userData);
2746 }
2747 }
2748
2749 @Override
2750 public boolean someUserHasSeedAccount(String accountName, String accountType)
2751 throws RemoteException {
2752 checkManageUsersPermission("Cannot check seed account information");
2753 synchronized (mUsersLock) {
2754 final int userSize = mUsers.size();
2755 for (int i = 0; i < userSize; i++) {
2756 final UserData data = mUsers.valueAt(i);
2757 if (data.info.isInitialized()) continue;
2758 if (data.seedAccountName == null || !data.seedAccountName.equals(accountName)) {
2759 continue;
2760 }
2761 if (data.seedAccountType == null || !data.seedAccountType.equals(accountType)) {
2762 continue;
2763 }
2764 return true;
2765 }
2766 }
2767 return false;
2768 }
2769
2770 @Override
Todd Kennedy60459ab2015-10-30 11:32:16 -07002771 public void onShellCommand(FileDescriptor in, FileDescriptor out,
2772 FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
2773 (new Shell()).exec(this, in, out, err, args, resultReceiver);
2774 }
2775
2776 int onShellCommand(Shell shell, String cmd) {
2777 if (cmd == null) {
2778 return shell.handleDefaultCommands(cmd);
2779 }
2780
2781 final PrintWriter pw = shell.getOutPrintWriter();
2782 try {
2783 switch(cmd) {
2784 case "list":
2785 return runList(pw);
2786 }
2787 } catch (RemoteException e) {
2788 pw.println("Remote exception: " + e);
2789 }
2790 return -1;
2791 }
2792
2793 private int runList(PrintWriter pw) throws RemoteException {
2794 final IActivityManager am = ActivityManagerNative.getDefault();
2795 final List<UserInfo> users = getUsers(false);
2796 if (users == null) {
2797 pw.println("Error: couldn't get users");
2798 return 1;
2799 } else {
2800 pw.println("Users:");
2801 for (int i = 0; i < users.size(); i++) {
Jeff Sharkeye17ac152015-11-06 22:40:29 -08002802 String running = am.isUserRunning(users.get(i).id, 0) ? " running" : "";
Todd Kennedy60459ab2015-10-30 11:32:16 -07002803 pw.println("\t" + users.get(i).toString() + running);
2804 }
2805 return 0;
2806 }
2807 }
2808
2809 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -07002810 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2811 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2812 != PackageManager.PERMISSION_GRANTED) {
2813 pw.println("Permission Denial: can't dump UserManager from from pid="
2814 + Binder.getCallingPid()
2815 + ", uid=" + Binder.getCallingUid()
2816 + " without permission "
2817 + android.Manifest.permission.DUMP);
2818 return;
2819 }
2820
2821 long now = System.currentTimeMillis();
2822 StringBuilder sb = new StringBuilder();
2823 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002824 synchronized (mUsersLock) {
2825 pw.println("Users:");
2826 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002827 UserData userData = mUsers.valueAt(i);
2828 if (userData == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002829 continue;
2830 }
Amith Yamasani12747872015-12-07 14:19:49 -08002831 UserInfo userInfo = userData.info;
2832 final int userId = userInfo.id;
2833 pw.print(" "); pw.print(userInfo);
2834 pw.print(" serialNo="); pw.print(userInfo.serialNumber);
Makoto Onukie7927da2015-11-25 10:05:17 -08002835 if (mRemovingUserIds.get(userId)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002836 pw.print(" <removing> ");
2837 }
Amith Yamasani12747872015-12-07 14:19:49 -08002838 if (userInfo.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002839 pw.print(" <partial>");
2840 }
2841 pw.println();
2842 pw.print(" Created: ");
Amith Yamasani12747872015-12-07 14:19:49 -08002843 if (userInfo.creationTime == 0) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002844 pw.println("<unknown>");
2845 } else {
2846 sb.setLength(0);
Amith Yamasani12747872015-12-07 14:19:49 -08002847 TimeUtils.formatDuration(now - userInfo.creationTime, sb);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002848 sb.append(" ago");
2849 pw.println(sb);
2850 }
2851 pw.print(" Last logged in: ");
Amith Yamasani12747872015-12-07 14:19:49 -08002852 if (userInfo.lastLoggedInTime == 0) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002853 pw.println("<unknown>");
2854 } else {
2855 sb.setLength(0);
Amith Yamasani12747872015-12-07 14:19:49 -08002856 TimeUtils.formatDuration(now - userInfo.lastLoggedInTime, sb);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002857 sb.append(" ago");
2858 pw.println(sb);
2859 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002860 pw.print(" Last logged in fingerprint: ");
2861 pw.println(userInfo.lastLoggedInFingerprint);
Makoto Onukie7927da2015-11-25 10:05:17 -08002862 pw.print(" Has profile owner: ");
2863 pw.println(mIsUserManaged.get(userId));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002864 pw.println(" Restrictions:");
2865 synchronized (mRestrictionsLock) {
2866 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08002867 pw, " ", mBaseUserRestrictions.get(userInfo.id));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002868 pw.println(" Device policy local restrictions:");
2869 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08002870 pw, " ", mDevicePolicyLocalUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002871 pw.println(" Effective restrictions:");
2872 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08002873 pw, " ", mCachedEffectiveUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002874 }
Amith Yamasani12747872015-12-07 14:19:49 -08002875
2876 if (userData.account != null) {
2877 pw.print(" Account name: " + userData.account);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08002878 pw.println();
2879 }
Amith Yamasani12747872015-12-07 14:19:49 -08002880
2881 if (userData.seedAccountName != null) {
2882 pw.print(" Seed account name: " + userData.seedAccountName);
2883 pw.println();
2884 if (userData.seedAccountType != null) {
2885 pw.print(" account type: " + userData.seedAccountType);
2886 pw.println();
2887 }
2888 if (userData.seedAccountOptions != null) {
2889 pw.print(" account options exist");
2890 pw.println();
2891 }
2892 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002893 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002894 }
Amith Yamasani12747872015-12-07 14:19:49 -08002895 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002896 pw.println(" Device policy global restrictions:");
2897 synchronized (mRestrictionsLock) {
2898 UserRestrictionsUtils
2899 .dumpRestrictions(pw, " ", mDevicePolicyGlobalUserRestrictions);
2900 }
Makoto Onukia4f11972015-10-01 13:19:58 -07002901 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002902 pw.println(" Guest restrictions:");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002903 synchronized (mGuestRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002904 UserRestrictionsUtils.dumpRestrictions(pw, " ", mGuestRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002905 }
Makoto Onukie7927da2015-11-25 10:05:17 -08002906 synchronized (mUsersLock) {
2907 pw.println();
2908 pw.println(" Device managed: " + mIsDeviceManaged);
2909 }
Amith Yamasani12747872015-12-07 14:19:49 -08002910 // Dump some capabilities
2911 pw.println();
2912 pw.println(" Max users: " + UserManager.getMaxSupportedUsers());
2913 pw.println(" Supports switchable users: " + UserManager.supportsMultipleUsers());
Lenka Trochtova02fee152015-12-22 14:26:18 +01002914 pw.println(" All guests ephemeral: " + Resources.getSystem().getBoolean(
2915 com.android.internal.R.bool.config_guestUserEphemeral));
Amith Yamasani920ace02012-09-20 22:15:37 -07002916 }
2917 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002918
2919 final class MainHandler extends Handler {
2920
2921 @Override
2922 public void handleMessage(Message msg) {
2923 switch (msg.what) {
2924 case WRITE_USER_MSG:
2925 removeMessages(WRITE_USER_MSG, msg.obj);
2926 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002927 int userId = ((UserData) msg.obj).info.id;
2928 UserData userData = getUserDataNoChecks(userId);
2929 if (userData != null) {
2930 writeUserLP(userData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002931 }
2932 }
2933 }
2934 }
2935 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07002936
2937 /**
2938 * @param userId
2939 * @return whether the user has been initialized yet
2940 */
2941 boolean isInitialized(int userId) {
2942 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
2943 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07002944
2945 private class LocalService extends UserManagerInternal {
Makoto Onuki068c54a2015-10-13 14:34:03 -07002946 @Override
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002947 public void setDevicePolicyUserRestrictions(int userId, @NonNull Bundle localRestrictions,
2948 @Nullable Bundle globalRestrictions) {
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002949 UserManagerService.this.setDevicePolicyUserRestrictionsInner(userId, localRestrictions,
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002950 globalRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002951 }
2952
2953 @Override
2954 public Bundle getBaseUserRestrictions(int userId) {
2955 synchronized (mRestrictionsLock) {
2956 return mBaseUserRestrictions.get(userId);
2957 }
2958 }
2959
2960 @Override
2961 public void setBaseUserRestrictionsByDpmsForMigration(
2962 int userId, Bundle baseRestrictions) {
2963 synchronized (mRestrictionsLock) {
2964 mBaseUserRestrictions.put(userId, new Bundle(baseRestrictions));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002965 invalidateEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002966 }
2967
Amith Yamasani12747872015-12-07 14:19:49 -08002968 final UserData userData = getUserDataNoChecks(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002969 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002970 if (userData != null) {
2971 writeUserLP(userData);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002972 } else {
2973 Slog.w(LOG_TAG, "UserInfo not found for " + userId);
2974 }
2975 }
2976 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08002977
2978 @Override
2979 public boolean getUserRestriction(int userId, String key) {
2980 return getUserRestrictions(userId).getBoolean(key);
2981 }
2982
2983 @Override
2984 public void addUserRestrictionsListener(UserRestrictionsListener listener) {
2985 synchronized (mUserRestrictionsListeners) {
2986 mUserRestrictionsListeners.add(listener);
2987 }
2988 }
2989
2990 @Override
2991 public void removeUserRestrictionsListener(UserRestrictionsListener listener) {
2992 synchronized (mUserRestrictionsListeners) {
2993 mUserRestrictionsListeners.remove(listener);
2994 }
2995 }
Makoto Onukie7927da2015-11-25 10:05:17 -08002996
2997 @Override
2998 public void setDeviceManaged(boolean isManaged) {
2999 synchronized (mUsersLock) {
3000 mIsDeviceManaged = isManaged;
3001 }
3002 }
3003
3004 @Override
3005 public void setUserManaged(int userId, boolean isManaged) {
3006 synchronized (mUsersLock) {
3007 mIsUserManaged.put(userId, isManaged);
3008 }
3009 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01003010
3011 @Override
3012 public void setUserIcon(int userId, Bitmap bitmap) {
3013 long ident = Binder.clearCallingIdentity();
3014 try {
3015 synchronized (mPackagesLock) {
3016 UserData userData = getUserDataNoChecks(userId);
3017 if (userData == null || userData.info.partial) {
3018 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
3019 return;
3020 }
3021 writeBitmapLP(userData.info, bitmap);
3022 writeUserLP(userData);
3023 }
3024 sendUserInfoChangedBroadcast(userId);
3025 } finally {
3026 Binder.restoreCallingIdentity(ident);
3027 }
3028 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01003029
3030 @Override
3031 public void setForceEphemeralUsers(boolean forceEphemeralUsers) {
3032 synchronized (mUsersLock) {
3033 mForceEphemeralUsers = forceEphemeralUsers;
3034 }
3035 }
3036
3037 @Override
3038 public void removeAllUsers() {
3039 if (UserHandle.USER_SYSTEM == ActivityManager.getCurrentUser()) {
3040 // Remove the non-system users straight away.
3041 removeNonSystemUsers();
3042 } else {
3043 // Switch to the system user first and then remove the other users.
3044 BroadcastReceiver userSwitchedReceiver = new BroadcastReceiver() {
3045 @Override
3046 public void onReceive(Context context, Intent intent) {
3047 int userId =
3048 intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3049 if (userId != UserHandle.USER_SYSTEM) {
3050 return;
3051 }
3052 mContext.unregisterReceiver(this);
3053 removeNonSystemUsers();
3054 }
3055 };
3056 IntentFilter userSwitchedFilter = new IntentFilter();
3057 userSwitchedFilter.addAction(Intent.ACTION_USER_SWITCHED);
3058 mContext.registerReceiver(
3059 userSwitchedReceiver, userSwitchedFilter, null, mHandler);
3060
3061 // Switch to the system user.
3062 ActivityManager am =
3063 (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
3064 am.switchUser(UserHandle.USER_SYSTEM);
3065 }
3066 }
phweisse9c44062016-02-10 12:57:38 +01003067
3068 @Override
Lenka Trochtova1ddda472016-02-12 10:42:12 +01003069 public void onEphemeralUserStop(int userId) {
3070 synchronized (mUsersLock) {
3071 UserInfo userInfo = getUserInfoLU(userId);
3072 if (userInfo != null && userInfo.isEphemeral()) {
3073 // Do not allow switching back to the ephemeral user again as the user is going
3074 // to be deleted.
3075 userInfo.flags |= UserInfo.FLAG_DISABLED;
3076 if (userInfo.isGuest()) {
3077 // Indicate that the guest will be deleted after it stops.
3078 userInfo.guestToRemove = true;
3079 }
3080 }
3081 }
3082 }
3083
3084 @Override
phweisse9c44062016-02-10 12:57:38 +01003085 public UserInfo createUserEvenWhenDisallowed(String name, int flags) {
3086 UserInfo user = createUserInternalUnchecked(name, flags, UserHandle.USER_NULL);
3087 // Keep this in sync with UserManager.createUser
3088 if (user != null && !user.isAdmin()) {
3089 setUserRestriction(UserManager.DISALLOW_SMS, true, user.id);
3090 setUserRestriction(UserManager.DISALLOW_OUTGOING_CALLS, true, user.id);
3091 }
3092 return user;
3093 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01003094 }
3095
3096 /* Remove all the users except of the system one. */
3097 private void removeNonSystemUsers() {
3098 ArrayList<UserInfo> usersToRemove = new ArrayList<>();
3099 synchronized (mUsersLock) {
3100 final int userSize = mUsers.size();
3101 for (int i = 0; i < userSize; i++) {
3102 UserInfo ui = mUsers.valueAt(i).info;
3103 if (ui.id != UserHandle.USER_SYSTEM) {
3104 usersToRemove.add(ui);
3105 }
3106 }
3107 }
3108 for (UserInfo ui: usersToRemove) {
3109 removeUser(ui.id);
3110 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003111 }
Todd Kennedy60459ab2015-10-30 11:32:16 -07003112
3113 private class Shell extends ShellCommand {
3114 @Override
3115 public int onCommand(String cmd) {
3116 return onShellCommand(this, cmd);
3117 }
3118
3119 @Override
3120 public void onHelp() {
3121 final PrintWriter pw = getOutPrintWriter();
3122 pw.println("User manager (user) commands:");
3123 pw.println(" help");
3124 pw.println(" Print this help text.");
3125 pw.println("");
3126 pw.println(" list");
3127 pw.println(" Prints all users on the system.");
3128 }
3129 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003130
3131 private static void debug(String message) {
3132 Log.d(LOG_TAG, message +
3133 (DBG_WITH_STACKTRACE ? " called at\n" + Debug.getCallers(10, " ") : ""));
3134 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003135}