blob: 4541e2ecf2c9e878e6c73ce498d2d3e77517d8ca [file] [log] [blame]
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
Benjamin Franzf02420c2016-04-04 18:52:21 +010019import static android.content.Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS;
20import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
21
Xiaohui Chenb3b92582015-12-07 11:22:13 -080022import android.Manifest;
Xiaohui Chen594f2082015-08-18 11:04:20 -070023import android.annotation.NonNull;
Makoto Onuki068c54a2015-10-13 14:34:03 -070024import android.annotation.Nullable;
Bart Searsc51e7252016-05-27 04:12:51 +000025import android.annotation.SystemApi;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -060026import android.annotation.UserIdInt;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070027import android.app.Activity;
Amith Yamasani2a003292012-08-14 18:25:45 -070028import android.app.ActivityManager;
Amith Yamasani515d4062015-09-28 11:30:06 -070029import android.app.ActivityManagerInternal;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070030import android.app.ActivityManagerNative;
Amith Yamasanieb437d42016-04-29 09:31:25 -070031import android.app.AppGlobals;
Todd Kennedy60459ab2015-10-30 11:32:16 -070032import android.app.IActivityManager;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070033import android.app.IStopUserCallback;
Benjamin Franzf02420c2016-04-04 18:52:21 +010034import android.app.KeyguardManager;
Bart Searsc51e7252016-05-27 04:12:51 +000035import android.app.admin.DevicePolicyManager;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070036import android.content.BroadcastReceiver;
Bart Searsc51e7252016-05-27 04:12:51 +000037import android.content.ComponentName;
Amith Yamasani258848d2012-08-10 17:06:33 -070038import android.content.Context;
39import android.content.Intent;
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +010040import android.content.IntentFilter;
Benjamin Franzf02420c2016-04-04 18:52:21 +010041import android.content.IntentSender;
Amith Yamasani0b285492011-04-14 17:35:23 -070042import android.content.pm.PackageManager;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -080043import android.content.pm.PackageManager.NameNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070044import android.content.pm.UserInfo;
Lenka Trochtova02fee152015-12-22 14:26:18 +010045import android.content.res.Resources;
Amith Yamasanie928d7d2012-09-17 21:46:51 -070046import android.graphics.Bitmap;
Amith Yamasani258848d2012-08-10 17:06:33 -070047import android.os.Binder;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -060048import android.os.Build;
Amith Yamasanie4cf7342012-12-17 11:12:09 -080049import android.os.Bundle;
Makoto Onuki1a2cd742015-11-16 13:51:27 -080050import android.os.Debug;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070051import android.os.Environment;
52import android.os.FileUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080053import android.os.Handler;
Svet Ganov9cea80cd2016-02-16 11:47:00 -080054import android.os.IBinder;
Amith Yamasani258848d2012-08-10 17:06:33 -070055import android.os.IUserManager;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -080056import android.os.Message;
Adrian Roos1bdff912015-02-17 15:51:35 +010057import android.os.ParcelFileDescriptor;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070058import android.os.Parcelable;
Amith Yamasani12747872015-12-07 14:19:49 -080059import android.os.PersistableBundle;
Amith Yamasani258848d2012-08-10 17:06:33 -070060import android.os.Process;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070061import android.os.RemoteException;
Todd Kennedy60459ab2015-10-30 11:32:16 -070062import android.os.ResultReceiver;
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +010063import android.os.SELinux;
Jason Monk62062992014-05-06 09:55:28 -040064import android.os.ServiceManager;
Todd Kennedy60459ab2015-10-30 11:32:16 -070065import android.os.ShellCommand;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070066import android.os.UserHandle;
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070067import android.os.UserManager;
Makoto Onuki068c54a2015-10-13 14:34:03 -070068import android.os.UserManagerInternal;
Makoto Onukid45a4a22015-11-02 17:17:38 -080069import android.os.UserManagerInternal.UserRestrictionsListener;
Paul Crowley85e4e812015-05-19 12:42:00 +010070import android.os.storage.StorageManager;
Jeff Sharkey6dce4962015-07-03 18:08:41 -070071import android.system.ErrnoException;
72import android.system.Os;
73import android.system.OsConstants;
Amith Yamasanieb437d42016-04-29 09:31:25 -070074import android.text.TextUtils;
Amith Yamasani2a003292012-08-14 18:25:45 -070075import android.util.AtomicFile;
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -070076import android.util.IntArray;
Amith Yamasani655d0e22013-06-12 14:19:10 -070077import android.util.Log;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070078import android.util.Slog;
79import android.util.SparseArray;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080080import android.util.SparseBooleanArray;
Amith Yamasani920ace02012-09-20 22:15:37 -070081import android.util.TimeUtils;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070082import android.util.Xml;
83
Makoto Onuki068c54a2015-10-13 14:34:03 -070084import com.android.internal.annotations.GuardedBy;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070085import com.android.internal.annotations.VisibleForTesting;
Jason Monk62062992014-05-06 09:55:28 -040086import com.android.internal.app.IAppOpsService;
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -080087import com.android.internal.logging.MetricsLogger;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080088import com.android.internal.util.FastXmlSerializer;
Makoto Onuki068c54a2015-10-13 14:34:03 -070089import com.android.internal.util.Preconditions;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070090import com.android.internal.util.XmlUtils;
Clara Bayarri10ad84a2015-12-01 17:38:05 +000091import com.android.internal.widget.LockPatternUtils;
Amith Yamasani515d4062015-09-28 11:30:06 -070092import com.android.server.LocalServices;
Jeff Sharkey47f71082016-02-01 17:03:54 -070093
94import libcore.io.IoUtils;
95import libcore.util.Objects;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080096
97import org.xmlpull.v1.XmlPullParser;
98import org.xmlpull.v1.XmlPullParserException;
99import org.xmlpull.v1.XmlSerializer;
100
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700101import java.io.BufferedOutputStream;
102import java.io.File;
Amith Yamasani920ace02012-09-20 22:15:37 -0700103import java.io.FileDescriptor;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700104import java.io.FileInputStream;
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700105import java.io.FileNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700106import java.io.FileOutputStream;
107import java.io.IOException;
Amith Yamasani920ace02012-09-20 22:15:37 -0700108import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100109import java.nio.charset.StandardCharsets;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700110import java.util.ArrayList;
111import java.util.List;
112
Makoto Onuki068c54a2015-10-13 14:34:03 -0700113/**
114 * Service for {@link UserManager}.
115 *
116 * Method naming convention:
Fyodor Kupolov82402752015-10-28 14:54:51 -0700117 * <ul>
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800118 * <li> Methods suffixed with "LP" should be called within the {@link #mPackagesLock} lock.
Fyodor Kupolov82402752015-10-28 14:54:51 -0700119 * <li> Methods suffixed with "LR" should be called within the {@link #mRestrictionsLock} lock.
120 * <li> Methods suffixed with "LU" should be called within the {@link #mUsersLock} lock.
121 * </ul>
Makoto Onuki068c54a2015-10-13 14:34:03 -0700122 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700123public class UserManagerService extends IUserManager.Stub {
Amith Yamasani2a003292012-08-14 18:25:45 -0700124 private static final String LOG_TAG = "UserManagerService";
Makoto Onuki81c61ea2016-01-22 11:22:26 -0800125 static final boolean DBG = false; // DO NOT SUBMIT WITH TRUE
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800126 private static final boolean DBG_WITH_STACKTRACE = false; // DO NOT SUBMIT WITH TRUE
Amith Yamasani16389312012-10-17 21:20:14 -0700127
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700128 private static final String TAG_NAME = "name";
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800129 private static final String TAG_ACCOUNT = "account";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700130 private static final String ATTR_FLAGS = "flags";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700131 private static final String ATTR_ICON_PATH = "icon";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700132 private static final String ATTR_ID = "id";
Amith Yamasani920ace02012-09-20 22:15:37 -0700133 private static final String ATTR_CREATION_TIME = "created";
134 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -0600135 private static final String ATTR_LAST_LOGGED_IN_FINGERPRINT = "lastLoggedInFingerprint";
Amith Yamasani2a003292012-08-14 18:25:45 -0700136 private static final String ATTR_SERIAL_NO = "serialNumber";
137 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700138 private static final String ATTR_PARTIAL = "partial";
Adam Lesinskieddeb492014-09-08 17:50:03 -0700139 private static final String ATTR_GUEST_TO_REMOVE = "guestToRemove";
Amith Yamasani6f34b412012-10-22 18:19:27 -0700140 private static final String ATTR_USER_VERSION = "version";
Kenny Guy2a764942014-04-02 13:29:20 +0100141 private static final String ATTR_PROFILE_GROUP_ID = "profileGroupId";
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700142 private static final String ATTR_RESTRICTED_PROFILE_PARENT_ID = "restrictedProfileParentId";
Amith Yamasani12747872015-12-07 14:19:49 -0800143 private static final String ATTR_SEED_ACCOUNT_NAME = "seedAccountName";
144 private static final String ATTR_SEED_ACCOUNT_TYPE = "seedAccountType";
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530145 private static final String TAG_GUEST_RESTRICTIONS = "guestRestrictions";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700146 private static final String TAG_USERS = "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700147 private static final String TAG_USER = "user";
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800148 private static final String TAG_RESTRICTIONS = "restrictions";
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800149 private static final String TAG_DEVICE_POLICY_RESTRICTIONS = "device_policy_restrictions";
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +0100150 private static final String TAG_GLOBAL_RESTRICTION_OWNER_ID = "globalRestrictionOwnerUserId";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800151 private static final String TAG_ENTRY = "entry";
152 private static final String TAG_VALUE = "value";
Amith Yamasani12747872015-12-07 14:19:49 -0800153 private static final String TAG_SEED_ACCOUNT_OPTIONS = "seedAccountOptions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800154 private static final String ATTR_KEY = "key";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700155 private static final String ATTR_VALUE_TYPE = "type";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800156 private static final String ATTR_MULTIPLE = "m";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700157
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700158 private static final String ATTR_TYPE_STRING_ARRAY = "sa";
159 private static final String ATTR_TYPE_STRING = "s";
160 private static final String ATTR_TYPE_BOOLEAN = "b";
Amith Yamasani5b5aa402014-06-01 20:10:14 -0700161 private static final String ATTR_TYPE_INTEGER = "i";
Fyodor Kupolov262f9952015-03-23 18:55:11 -0700162 private static final String ATTR_TYPE_BUNDLE = "B";
163 private static final String ATTR_TYPE_BUNDLE_ARRAY = "BA";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700164
Amith Yamasani0b285492011-04-14 17:35:23 -0700165 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700166 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700167 private static final String USER_PHOTO_FILENAME = "photo.png";
Adrian Roos1bdff912015-02-17 15:51:35 +0100168 private static final String USER_PHOTO_FILENAME_TMP = USER_PHOTO_FILENAME + ".tmp";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700169
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800170 private static final String RESTRICTIONS_FILE_PREFIX = "res_";
Amith Yamasanifc95e702013-09-26 13:20:17 -0700171 private static final String XML_SUFFIX = ".xml";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800172
Amith Yamasani634cf312012-10-04 17:34:21 -0700173 private static final int MIN_USER_ID = 10;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700174 // We need to keep process uid within Integer.MAX_VALUE.
175 private static final int MAX_USER_ID = Integer.MAX_VALUE / UserHandle.PER_USER_RANGE;
Amith Yamasani634cf312012-10-04 17:34:21 -0700176
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700177 private static final int USER_VERSION = 6;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700178
Amith Yamasani920ace02012-09-20 22:15:37 -0700179 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
180
Nicolas Prevotb8186812015-08-06 15:00:03 +0100181 // Maximum number of managed profiles permitted per user is 1. This cannot be increased
Amith Yamasani95ab7842014-08-11 17:09:26 -0700182 // without first making sure that the rest of the framework is prepared for it.
183 private static final int MAX_MANAGED_PROFILES = 1;
184
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800185 static final int WRITE_USER_MSG = 1;
186 static final int WRITE_USER_DELAY = 2*1000; // 2 seconds
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530187
Jeff Sharkey6dce4962015-07-03 18:08:41 -0700188 private static final String XATTR_SERIAL = "user.serial";
189
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -0800190 // Tron counters
191 private static final String TRON_GUEST_CREATED = "users_guest_created";
192 private static final String TRON_USER_CREATED = "users_user_created";
193
Dianne Hackborn4428e172012-08-24 17:43:05 -0700194 private final Context mContext;
195 private final PackageManagerService mPm;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700196 private final Object mPackagesLock;
Fyodor Kupolov82402752015-10-28 14:54:51 -0700197 // Short-term lock for internal state, when interaction/sync with PM is not required
198 private final Object mUsersLock = new Object();
199 private final Object mRestrictionsLock = new Object();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700200
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800201 private final Handler mHandler;
202
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700203 private final File mUsersDir;
204 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700205
Svet Ganov9cea80cd2016-02-16 11:47:00 -0800206 private static final IBinder mUserRestriconToken = new Binder();
207
Makoto Onuki068c54a2015-10-13 14:34:03 -0700208 /**
Amith Yamasani12747872015-12-07 14:19:49 -0800209 * User-related information that is used for persisting to flash. Only UserInfo is
210 * directly exposed to other system apps.
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800211 */
Amith Yamasani12747872015-12-07 14:19:49 -0800212 private static class UserData {
213 // Basic user information and properties
214 UserInfo info;
215 // Account name used when there is a strong association between a user and an account
216 String account;
217 // Account information for seeding into a newly created user. This could also be
218 // used for login validation for an existing user, for updating their credentials.
219 // In the latter case, data may not need to be persisted as it is only valid for the
220 // current login session.
221 String seedAccountName;
222 String seedAccountType;
223 PersistableBundle seedAccountOptions;
224 // Whether to perist the seed account information to be available after a boot
225 boolean persistSeedData;
226
227 void clearSeedAccountData() {
228 seedAccountName = null;
229 seedAccountType = null;
230 seedAccountOptions = null;
231 persistSeedData = false;
232 }
233 }
234
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800235 @GuardedBy("mUsersLock")
Amith Yamasani12747872015-12-07 14:19:49 -0800236 private final SparseArray<UserData> mUsers = new SparseArray<>();
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800237
238 /**
Makoto Onuki068c54a2015-10-13 14:34:03 -0700239 * User restrictions set via UserManager. This doesn't include restrictions set by
240 * device owner / profile owners.
241 *
242 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
243 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
244 * maybe shared between {@link #mBaseUserRestrictions} and
245 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
246 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700247 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700248 */
249 @GuardedBy("mRestrictionsLock")
250 private final SparseArray<Bundle> mBaseUserRestrictions = new SparseArray<>();
251
252 /**
253 * Cached user restrictions that are in effect -- i.e. {@link #mBaseUserRestrictions} combined
254 * with device / profile owner restrictions. We'll initialize it lazily; use
255 * {@link #getEffectiveUserRestrictions} to access it.
256 *
257 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
258 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
259 * maybe shared between {@link #mBaseUserRestrictions} and
260 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
261 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700262 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700263 */
264 @GuardedBy("mRestrictionsLock")
265 private final SparseArray<Bundle> mCachedEffectiveUserRestrictions = new SparseArray<>();
266
Makoto Onuki4f160732015-10-27 17:15:38 -0700267 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800268 * User restrictions that have already been applied in
269 * {@link #updateUserRestrictionsInternalLR(Bundle, int)}. We use it to detect restrictions
270 * that have changed since the last
271 * {@link #updateUserRestrictionsInternalLR(Bundle, int)} call.
Makoto Onuki4f160732015-10-27 17:15:38 -0700272 */
273 @GuardedBy("mRestrictionsLock")
274 private final SparseArray<Bundle> mAppliedUserRestrictions = new SparseArray<>();
275
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800276 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800277 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
278 * that should be applied to all users, including guests.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800279 */
280 @GuardedBy("mRestrictionsLock")
281 private Bundle mDevicePolicyGlobalUserRestrictions;
282
283 /**
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +0100284 * Id of the user that set global restrictions.
285 */
286 @GuardedBy("mRestrictionsLock")
287 private int mGlobalRestrictionOwnerUserId = UserHandle.USER_NULL;
288
289 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800290 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
291 * for each user.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800292 */
293 @GuardedBy("mRestrictionsLock")
294 private final SparseArray<Bundle> mDevicePolicyLocalUserRestrictions = new SparseArray<>();
295
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800296 @GuardedBy("mGuestRestrictions")
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530297 private final Bundle mGuestRestrictions = new Bundle();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800298
299 /**
300 * Set of user IDs being actively removed. Removed IDs linger in this set
301 * for several seconds to work around a VFS caching issue.
302 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700303 @GuardedBy("mUsersLock")
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800304 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700305
Fyodor Kupolov82402752015-10-28 14:54:51 -0700306 @GuardedBy("mUsersLock")
Amith Yamasani0b285492011-04-14 17:35:23 -0700307 private int[] mUserIds;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800308 @GuardedBy("mPackagesLock")
Amith Yamasani2a003292012-08-14 18:25:45 -0700309 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700310 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700311
Jason Monk62062992014-05-06 09:55:28 -0400312 private IAppOpsService mAppOpsService;
313
Makoto Onuki068c54a2015-10-13 14:34:03 -0700314 private final LocalService mLocalService;
315
Makoto Onukie7927da2015-11-25 10:05:17 -0800316 @GuardedBy("mUsersLock")
317 private boolean mIsDeviceManaged;
318
319 @GuardedBy("mUsersLock")
320 private final SparseBooleanArray mIsUserManaged = new SparseBooleanArray();
321
Makoto Onukid45a4a22015-11-02 17:17:38 -0800322 @GuardedBy("mUserRestrictionsListeners")
323 private final ArrayList<UserRestrictionsListener> mUserRestrictionsListeners =
324 new ArrayList<>();
325
Clara Bayarria1771112015-12-18 16:29:18 +0000326 private final LockPatternUtils mLockPatternUtils;
327
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +0100328 /**
329 * Whether all users should be created ephemeral.
330 */
331 @GuardedBy("mUsersLock")
332 private boolean mForceEphemeralUsers;
333
Bart Searsc51e7252016-05-27 04:12:51 +0000334 @GuardedBy("mUsersLock")
335 private final SparseBooleanArray mUnlockingOrUnlockedUsers = new SparseBooleanArray();
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -0700336
Amith Yamasani258848d2012-08-10 17:06:33 -0700337 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700338
Dianne Hackborn4428e172012-08-24 17:43:05 -0700339 public static UserManagerService getInstance() {
340 synchronized (UserManagerService.class) {
341 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700342 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700343 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700344
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800345 @VisibleForTesting
346 UserManagerService(File dataDir) {
347 this(null, null, new Object(), dataDir);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700348 }
349
Dianne Hackborn4428e172012-08-24 17:43:05 -0700350 /**
351 * Called by package manager to create the service. This is closely
352 * associated with the package manager, and the given lock is the
353 * package manager's own lock.
354 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800355 UserManagerService(Context context, PackageManagerService pm, Object packagesLock) {
356 this(context, pm, packagesLock, Environment.getDataDirectory());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700357 }
358
Dianne Hackborn4428e172012-08-24 17:43:05 -0700359 private UserManagerService(Context context, PackageManagerService pm,
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800360 Object packagesLock, File dataDir) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700361 mContext = context;
362 mPm = pm;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700363 mPackagesLock = packagesLock;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800364 mHandler = new MainHandler();
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800365 synchronized (mPackagesLock) {
366 mUsersDir = new File(dataDir, USER_INFO_DIR);
367 mUsersDir.mkdirs();
368 // Make zeroth user directory, for services to migrate their files to that location
369 File userZeroDir = new File(mUsersDir, String.valueOf(UserHandle.USER_SYSTEM));
370 userZeroDir.mkdirs();
371 FileUtils.setPermissions(mUsersDir.toString(),
372 FileUtils.S_IRWXU | FileUtils.S_IRWXG | FileUtils.S_IROTH | FileUtils.S_IXOTH,
373 -1, -1);
374 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
375 initDefaultGuestRestrictions();
376 readUserListLP();
377 sInstance = this;
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700378 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700379 mLocalService = new LocalService();
380 LocalServices.addService(UserManagerInternal.class, mLocalService);
Clara Bayarria1771112015-12-18 16:29:18 +0000381 mLockPatternUtils = new LockPatternUtils(mContext);
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700382 }
383
384 void systemReady() {
Lenka Trochtovac4dd0212015-11-18 12:22:06 +0100385 // Prune out any partially created, partially removed and ephemeral users.
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800386 ArrayList<UserInfo> partials = new ArrayList<>();
387 synchronized (mUsersLock) {
388 final int userSize = mUsers.size();
389 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800390 UserInfo ui = mUsers.valueAt(i).info;
Lenka Trochtovac4dd0212015-11-18 12:22:06 +0100391 if ((ui.partial || ui.guestToRemove || ui.isEphemeral()) && i != 0) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800392 partials.add(ui);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700393 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700394 }
Dianne Hackborn4428e172012-08-24 17:43:05 -0700395 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800396 final int partialsSize = partials.size();
397 for (int i = 0; i < partialsSize; i++) {
398 UserInfo ui = partials.get(i);
399 Slog.w(LOG_TAG, "Removing partially created user " + ui.id
400 + " (name=" + ui.name + ")");
401 removeUserState(ui.id);
402 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800403
Jason Monk62062992014-05-06 09:55:28 -0400404 mAppOpsService = IAppOpsService.Stub.asInterface(
405 ServiceManager.getService(Context.APP_OPS_SERVICE));
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800406
407 synchronized (mRestrictionsLock) {
408 applyUserRestrictionsLR(UserHandle.USER_SYSTEM);
Jason Monk62062992014-05-06 09:55:28 -0400409 }
Samuel Tand9453b82016-03-14 15:57:02 -0700410
411 UserInfo currentGuestUser = findCurrentGuestUser();
412 if (currentGuestUser != null && !hasUserRestriction(
413 UserManager.DISALLOW_CONFIG_WIFI, currentGuestUser.id)) {
414 // If a guest user currently exists, apply the DISALLOW_CONFIG_WIFI option
415 // to it, in case this guest was created in a previous version where this
416 // user restriction was not a default guest restriction.
417 setUserRestriction(UserManager.DISALLOW_CONFIG_WIFI, true, currentGuestUser.id);
418 }
Amith Yamasanieb437d42016-04-29 09:31:25 -0700419
420 maybeInitializeDemoMode(UserHandle.USER_SYSTEM);
421}
Amith Yamasani258848d2012-08-10 17:06:33 -0700422
423 @Override
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800424 public String getUserAccount(int userId) {
425 checkManageUserAndAcrossUsersFullPermission("get user account");
426 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800427 return mUsers.get(userId).account;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800428 }
429 }
430
431 @Override
432 public void setUserAccount(int userId, String accountName) {
433 checkManageUserAndAcrossUsersFullPermission("set user account");
Amith Yamasani12747872015-12-07 14:19:49 -0800434 UserData userToUpdate = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800435 synchronized (mPackagesLock) {
436 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800437 final UserData userData = mUsers.get(userId);
438 if (userData == null) {
439 Slog.e(LOG_TAG, "User not found for setting user account: u" + userId);
440 return;
441 }
442 String currentAccount = userData.account;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800443 if (!Objects.equal(currentAccount, accountName)) {
Amith Yamasani12747872015-12-07 14:19:49 -0800444 userData.account = accountName;
445 userToUpdate = userData;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800446 }
447 }
448
449 if (userToUpdate != null) {
450 writeUserLP(userToUpdate);
451 }
452 }
453 }
454
455 @Override
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700456 public UserInfo getPrimaryUser() {
457 checkManageUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700458 synchronized (mUsersLock) {
Amith Yamasani515d4062015-09-28 11:30:06 -0700459 final int userSize = mUsers.size();
460 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800461 UserInfo ui = mUsers.valueAt(i).info;
Xiaohui Chend3e9e182015-11-18 13:37:32 -0800462 if (ui.isPrimary() && !mRemovingUserIds.get(ui.id)) {
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700463 return ui;
464 }
465 }
466 }
467 return null;
468 }
469
470 @Override
Xiaohui Chen594f2082015-08-18 11:04:20 -0700471 public @NonNull List<UserInfo> getUsers(boolean excludeDying) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700472 checkManageUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700473 synchronized (mUsersLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700474 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasani515d4062015-09-28 11:30:06 -0700475 final int userSize = mUsers.size();
476 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800477 UserInfo ui = mUsers.valueAt(i).info;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700478 if (ui.partial) {
479 continue;
480 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800481 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Amith Yamasani6f48d6e2016-03-23 14:28:25 -0700482 users.add(userWithName(ui));
Amith Yamasani920ace02012-09-20 22:15:37 -0700483 }
Amith Yamasani13593602012-03-22 16:16:17 -0700484 }
485 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700486 }
Amith Yamasani13593602012-03-22 16:16:17 -0700487 }
488
Amith Yamasani258848d2012-08-10 17:06:33 -0700489 @Override
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100490 public List<UserInfo> getProfiles(int userId, boolean enabledOnly) {
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700491 boolean returnFullInfo = true;
Amith Yamasani4f582632014-02-19 14:31:52 -0800492 if (userId != UserHandle.getCallingUserId()) {
493 checkManageUsersPermission("getting profiles related to user " + userId);
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700494 } else {
495 returnFullInfo = hasManageUsersPermission();
Amith Yamasani4f582632014-02-19 14:31:52 -0800496 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700497 final long ident = Binder.clearCallingIdentity();
498 try {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700499 synchronized (mUsersLock) {
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700500 return getProfilesLU(userId, enabledOnly, returnFullInfo);
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100501 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700502 } finally {
503 Binder.restoreCallingIdentity(ident);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000504 }
505 }
506
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700507 @Override
508 public int[] getProfileIds(int userId, boolean enabledOnly) {
509 if (userId != UserHandle.getCallingUserId()) {
510 checkManageUsersPermission("getting profiles related to user " + userId);
511 }
512 final long ident = Binder.clearCallingIdentity();
513 try {
514 synchronized (mUsersLock) {
515 return getProfileIdsLU(userId, enabledOnly).toArray();
516 }
517 } finally {
518 Binder.restoreCallingIdentity(ident);
519 }
520 }
521
Amith Yamasanibe465322014-04-24 13:45:17 -0700522 /** Assume permissions already checked and caller's identity cleared */
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700523 private List<UserInfo> getProfilesLU(int userId, boolean enabledOnly, boolean fullInfo) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700524 IntArray profileIds = getProfileIdsLU(userId, enabledOnly);
525 ArrayList<UserInfo> users = new ArrayList<>(profileIds.size());
526 for (int i = 0; i < profileIds.size(); i++) {
527 int profileId = profileIds.get(i);
528 UserInfo userInfo = mUsers.get(profileId).info;
529 // If full info is not required - clear PII data to prevent 3P apps from reading it
530 if (!fullInfo) {
531 userInfo = new UserInfo(userInfo);
532 userInfo.name = null;
533 userInfo.iconPath = null;
534 } else {
535 userInfo = userWithName(userInfo);
536 }
537 users.add(userInfo);
538 }
539 return users;
540 }
541
542 /**
543 * Assume permissions already checked and caller's identity cleared
544 */
545 private IntArray getProfileIdsLU(int userId, boolean enabledOnly) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700546 UserInfo user = getUserInfoLU(userId);
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700547 IntArray result = new IntArray(mUsers.size());
Amith Yamasanidda003f2014-08-28 18:06:51 -0700548 if (user == null) {
549 // Probably a dying user
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700550 return result;
Amith Yamasanidda003f2014-08-28 18:06:51 -0700551 }
Amith Yamasani515d4062015-09-28 11:30:06 -0700552 final int userSize = mUsers.size();
553 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800554 UserInfo profile = mUsers.valueAt(i).info;
Amith Yamasanibe465322014-04-24 13:45:17 -0700555 if (!isProfileOf(user, profile)) {
556 continue;
557 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100558 if (enabledOnly && !profile.isEnabled()) {
559 continue;
Amith Yamasanibe465322014-04-24 13:45:17 -0700560 }
Amith Yamasani70fcf0c2014-07-11 08:40:19 -0700561 if (mRemovingUserIds.get(profile.id)) {
562 continue;
563 }
Tony Mak80189cd2016-04-05 17:21:42 +0100564 if (profile.partial) {
565 continue;
566 }
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700567 result.add(profile.id);
Amith Yamasanibe465322014-04-24 13:45:17 -0700568 }
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700569 return result;
Amith Yamasanibe465322014-04-24 13:45:17 -0700570 }
571
Jessica Hummelbe81c802014-04-22 15:49:22 +0100572 @Override
Andres Moralesc5548c02015-08-05 10:23:12 -0700573 public int getCredentialOwnerProfile(int userHandle) {
574 checkManageUsersPermission("get the credential owner");
Clara Bayarria1771112015-12-18 16:29:18 +0000575 if (!mLockPatternUtils.isSeparateProfileChallengeEnabled(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700576 synchronized (mUsersLock) {
577 UserInfo profileParent = getProfileParentLU(userHandle);
Andres Moralesc5548c02015-08-05 10:23:12 -0700578 if (profileParent != null) {
579 return profileParent.id;
580 }
581 }
582 }
583
584 return userHandle;
585 }
586
587 @Override
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700588 public boolean isSameProfileGroup(int userId, int otherUserId) {
589 if (userId == otherUserId) return true;
590 checkManageUsersPermission("check if in the same profile group");
591 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700592 return isSameProfileGroupLP(userId, otherUserId);
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700593 }
594 }
595
Fyodor Kupolov82402752015-10-28 14:54:51 -0700596 private boolean isSameProfileGroupLP(int userId, int otherUserId) {
597 synchronized (mUsersLock) {
598 UserInfo userInfo = getUserInfoLU(userId);
599 if (userInfo == null || userInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
600 return false;
601 }
602 UserInfo otherUserInfo = getUserInfoLU(otherUserId);
603 if (otherUserInfo == null
604 || otherUserInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
605 return false;
606 }
607 return userInfo.profileGroupId == otherUserInfo.profileGroupId;
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700608 }
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700609 }
610
611 @Override
Jessica Hummelbe81c802014-04-22 15:49:22 +0100612 public UserInfo getProfileParent(int userHandle) {
613 checkManageUsersPermission("get the profile parent");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700614 synchronized (mUsersLock) {
615 return getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700616 }
617 }
618
Fyodor Kupolov82402752015-10-28 14:54:51 -0700619 private UserInfo getProfileParentLU(int userHandle) {
620 UserInfo profile = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700621 if (profile == null) {
622 return null;
623 }
624 int parentUserId = profile.profileGroupId;
625 if (parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
626 return null;
627 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700628 return getUserInfoLU(parentUserId);
Jessica Hummelbe81c802014-04-22 15:49:22 +0100629 }
630 }
631
Fyodor Kupolov82402752015-10-28 14:54:51 -0700632 private static boolean isProfileOf(UserInfo user, UserInfo profile) {
Kenny Guy2a764942014-04-02 13:29:20 +0100633 return user.id == profile.id ||
634 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
635 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000636 }
637
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000638 private void broadcastProfileAvailabilityChanges(UserHandle profileHandle,
Rubin Xuf13c9802016-01-21 18:06:00 +0000639 UserHandle parentHandle, boolean inQuietMode) {
Rubin Xue95057a2016-04-01 16:49:25 +0100640 Intent intent = new Intent();
641 if (inQuietMode) {
642 intent.setAction(Intent.ACTION_MANAGED_PROFILE_UNAVAILABLE);
643 } else {
644 intent.setAction(Intent.ACTION_MANAGED_PROFILE_AVAILABLE);
645 }
Rubin Xuf13c9802016-01-21 18:06:00 +0000646 intent.putExtra(Intent.EXTRA_QUIET_MODE, inQuietMode);
647 intent.putExtra(Intent.EXTRA_USER, profileHandle);
648 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileHandle.getIdentifier());
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000649 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Rubin Xuf13c9802016-01-21 18:06:00 +0000650 mContext.sendBroadcastAsUser(intent, parentHandle);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000651 }
652
653 @Override
654 public void setQuietModeEnabled(int userHandle, boolean enableQuietMode) {
655 checkManageUsersPermission("silence profile");
656 boolean changed = false;
657 UserInfo profile, parent;
658 synchronized (mPackagesLock) {
659 synchronized (mUsersLock) {
660 profile = getUserInfoLU(userHandle);
661 parent = getProfileParentLU(userHandle);
662
663 }
664 if (profile == null || !profile.isManagedProfile()) {
665 throw new IllegalArgumentException("User " + userHandle + " is not a profile");
666 }
667 if (profile.isQuietModeEnabled() != enableQuietMode) {
668 profile.flags ^= UserInfo.FLAG_QUIET_MODE;
Amith Yamasani12747872015-12-07 14:19:49 -0800669 writeUserLP(getUserDataLU(profile.id));
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000670 changed = true;
671 }
672 }
673 if (changed) {
Rubin Xuf13c9802016-01-21 18:06:00 +0000674 long identity = Binder.clearCallingIdentity();
675 try {
676 if (enableQuietMode) {
Rubin Xuf8451b92016-04-01 15:50:58 +0100677 LocalServices.getService(ActivityManagerInternal.class)
678 .killForegroundAppsForUser(userHandle);
Rubin Xuf13c9802016-01-21 18:06:00 +0000679 ActivityManagerNative.getDefault().stopUser(userHandle, /* force */true, null);
680 } else {
681 ActivityManagerNative.getDefault().startUserInBackground(userHandle);
682 }
683 } catch (RemoteException e) {
684 Slog.e(LOG_TAG, "fail to start/stop user for quiet mode", e);
685 } finally {
686 Binder.restoreCallingIdentity(identity);
687 }
688
689 broadcastProfileAvailabilityChanges(profile.getUserHandle(), parent.getUserHandle(),
690 enableQuietMode);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000691 }
692 }
693
694 @Override
695 public boolean isQuietModeEnabled(int userHandle) {
696 synchronized (mPackagesLock) {
697 UserInfo info;
698 synchronized (mUsersLock) {
699 info = getUserInfoLU(userHandle);
700 }
701 if (info == null || !info.isManagedProfile()) {
Rubin Xuf13c9802016-01-21 18:06:00 +0000702 return false;
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000703 }
704 return info.isQuietModeEnabled();
705 }
706 }
707
Kenny Guya52dc3e2014-02-11 15:33:14 +0000708 @Override
Benjamin Franzf02420c2016-04-04 18:52:21 +0100709 public boolean trySetQuietModeDisabled(int userHandle, IntentSender target) {
Jeff Sharkeyce18c812016-04-27 16:00:41 -0600710 if (StorageManager.isUserKeyUnlocked(userHandle)
Ricky Wai9cc7ad62016-05-11 18:00:20 +0100711 || !mLockPatternUtils.isSecure(userHandle)) {
Benjamin Franzf02420c2016-04-04 18:52:21 +0100712 // if the user is already unlocked, no need to show a profile challenge
713 setQuietModeEnabled(userHandle, false);
714 return true;
715 }
716
717 long identity = Binder.clearCallingIdentity();
718 try {
719 // otherwise, we show a profile challenge to trigger decryption of the user
720 final KeyguardManager km = (KeyguardManager) mContext.getSystemService(
721 Context.KEYGUARD_SERVICE);
Ricky Wai7881cf82016-04-15 17:20:12 +0100722 // We should use userHandle not credentialOwnerUserId here, as even if it is unified
723 // lock, confirm screenlock page will know and show personal challenge, and unlock
724 // work profile when personal challenge is correct
Benjamin Franzf02420c2016-04-04 18:52:21 +0100725 final Intent unlockIntent = km.createConfirmDeviceCredentialIntent(null, null,
726 userHandle);
727 if (unlockIntent == null) {
728 return false;
729 }
730 if (target != null) {
731 unlockIntent.putExtra(Intent.EXTRA_INTENT, target);
732 }
733 unlockIntent.setFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
734 mContext.startActivity(unlockIntent);
735 } finally {
736 Binder.restoreCallingIdentity(identity);
737 }
738 return false;
739 }
740
741 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100742 public void setUserEnabled(int userId) {
743 checkManageUsersPermission("enable user");
744 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700745 UserInfo info;
746 synchronized (mUsersLock) {
747 info = getUserInfoLU(userId);
748 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100749 if (info != null && !info.isEnabled()) {
750 info.flags ^= UserInfo.FLAG_DISABLED;
Amith Yamasani12747872015-12-07 14:19:49 -0800751 writeUserLP(getUserDataLU(info.id));
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100752 }
753 }
754 }
755
756 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700757 public UserInfo getUserInfo(int userId) {
Tony Mak8673b282016-03-21 21:10:59 +0000758 checkManageUsersPermission("query user");
759 synchronized (mUsersLock) {
Amith Yamasani6f48d6e2016-03-23 14:28:25 -0700760 return userWithName(getUserInfoLU(userId));
761 }
762 }
763
764 /**
765 * Returns a UserInfo object with the name filled in, for Owner, or the original
766 * if the name is already set.
767 */
768 private UserInfo userWithName(UserInfo orig) {
769 if (orig != null && orig.name == null && orig.id == UserHandle.USER_SYSTEM) {
770 UserInfo withName = new UserInfo(orig);
771 withName.name = getOwnerName();
772 return withName;
773 } else {
774 return orig;
Tony Mak8673b282016-03-21 21:10:59 +0000775 }
776 }
777
778 @Override
779 public boolean isManagedProfile(int userId) {
Tony Makb531d082016-03-16 14:49:52 +0000780 int callingUserId = UserHandle.getCallingUserId();
781 if (callingUserId != userId && !hasManageUsersPermission()) {
782 synchronized (mPackagesLock) {
783 if (!isSameProfileGroupLP(callingUserId, userId)) {
784 throw new SecurityException(
Tony Mak8673b282016-03-21 21:10:59 +0000785 "You need MANAGE_USERS permission to: check if specified user a " +
786 "managed profile outside your profile group");
Tony Makb531d082016-03-16 14:49:52 +0000787 }
788 }
Tony Mak4dc008c2016-03-16 10:46:49 +0000789 }
Fyodor Kupolov82402752015-10-28 14:54:51 -0700790 synchronized (mUsersLock) {
Tony Mak8673b282016-03-21 21:10:59 +0000791 UserInfo userInfo = getUserInfoLU(userId);
792 return userInfo != null && userInfo.isManagedProfile();
Amith Yamasani13593602012-03-22 16:16:17 -0700793 }
794 }
795
Amith Yamasani71e6c692013-03-24 17:39:28 -0700796 @Override
797 public boolean isRestricted() {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700798 synchronized (mUsersLock) {
799 return getUserInfoLU(UserHandle.getCallingUserId()).isRestricted();
Amith Yamasani71e6c692013-03-24 17:39:28 -0700800 }
801 }
802
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700803 @Override
804 public boolean canHaveRestrictedProfile(int userId) {
805 checkManageUsersPermission("canHaveRestrictedProfile");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700806 synchronized (mUsersLock) {
807 final UserInfo userInfo = getUserInfoLU(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700808 if (userInfo == null || !userInfo.canHaveProfile()) {
809 return false;
810 }
811 if (!userInfo.isAdmin()) {
812 return false;
813 }
Makoto Onukie7927da2015-11-25 10:05:17 -0800814 // restricted profile can be created if there is no DO set and the admin user has no PO;
815 return !mIsDeviceManaged && !mIsUserManaged.get(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700816 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700817 }
818
Amith Yamasani195263742012-08-21 15:40:12 -0700819 /*
820 * Should be locked on mUsers before calling this.
821 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700822 private UserInfo getUserInfoLU(int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -0800823 final UserData userData = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -0700824 // If it is partial and not in the process of being removed, return as unknown user.
Amith Yamasani12747872015-12-07 14:19:49 -0800825 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700826 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
827 return null;
828 }
Amith Yamasani12747872015-12-07 14:19:49 -0800829 return userData != null ? userData.info : null;
830 }
831
832 private UserData getUserDataLU(int userId) {
833 final UserData userData = mUsers.get(userId);
834 // If it is partial and not in the process of being removed, return as unknown user.
835 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
836 return null;
837 }
838 return userData;
Amith Yamasani195263742012-08-21 15:40:12 -0700839 }
840
Fyodor Kupolov82402752015-10-28 14:54:51 -0700841 /**
842 * Obtains {@link #mUsersLock} and return UserInfo from mUsers.
843 * <p>No permissions checking or any addition checks are made</p>
844 */
845 private UserInfo getUserInfoNoChecks(int userId) {
846 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800847 final UserData userData = mUsers.get(userId);
848 return userData != null ? userData.info : null;
849 }
850 }
851
852 /**
853 * Obtains {@link #mUsersLock} and return UserData from mUsers.
854 * <p>No permissions checking or any addition checks are made</p>
855 */
856 private UserData getUserDataNoChecks(int userId) {
857 synchronized (mUsersLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700858 return mUsers.get(userId);
859 }
860 }
861
Amith Yamasani236b2b52015-08-18 14:32:14 -0700862 /** Called by PackageManagerService */
Amith Yamasani13593602012-03-22 16:16:17 -0700863 public boolean exists(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700864 return getUserInfoNoChecks(userId) != null;
Amith Yamasani13593602012-03-22 16:16:17 -0700865 }
866
Amith Yamasani258848d2012-08-10 17:06:33 -0700867 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700868 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700869 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700870 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700871 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800872 UserData userData = getUserDataNoChecks(userId);
873 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700874 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
875 return;
876 }
Amith Yamasani12747872015-12-07 14:19:49 -0800877 if (name != null && !name.equals(userData.info.name)) {
878 userData.info.name = name;
879 writeUserLP(userData);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700880 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -0700881 }
882 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700883 if (changed) {
884 sendUserInfoChangedBroadcast(userId);
885 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700886 }
887
Amith Yamasani258848d2012-08-10 17:06:33 -0700888 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700889 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700890 checkManageUsersPermission("update users");
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +0100891 if (hasUserRestriction(UserManager.DISALLOW_SET_USER_ICON, userId)) {
892 Log.w(LOG_TAG, "Cannot set user icon. DISALLOW_SET_USER_ICON is enabled.");
893 return;
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700894 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +0100895 mLocalService.setUserIcon(userId, bitmap);
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700896 }
897
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +0100898
899
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700900 private void sendUserInfoChangedBroadcast(int userId) {
901 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
902 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
903 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -0700904 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700905 }
906
Amith Yamasani258848d2012-08-10 17:06:33 -0700907 @Override
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +0100908 public ParcelFileDescriptor getUserIcon(int targetUserId) {
Adrian Roos1bdff912015-02-17 15:51:35 +0100909 String iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700910 synchronized (mPackagesLock) {
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +0100911 UserInfo targetUserInfo = getUserInfoNoChecks(targetUserId);
912 if (targetUserInfo == null || targetUserInfo.partial) {
913 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + targetUserId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700914 return null;
915 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +0100916
917 final int callingUserId = UserHandle.getCallingUserId();
918 final int callingGroupId = getUserInfoNoChecks(callingUserId).profileGroupId;
919 final int targetGroupId = targetUserInfo.profileGroupId;
920 final boolean sameGroup = (callingGroupId != UserInfo.NO_PROFILE_GROUP_ID
921 && callingGroupId == targetGroupId);
922 if ((callingUserId != targetUserId) && !sameGroup) {
Nicolas Prevot88cc3462014-05-14 14:51:48 +0100923 checkManageUsersPermission("get the icon of a user who is not related");
924 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +0100925
926 if (targetUserInfo.iconPath == null) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700927 return null;
928 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +0100929 iconPath = targetUserInfo.iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700930 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100931
932 try {
933 return ParcelFileDescriptor.open(
934 new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
935 } catch (FileNotFoundException e) {
936 Log.e(LOG_TAG, "Couldn't find icon file", e);
937 }
938 return null;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700939 }
940
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700941 public void makeInitialized(int userId) {
942 checkManageUsersPermission("makeInitialized");
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800943 boolean scheduleWriteUser = false;
Amith Yamasani12747872015-12-07 14:19:49 -0800944 UserData userData;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800945 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800946 userData = mUsers.get(userId);
947 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700948 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800949 return;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700950 }
Amith Yamasani12747872015-12-07 14:19:49 -0800951 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
952 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800953 scheduleWriteUser = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700954 }
955 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800956 if (scheduleWriteUser) {
Amith Yamasani12747872015-12-07 14:19:49 -0800957 scheduleWriteUser(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800958 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700959 }
960
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700961 /**
962 * If default guest restrictions haven't been initialized yet, add the basic
963 * restrictions.
964 */
965 private void initDefaultGuestRestrictions() {
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800966 synchronized (mGuestRestrictions) {
967 if (mGuestRestrictions.isEmpty()) {
Samuel Tand9453b82016-03-14 15:57:02 -0700968 mGuestRestrictions.putBoolean(UserManager.DISALLOW_CONFIG_WIFI, true);
Fyodor Kupolove04462c2015-11-30 15:02:53 -0800969 mGuestRestrictions.putBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, true);
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800970 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
971 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
972 }
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700973 }
974 }
975
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800976 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530977 public Bundle getDefaultGuestRestrictions() {
978 checkManageUsersPermission("getDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800979 synchronized (mGuestRestrictions) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530980 return new Bundle(mGuestRestrictions);
981 }
982 }
983
984 @Override
985 public void setDefaultGuestRestrictions(Bundle restrictions) {
986 checkManageUsersPermission("setDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800987 synchronized (mGuestRestrictions) {
988 mGuestRestrictions.clear();
989 mGuestRestrictions.putAll(restrictions);
990 }
991 synchronized (mPackagesLock) {
992 writeUserListLP();
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530993 }
994 }
995
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800996 /**
997 * See {@link UserManagerInternal#setDevicePolicyUserRestrictions(int, Bundle, Bundle)}
998 */
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800999 void setDevicePolicyUserRestrictionsInner(int userId, @NonNull Bundle local,
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001000 @Nullable Bundle global) {
1001 Preconditions.checkNotNull(local);
1002 boolean globalChanged = false;
1003 boolean localChanged;
1004 synchronized (mRestrictionsLock) {
1005 if (global != null) {
1006 // Update global.
1007 globalChanged = !UserRestrictionsUtils.areEqual(
1008 mDevicePolicyGlobalUserRestrictions, global);
1009 if (globalChanged) {
1010 mDevicePolicyGlobalUserRestrictions = global;
1011 }
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001012 // Remember the global restriction owner userId to be able to make a distinction
1013 // in getUserRestrictionSource on who set local policies.
1014 mGlobalRestrictionOwnerUserId = userId;
1015 } else {
1016 // When profile owner sets restrictions it passes null global bundle and we reset
1017 // global restriction owner userId.
1018 mGlobalRestrictionOwnerUserId = UserHandle.USER_NULL;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001019 }
1020 {
1021 // Update local.
1022 final Bundle prev = mDevicePolicyLocalUserRestrictions.get(userId);
1023 localChanged = !UserRestrictionsUtils.areEqual(prev, local);
1024 if (localChanged) {
1025 mDevicePolicyLocalUserRestrictions.put(userId, local);
1026 }
1027 }
1028 }
1029 if (DBG) {
1030 Log.d(LOG_TAG, "setDevicePolicyUserRestrictions: userId=" + userId
1031 + " global=" + global + (globalChanged ? " (changed)" : "")
1032 + " local=" + local + (localChanged ? " (changed)" : "")
1033 );
1034 }
1035 // Don't call them within the mRestrictionsLock.
1036 synchronized (mPackagesLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001037 if (localChanged) {
Amith Yamasani12747872015-12-07 14:19:49 -08001038 writeUserLP(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001039 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06001040 if (globalChanged) {
1041 writeUserListLP();
1042 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001043 }
1044
1045 synchronized (mRestrictionsLock) {
1046 if (globalChanged) {
1047 applyUserRestrictionsForAllUsersLR();
1048 } else if (localChanged) {
1049 applyUserRestrictionsLR(userId);
1050 }
1051 }
1052 }
1053
Makoto Onuki068c54a2015-10-13 14:34:03 -07001054 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001055 private Bundle computeEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001056 final Bundle baseRestrictions =
1057 UserRestrictionsUtils.nonNull(mBaseUserRestrictions.get(userId));
1058 final Bundle global = mDevicePolicyGlobalUserRestrictions;
1059 final Bundle local = mDevicePolicyLocalUserRestrictions.get(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001060
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001061 if (UserRestrictionsUtils.isEmpty(global) && UserRestrictionsUtils.isEmpty(local)) {
1062 // Common case first.
1063 return baseRestrictions;
Makoto Onuki068c54a2015-10-13 14:34:03 -07001064 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001065 final Bundle effective = UserRestrictionsUtils.clone(baseRestrictions);
1066 UserRestrictionsUtils.merge(effective, global);
1067 UserRestrictionsUtils.merge(effective, local);
1068
Makoto Onuki068c54a2015-10-13 14:34:03 -07001069 return effective;
1070 }
1071
1072 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001073 private void invalidateEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki068c54a2015-10-13 14:34:03 -07001074 if (DBG) {
1075 Log.d(LOG_TAG, "invalidateEffectiveUserRestrictions userId=" + userId);
1076 }
1077 mCachedEffectiveUserRestrictions.remove(userId);
1078 }
1079
1080 private Bundle getEffectiveUserRestrictions(int userId) {
1081 synchronized (mRestrictionsLock) {
1082 Bundle restrictions = mCachedEffectiveUserRestrictions.get(userId);
1083 if (restrictions == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001084 restrictions = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001085 mCachedEffectiveUserRestrictions.put(userId, restrictions);
1086 }
1087 return restrictions;
Amith Yamasani8cd28b52014-06-08 17:54:27 -07001088 }
1089 }
1090
Makoto Onuki068c54a2015-10-13 14:34:03 -07001091 /** @return a specific user restriction that's in effect currently. */
1092 @Override
1093 public boolean hasUserRestriction(String restrictionKey, int userId) {
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001094 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1095 return false;
1096 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001097 Bundle restrictions = getEffectiveUserRestrictions(userId);
1098 return restrictions != null && restrictions.getBoolean(restrictionKey);
1099 }
1100
1101 /**
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001102 * @hide
1103 *
1104 * Returns who set a user restriction on a user.
1105 * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
1106 * @param restrictionKey the string key representing the restriction
1107 * @param userId the id of the user for whom to retrieve the restrictions.
1108 * @return The source of user restriction. Any combination of
1109 * {@link UserManager#RESTRICTION_NOT_SET},
1110 * {@link UserManager#RESTRICTION_SOURCE_SYSTEM},
1111 * {@link UserManager#RESTRICTION_SOURCE_DEVICE_OWNER}
1112 * and {@link UserManager#RESTRICTION_SOURCE_PROFILE_OWNER}
1113 */
1114 @Override
1115 public int getUserRestrictionSource(String restrictionKey, int userId) {
1116 checkManageUsersPermission("getUserRestrictionSource");
1117 int result = UserManager.RESTRICTION_NOT_SET;
1118
1119 // Shortcut for the most common case
1120 if (!hasUserRestriction(restrictionKey, userId)) {
1121 return result;
1122 }
1123
1124 if (hasBaseUserRestriction(restrictionKey, userId)) {
1125 result |= UserManager.RESTRICTION_SOURCE_SYSTEM;
1126 }
1127
1128 synchronized(mRestrictionsLock) {
1129 Bundle localRestrictions = mDevicePolicyLocalUserRestrictions.get(userId);
1130 if (!UserRestrictionsUtils.isEmpty(localRestrictions)
1131 && localRestrictions.getBoolean(restrictionKey)) {
1132 // Local restrictions may have been set by device owner the userId of which is
1133 // stored in mGlobalRestrictionOwnerUserId.
1134 if (mGlobalRestrictionOwnerUserId == userId) {
1135 result |= UserManager.RESTRICTION_SOURCE_DEVICE_OWNER;
1136 } else {
1137 result |= UserManager.RESTRICTION_SOURCE_PROFILE_OWNER;
1138 }
1139 }
1140 if (!UserRestrictionsUtils.isEmpty(mDevicePolicyGlobalUserRestrictions)
1141 && mDevicePolicyGlobalUserRestrictions.getBoolean(restrictionKey)) {
1142 result |= UserManager.RESTRICTION_SOURCE_DEVICE_OWNER;
1143 }
1144 }
1145
1146 return result;
1147 }
1148
1149 /**
Makoto Onuki068c54a2015-10-13 14:34:03 -07001150 * @return UserRestrictions that are in effect currently. This always returns a new
1151 * {@link Bundle}.
1152 */
Amith Yamasani8cd28b52014-06-08 17:54:27 -07001153 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001154 public Bundle getUserRestrictions(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001155 return UserRestrictionsUtils.clone(getEffectiveUserRestrictions(userId));
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001156 }
1157
1158 @Override
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +00001159 public boolean hasBaseUserRestriction(String restrictionKey, int userId) {
1160 checkManageUsersPermission("hasBaseUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001161 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1162 return false;
1163 }
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +00001164 synchronized (mRestrictionsLock) {
1165 Bundle bundle = mBaseUserRestrictions.get(userId);
1166 return (bundle != null && bundle.getBoolean(restrictionKey, false));
1167 }
1168 }
1169
1170 @Override
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001171 public void setUserRestriction(String key, boolean value, int userId) {
Fyodor Kupolovd4b26042015-07-27 14:30:59 -07001172 checkManageUsersPermission("setUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001173 if (!UserRestrictionsUtils.isValidRestriction(key)) {
1174 return;
1175 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001176 synchronized (mRestrictionsLock) {
1177 // Note we can't modify Bundles stored in mBaseUserRestrictions directly, so create
1178 // a copy.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001179 final Bundle newRestrictions = UserRestrictionsUtils.clone(
1180 mBaseUserRestrictions.get(userId));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001181 newRestrictions.putBoolean(key, value);
1182
Fyodor Kupolov82402752015-10-28 14:54:51 -07001183 updateUserRestrictionsInternalLR(newRestrictions, userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001184 }
1185 }
1186
Makoto Onuki068c54a2015-10-13 14:34:03 -07001187 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001188 * Optionally updating user restrictions, calculate the effective user restrictions and also
1189 * propagate to other services and system settings.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001190 *
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001191 * @param newRestrictions User restrictions to set.
1192 * If null, will not update user restrictions and only does the propagation.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001193 * @param userId target user ID.
1194 */
1195 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001196 private void updateUserRestrictionsInternalLR(
Makoto Onuki068c54a2015-10-13 14:34:03 -07001197 @Nullable Bundle newRestrictions, int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001198
1199 final Bundle prevAppliedRestrictions = UserRestrictionsUtils.nonNull(
1200 mAppliedUserRestrictions.get(userId));
1201
1202 // Update base restrictions.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001203 if (newRestrictions != null) {
1204 // If newRestrictions == the current one, it's probably a bug.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001205 final Bundle prevBaseRestrictions = mBaseUserRestrictions.get(userId);
1206
1207 Preconditions.checkState(prevBaseRestrictions != newRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001208 Preconditions.checkState(mCachedEffectiveUserRestrictions.get(userId)
1209 != newRestrictions);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001210
1211 if (!UserRestrictionsUtils.areEqual(prevBaseRestrictions, newRestrictions)) {
1212 mBaseUserRestrictions.put(userId, newRestrictions);
Amith Yamasani12747872015-12-07 14:19:49 -08001213 scheduleWriteUser(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001214 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001215 }
1216
Fyodor Kupolov82402752015-10-28 14:54:51 -07001217 final Bundle effective = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001218
Makoto Onuki759a7632015-10-28 16:43:10 -07001219 mCachedEffectiveUserRestrictions.put(userId, effective);
1220
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001221 // Apply the new restrictions.
Makoto Onuki4f160732015-10-27 17:15:38 -07001222 if (DBG) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001223 debug("Applying user restrictions: userId=" + userId
1224 + " new=" + effective + " prev=" + prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001225 }
1226
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001227 if (mAppOpsService != null) { // We skip it until system-ready.
1228 final long token = Binder.clearCallingIdentity();
1229 try {
Svet Ganov9cea80cd2016-02-16 11:47:00 -08001230 mAppOpsService.setUserRestrictions(effective, mUserRestriconToken, userId);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001231 } catch (RemoteException e) {
1232 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
1233 } finally {
1234 Binder.restoreCallingIdentity(token);
1235 }
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001236 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001237
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001238 propagateUserRestrictionsLR(userId, effective, prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001239
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001240 mAppliedUserRestrictions.put(userId, new Bundle(effective));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001241 }
1242
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001243 private void propagateUserRestrictionsLR(final int userId,
Makoto Onukid45a4a22015-11-02 17:17:38 -08001244 Bundle newRestrictions, Bundle prevRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001245 // Note this method doesn't touch any state, meaning it doesn't require mRestrictionsLock
1246 // actually, but we still need some kind of synchronization otherwise we might end up
1247 // calling listeners out-of-order, thus "LR".
1248
1249 if (UserRestrictionsUtils.areEqual(newRestrictions, prevRestrictions)) {
1250 return;
1251 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08001252
1253 final Bundle newRestrictionsFinal = new Bundle(newRestrictions);
1254 final Bundle prevRestrictionsFinal = new Bundle(prevRestrictions);
1255
1256 mHandler.post(new Runnable() {
1257 @Override
1258 public void run() {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07001259 UserRestrictionsUtils.applyUserRestrictions(
1260 mContext, userId, newRestrictionsFinal, prevRestrictionsFinal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001261
Makoto Onukid45a4a22015-11-02 17:17:38 -08001262 final UserRestrictionsListener[] listeners;
1263 synchronized (mUserRestrictionsListeners) {
1264 listeners = new UserRestrictionsListener[mUserRestrictionsListeners.size()];
1265 mUserRestrictionsListeners.toArray(listeners);
1266 }
1267 for (int i = 0; i < listeners.length; i++) {
1268 listeners[i].onUserRestrictionsChanged(userId,
1269 newRestrictionsFinal, prevRestrictionsFinal);
1270 }
1271 }
1272 });
1273 }
1274
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001275 // Package private for the inner class.
1276 void applyUserRestrictionsLR(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001277 updateUserRestrictionsInternalLR(null, userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001278 }
1279
1280 @GuardedBy("mRestrictionsLock")
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001281 // Package private for the inner class.
1282 void applyUserRestrictionsForAllUsersLR() {
1283 if (DBG) {
1284 debug("applyUserRestrictionsForAllUsersLR");
1285 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001286 // First, invalidate all cached values.
Makoto Onuki4f160732015-10-27 17:15:38 -07001287 mCachedEffectiveUserRestrictions.clear();
1288
Makoto Onuki068c54a2015-10-13 14:34:03 -07001289 // We don't want to call into ActivityManagerNative while taking a lock, so we'll call
1290 // it on a handler.
1291 final Runnable r = new Runnable() {
1292 @Override
1293 public void run() {
1294 // Then get the list of running users.
1295 final int[] runningUsers;
1296 try {
1297 runningUsers = ActivityManagerNative.getDefault().getRunningUserIds();
1298 } catch (RemoteException e) {
1299 Log.w(LOG_TAG, "Unable to access ActivityManagerNative");
1300 return;
1301 }
1302 // Then re-calculate the effective restrictions and apply, only for running users.
1303 // It's okay if a new user has started after the getRunningUserIds() call,
1304 // because we'll do the same thing (re-calculate the restrictions and apply)
1305 // when we start a user.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001306 synchronized (mRestrictionsLock) {
1307 for (int i = 0; i < runningUsers.length; i++) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001308 applyUserRestrictionsLR(runningUsers[i]);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001309 }
1310 }
1311 }
1312 };
1313 mHandler.post(r);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001314 }
1315
Amith Yamasani258848d2012-08-10 17:06:33 -07001316 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001317 * Check if we've hit the limit of how many users can be created.
1318 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001319 private boolean isUserLimitReached() {
1320 int count;
1321 synchronized (mUsersLock) {
1322 count = getAliveUsersExcludingGuestsCountLU();
1323 }
1324 return count >= UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001325 }
1326
1327 @Override
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001328 public boolean canAddMoreManagedProfiles(int userId, boolean allowedToRemoveOne) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001329 checkManageUsersPermission("check if more managed profiles can be added.");
1330 if (ActivityManager.isLowRamDeviceStatic()) {
1331 return false;
1332 }
Fyodor Kupolovb6157992015-06-05 15:32:28 -07001333 if (!mContext.getPackageManager().hasSystemFeature(
1334 PackageManager.FEATURE_MANAGED_USERS)) {
1335 return false;
1336 }
Nicolas Prevotb8186812015-08-06 15:00:03 +01001337 // Limit number of managed profiles that can be created
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001338 final int managedProfilesCount = getProfiles(userId, true).size() - 1;
1339 final int profilesRemovedCount = managedProfilesCount > 0 && allowedToRemoveOne ? 1 : 0;
1340 if (managedProfilesCount - profilesRemovedCount >= MAX_MANAGED_PROFILES) {
Nicolas Prevotb8186812015-08-06 15:00:03 +01001341 return false;
1342 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001343 synchronized(mUsersLock) {
1344 UserInfo userInfo = getUserInfoLU(userId);
Nicolas Prevotb8186812015-08-06 15:00:03 +01001345 if (!userInfo.canHaveProfile()) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001346 return false;
1347 }
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001348 int usersCountAfterRemoving = getAliveUsersExcludingGuestsCountLU()
1349 - profilesRemovedCount;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001350 // We allow creating a managed profile in the special case where there is only one user.
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001351 return usersCountAfterRemoving == 1
1352 || usersCountAfterRemoving < UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001353 }
1354 }
1355
Fyodor Kupolov82402752015-10-28 14:54:51 -07001356 private int getAliveUsersExcludingGuestsCountLU() {
Amith Yamasanif584f012014-05-19 17:57:25 -07001357 int aliveUserCount = 0;
1358 final int totalUserCount = mUsers.size();
1359 // Skip over users being removed
1360 for (int i = 0; i < totalUserCount; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001361 UserInfo user = mUsers.valueAt(i).info;
Amith Yamasani95ab7842014-08-11 17:09:26 -07001362 if (!mRemovingUserIds.get(user.id)
Amith Yamasani1df14732014-08-29 21:37:27 -07001363 && !user.isGuest() && !user.partial) {
Amith Yamasanif584f012014-05-19 17:57:25 -07001364 aliveUserCount++;
1365 }
1366 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001367 return aliveUserCount;
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001368 }
1369
1370 /**
Amith Yamasani195263742012-08-21 15:40:12 -07001371 * Enforces that only the system UID or root's UID or apps that have the
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001372 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} and
1373 * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL INTERACT_ACROSS_USERS_FULL}
1374 * permissions can make certain calls to the UserManager.
1375 *
1376 * @param message used as message if SecurityException is thrown
1377 * @throws SecurityException if the caller does not have enough privilege.
1378 */
1379 private static final void checkManageUserAndAcrossUsersFullPermission(String message) {
1380 final int uid = Binder.getCallingUid();
1381 if (uid != Process.SYSTEM_UID && uid != 0
1382 && ActivityManager.checkComponentPermission(
1383 Manifest.permission.MANAGE_USERS,
1384 uid, -1, true) != PackageManager.PERMISSION_GRANTED
1385 && ActivityManager.checkComponentPermission(
1386 Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1387 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
1388 throw new SecurityException(
1389 "You need MANAGE_USERS and INTERACT_ACROSS_USERS_FULL permission to: "
1390 + message);
1391 }
1392 }
1393
1394 /**
1395 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001396 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -07001397 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -07001398 *
1399 * @param message used as message if SecurityException is thrown
1400 * @throws SecurityException if the caller is not system or root
Tony Mak4dc008c2016-03-16 10:46:49 +00001401 * @see #hasManageUsersPermission()
Amith Yamasani258848d2012-08-10 17:06:33 -07001402 */
Amith Yamasanibe465322014-04-24 13:45:17 -07001403 private static final void checkManageUsersPermission(String message) {
Tony Mak4dc008c2016-03-16 10:46:49 +00001404 if (!hasManageUsersPermission()) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001405 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
1406 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -04001407 }
1408
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001409 /**
Tony Mak4dc008c2016-03-16 10:46:49 +00001410 * @return whether the calling UID is system UID or root's UID or the calling app has the
1411 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}.
1412 */
1413 private static final boolean hasManageUsersPermission() {
1414 final int callingUid = Binder.getCallingUid();
1415 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
1416 || callingUid == Process.ROOT_UID
1417 || ActivityManager.checkComponentPermission(
1418 android.Manifest.permission.MANAGE_USERS,
1419 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED;
1420 }
1421
1422 /**
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001423 * Enforces that only the system UID or root's UID (on any user) can make certain calls to the
1424 * UserManager.
1425 *
1426 * @param message used as message if SecurityException is thrown
1427 * @throws SecurityException if the caller is not system or root
1428 */
1429 private static void checkSystemOrRoot(String message) {
1430 final int uid = Binder.getCallingUid();
1431 if (!UserHandle.isSameApp(uid, Process.SYSTEM_UID) && uid != Process.ROOT_UID) {
1432 throw new SecurityException("Only system may: " + message);
1433 }
1434 }
1435
Fyodor Kupolov82402752015-10-28 14:54:51 -07001436 private void writeBitmapLP(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001437 try {
1438 File dir = new File(mUsersDir, Integer.toString(info.id));
1439 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +01001440 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001441 if (!dir.exists()) {
1442 dir.mkdir();
1443 FileUtils.setPermissions(
1444 dir.getPath(),
1445 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
1446 -1, -1);
1447 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001448 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +01001449 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001450 && tmp.renameTo(file) && SELinux.restorecon(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -07001451 info.iconPath = file.getAbsolutePath();
1452 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001453 try {
1454 os.close();
1455 } catch (IOException ioe) {
1456 // What the ... !
1457 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001458 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001459 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001460 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001461 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001462 }
1463
Amith Yamasani0b285492011-04-14 17:35:23 -07001464 /**
1465 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
1466 * cache it elsewhere.
1467 * @return the array of user ids.
1468 */
Dianne Hackborn1676c852012-09-10 14:52:30 -07001469 public int[] getUserIds() {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001470 synchronized (mUsersLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001471 return mUserIds;
1472 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001473 }
1474
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001475 private void readUserListLP() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001476 if (!mUserListFile.exists()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001477 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001478 return;
1479 }
1480 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001481 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001482 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001483 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001484 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001485 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001486 int type;
1487 while ((type = parser.next()) != XmlPullParser.START_TAG
1488 && type != XmlPullParser.END_DOCUMENT) {
Amith Yamasani12747872015-12-07 14:19:49 -08001489 // Skip
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001490 }
1491
1492 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001493 Slog.e(LOG_TAG, "Unable to read user list");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001494 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001495 return;
1496 }
1497
Amith Yamasani2a003292012-08-14 18:25:45 -07001498 mNextSerialNumber = -1;
1499 if (parser.getName().equals(TAG_USERS)) {
1500 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
1501 if (lastSerialNumber != null) {
1502 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
1503 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001504 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
1505 if (versionNumber != null) {
1506 mUserVersion = Integer.parseInt(versionNumber);
1507 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001508 }
1509
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001510 final Bundle newDevicePolicyGlobalUserRestrictions = new Bundle();
1511
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001512 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301513 if (type == XmlPullParser.START_TAG) {
1514 final String name = parser.getName();
1515 if (name.equals(TAG_USER)) {
1516 String id = parser.getAttributeValue(null, ATTR_ID);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001517
Amith Yamasani12747872015-12-07 14:19:49 -08001518 UserData userData = readUserLP(Integer.parseInt(id));
1519
1520 if (userData != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001521 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001522 mUsers.put(userData.info.id, userData);
1523 if (mNextSerialNumber < 0
1524 || mNextSerialNumber <= userData.info.id) {
1525 mNextSerialNumber = userData.info.id + 1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001526 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301527 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001528 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301529 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -08001530 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1531 && type != XmlPullParser.END_TAG) {
1532 if (type == XmlPullParser.START_TAG) {
1533 if (parser.getName().equals(TAG_RESTRICTIONS)) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001534 synchronized (mGuestRestrictions) {
1535 UserRestrictionsUtils
1536 .readRestrictions(parser, mGuestRestrictions);
1537 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001538 } else if (parser.getName().equals(TAG_DEVICE_POLICY_RESTRICTIONS)
1539 ) {
1540 UserRestrictionsUtils.readRestrictions(parser,
1541 newDevicePolicyGlobalUserRestrictions);
Amith Yamasanida0b1682014-11-21 12:58:17 -08001542 }
1543 break;
1544 }
1545 }
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001546 } else if (name.equals(TAG_GLOBAL_RESTRICTION_OWNER_ID)) {
1547 String ownerUserId = parser.getAttributeValue(null, ATTR_ID);
1548 if (ownerUserId != null) {
1549 mGlobalRestrictionOwnerUserId = Integer.parseInt(ownerUserId);
1550 }
Amith Yamasani258848d2012-08-10 17:06:33 -07001551 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001552 }
1553 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001554 synchronized (mRestrictionsLock) {
1555 mDevicePolicyGlobalUserRestrictions = newDevicePolicyGlobalUserRestrictions;
1556 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001557 updateUserIds();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001558 upgradeIfNecessaryLP();
1559 } catch (IOException | XmlPullParserException e) {
1560 fallbackToSingleUserLP();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001561 } finally {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001562 IoUtils.closeQuietly(fis);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001563 }
1564 }
1565
Amith Yamasani6f34b412012-10-22 18:19:27 -07001566 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -08001567 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -07001568 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001569 private void upgradeIfNecessaryLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001570 final int originalVersion = mUserVersion;
Amith Yamasani6f34b412012-10-22 18:19:27 -07001571 int userVersion = mUserVersion;
1572 if (userVersion < 1) {
1573 // Assign a proper name for the owner, if not initialized correctly before
Amith Yamasani12747872015-12-07 14:19:49 -08001574 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
1575 if ("Primary".equals(userData.info.name)) {
1576 userData.info.name =
1577 mContext.getResources().getString(com.android.internal.R.string.owner_name);
1578 scheduleWriteUser(userData);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001579 }
1580 userVersion = 1;
1581 }
1582
Amith Yamasanibc9625052012-11-15 14:39:18 -08001583 if (userVersion < 2) {
1584 // Owner should be marked as initialized
Amith Yamasani12747872015-12-07 14:19:49 -08001585 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
1586 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1587 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
1588 scheduleWriteUser(userData);
Amith Yamasanibc9625052012-11-15 14:39:18 -08001589 }
1590 userVersion = 2;
1591 }
1592
Amith Yamasani350962c2013-08-06 11:18:53 -07001593
Amith Yamasani5e486f52013-08-07 11:06:44 -07001594 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -07001595 userVersion = 4;
1596 }
1597
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001598 if (userVersion < 5) {
1599 initDefaultGuestRestrictions();
1600 userVersion = 5;
1601 }
1602
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001603 if (userVersion < 6) {
1604 final boolean splitSystemUser = UserManager.isSplitSystemUser();
Fyodor Kupolov82402752015-10-28 14:54:51 -07001605 synchronized (mUsersLock) {
1606 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001607 UserData userData = mUsers.valueAt(i);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001608 // In non-split mode, only user 0 can have restricted profiles
Amith Yamasani12747872015-12-07 14:19:49 -08001609 if (!splitSystemUser && userData.info.isRestricted()
1610 && (userData.info.restrictedProfileParentId
1611 == UserInfo.NO_PROFILE_GROUP_ID)) {
1612 userData.info.restrictedProfileParentId = UserHandle.USER_SYSTEM;
1613 scheduleWriteUser(userData);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001614 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001615 }
1616 }
1617 userVersion = 6;
1618 }
1619
Amith Yamasani6f34b412012-10-22 18:19:27 -07001620 if (userVersion < USER_VERSION) {
1621 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
1622 + USER_VERSION);
1623 } else {
1624 mUserVersion = userVersion;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001625
1626 if (originalVersion < mUserVersion) {
1627 writeUserListLP();
1628 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001629 }
1630 }
1631
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001632 private void fallbackToSingleUserLP() {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001633 int flags = UserInfo.FLAG_INITIALIZED;
1634 // In split system user mode, the admin and primary flags are assigned to the first human
1635 // user.
1636 if (!UserManager.isSplitSystemUser()) {
1637 flags |= UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY;
1638 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001639 // Create the system user
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001640 UserInfo system = new UserInfo(UserHandle.USER_SYSTEM, null, null, flags);
Amith Yamasani12747872015-12-07 14:19:49 -08001641 UserData userData = new UserData();
1642 userData.info = system;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001643 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001644 mUsers.put(system.id, userData);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001645 }
Amith Yamasani634cf312012-10-04 17:34:21 -07001646 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -04001647 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -08001648
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001649 Bundle restrictions = new Bundle();
Makoto Onuki068c54a2015-10-13 14:34:03 -07001650 synchronized (mRestrictionsLock) {
1651 mBaseUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions);
1652 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001653
Fyodor Kupolov82402752015-10-28 14:54:51 -07001654 updateUserIds();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001655 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001656
Amith Yamasani12747872015-12-07 14:19:49 -08001657 writeUserLP(userData);
Jeff Sharkeycd575992016-03-29 14:12:49 -06001658 writeUserListLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001659 }
1660
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001661 private String getOwnerName() {
1662 return mContext.getResources().getString(com.android.internal.R.string.owner_name);
1663 }
1664
Amith Yamasani12747872015-12-07 14:19:49 -08001665 private void scheduleWriteUser(UserData UserData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001666 if (DBG) {
1667 debug("scheduleWriteUser");
1668 }
Makoto Onuki9e935a32015-11-06 14:24:24 -08001669 // No need to wrap it within a lock -- worst case, we'll just post the same message
1670 // twice.
Amith Yamasani12747872015-12-07 14:19:49 -08001671 if (!mHandler.hasMessages(WRITE_USER_MSG, UserData)) {
1672 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, UserData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001673 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
1674 }
1675 }
1676
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001677 /*
1678 * Writes the user file in this format:
1679 *
1680 * <user flags="20039023" id="0">
1681 * <name>Primary</name>
1682 * </user>
1683 */
Amith Yamasani12747872015-12-07 14:19:49 -08001684 private void writeUserLP(UserData userData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001685 if (DBG) {
Amith Yamasani12747872015-12-07 14:19:49 -08001686 debug("writeUserLP " + userData);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001687 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001688 FileOutputStream fos = null;
Amith Yamasani12747872015-12-07 14:19:49 -08001689 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userData.info.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001690 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001691 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001692 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1693
1694 // XmlSerializer serializer = XmlUtils.serializerInstance();
1695 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001696 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001697 serializer.startDocument(null, true);
1698 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1699
Amith Yamasani12747872015-12-07 14:19:49 -08001700 final UserInfo userInfo = userData.info;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001701 serializer.startTag(null, TAG_USER);
1702 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
Amith Yamasani2a003292012-08-14 18:25:45 -07001703 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001704 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Amith Yamasani920ace02012-09-20 22:15:37 -07001705 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
1706 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
1707 Long.toString(userInfo.lastLoggedInTime));
Jeff Sharkeycd575992016-03-29 14:12:49 -06001708 if (userInfo.lastLoggedInFingerprint != null) {
1709 serializer.attribute(null, ATTR_LAST_LOGGED_IN_FINGERPRINT,
1710 userInfo.lastLoggedInFingerprint);
1711 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001712 if (userInfo.iconPath != null) {
1713 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
1714 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001715 if (userInfo.partial) {
1716 serializer.attribute(null, ATTR_PARTIAL, "true");
1717 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001718 if (userInfo.guestToRemove) {
1719 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
1720 }
Kenny Guy2a764942014-04-02 13:29:20 +01001721 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
1722 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
1723 Integer.toString(userInfo.profileGroupId));
Kenny Guya52dc3e2014-02-11 15:33:14 +00001724 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001725 if (userInfo.restrictedProfileParentId != UserInfo.NO_PROFILE_GROUP_ID) {
1726 serializer.attribute(null, ATTR_RESTRICTED_PROFILE_PARENT_ID,
1727 Integer.toString(userInfo.restrictedProfileParentId));
1728 }
Amith Yamasani12747872015-12-07 14:19:49 -08001729 // Write seed data
1730 if (userData.persistSeedData) {
1731 if (userData.seedAccountName != null) {
1732 serializer.attribute(null, ATTR_SEED_ACCOUNT_NAME, userData.seedAccountName);
1733 }
1734 if (userData.seedAccountType != null) {
1735 serializer.attribute(null, ATTR_SEED_ACCOUNT_TYPE, userData.seedAccountType);
1736 }
1737 }
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001738 if (userInfo.name != null) {
1739 serializer.startTag(null, TAG_NAME);
1740 serializer.text(userInfo.name);
1741 serializer.endTag(null, TAG_NAME);
1742 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001743 synchronized (mRestrictionsLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001744 UserRestrictionsUtils.writeRestrictions(serializer,
1745 mBaseUserRestrictions.get(userInfo.id), TAG_RESTRICTIONS);
1746 UserRestrictionsUtils.writeRestrictions(serializer,
1747 mDevicePolicyLocalUserRestrictions.get(userInfo.id),
1748 TAG_DEVICE_POLICY_RESTRICTIONS);
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001749 }
Amith Yamasani12747872015-12-07 14:19:49 -08001750
1751 if (userData.account != null) {
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001752 serializer.startTag(null, TAG_ACCOUNT);
Amith Yamasani12747872015-12-07 14:19:49 -08001753 serializer.text(userData.account);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001754 serializer.endTag(null, TAG_ACCOUNT);
1755 }
1756
Amith Yamasani12747872015-12-07 14:19:49 -08001757 if (userData.persistSeedData && userData.seedAccountOptions != null) {
1758 serializer.startTag(null, TAG_SEED_ACCOUNT_OPTIONS);
1759 userData.seedAccountOptions.saveToXml(serializer);
1760 serializer.endTag(null, TAG_SEED_ACCOUNT_OPTIONS);
1761 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001762 serializer.endTag(null, TAG_USER);
1763
1764 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001765 userFile.finishWrite(fos);
1766 } catch (Exception ioe) {
Jeff Sharkeycd575992016-03-29 14:12:49 -06001767 Slog.e(LOG_TAG, "Error writing user info " + userData.info.id, ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -07001768 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001769 }
1770 }
1771
1772 /*
1773 * Writes the user list file in this format:
1774 *
Amith Yamasani2a003292012-08-14 18:25:45 -07001775 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001776 * <user id="0"></user>
1777 * <user id="2"></user>
1778 * </users>
1779 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001780 private void writeUserListLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001781 if (DBG) {
1782 debug("writeUserList");
1783 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001784 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001785 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001786 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001787 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001788 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1789
1790 // XmlSerializer serializer = XmlUtils.serializerInstance();
1791 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001792 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001793 serializer.startDocument(null, true);
1794 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1795
1796 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -07001797 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -07001798 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001799
Adam Lesinskieddeb492014-09-08 17:50:03 -07001800 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001801 synchronized (mGuestRestrictions) {
1802 UserRestrictionsUtils
1803 .writeRestrictions(serializer, mGuestRestrictions, TAG_RESTRICTIONS);
1804 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301805 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001806 synchronized (mRestrictionsLock) {
1807 UserRestrictionsUtils.writeRestrictions(serializer,
1808 mDevicePolicyGlobalUserRestrictions, TAG_DEVICE_POLICY_RESTRICTIONS);
1809 }
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001810 serializer.startTag(null, TAG_GLOBAL_RESTRICTION_OWNER_ID);
1811 serializer.attribute(null, ATTR_ID, Integer.toString(mGlobalRestrictionOwnerUserId));
1812 serializer.endTag(null, TAG_GLOBAL_RESTRICTION_OWNER_ID);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001813 int[] userIdsToWrite;
1814 synchronized (mUsersLock) {
1815 userIdsToWrite = new int[mUsers.size()];
1816 for (int i = 0; i < userIdsToWrite.length; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001817 UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001818 userIdsToWrite[i] = user.id;
1819 }
1820 }
1821 for (int id : userIdsToWrite) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001822 serializer.startTag(null, TAG_USER);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001823 serializer.attribute(null, ATTR_ID, Integer.toString(id));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001824 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001825 }
1826
1827 serializer.endTag(null, TAG_USERS);
1828
1829 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001830 userListFile.finishWrite(fos);
1831 } catch (Exception e) {
1832 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -07001833 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001834 }
1835 }
1836
Amith Yamasani12747872015-12-07 14:19:49 -08001837 private UserData readUserLP(int id) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001838 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -07001839 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001840 String name = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001841 String account = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001842 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -07001843 long creationTime = 0L;
1844 long lastLoggedInTime = 0L;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06001845 String lastLoggedInFingerprint = null;
Kenny Guy2a764942014-04-02 13:29:20 +01001846 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001847 int restrictedProfileParentId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001848 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001849 boolean guestToRemove = false;
Amith Yamasani12747872015-12-07 14:19:49 -08001850 boolean persistSeedData = false;
1851 String seedAccountName = null;
1852 String seedAccountType = null;
1853 PersistableBundle seedAccountOptions = null;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001854 Bundle baseRestrictions = new Bundle();
1855 Bundle localRestrictions = new Bundle();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001856
1857 FileInputStream fis = null;
1858 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001859 AtomicFile userFile =
Amith Yamasanifc95e702013-09-26 13:20:17 -07001860 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
Amith Yamasani2a003292012-08-14 18:25:45 -07001861 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001862 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001863 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001864 int type;
1865 while ((type = parser.next()) != XmlPullParser.START_TAG
1866 && type != XmlPullParser.END_DOCUMENT) {
Amith Yamasani12747872015-12-07 14:19:49 -08001867 // Skip
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001868 }
1869
1870 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001871 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001872 return null;
1873 }
1874
1875 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001876 int storedId = readIntAttribute(parser, ATTR_ID, -1);
1877 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001878 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001879 return null;
1880 }
Amith Yamasani920ace02012-09-20 22:15:37 -07001881 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
1882 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001883 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -07001884 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
1885 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06001886 lastLoggedInFingerprint = parser.getAttributeValue(null,
1887 ATTR_LAST_LOGGED_IN_FINGERPRINT);
Kenny Guy2a764942014-04-02 13:29:20 +01001888 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
1889 UserInfo.NO_PROFILE_GROUP_ID);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001890 restrictedProfileParentId = readIntAttribute(parser,
1891 ATTR_RESTRICTED_PROFILE_PARENT_ID, UserInfo.NO_PROFILE_GROUP_ID);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001892 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
1893 if ("true".equals(valueString)) {
1894 partial = true;
1895 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001896 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
1897 if ("true".equals(valueString)) {
1898 guestToRemove = true;
1899 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001900
Amith Yamasani12747872015-12-07 14:19:49 -08001901 seedAccountName = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_NAME);
1902 seedAccountType = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_TYPE);
1903 if (seedAccountName != null || seedAccountType != null) {
1904 persistSeedData = true;
1905 }
1906
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001907 int outerDepth = parser.getDepth();
1908 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1909 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1910 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1911 continue;
1912 }
1913 String tag = parser.getName();
1914 if (TAG_NAME.equals(tag)) {
1915 type = parser.next();
1916 if (type == XmlPullParser.TEXT) {
1917 name = parser.getText();
1918 }
1919 } else if (TAG_RESTRICTIONS.equals(tag)) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001920 UserRestrictionsUtils.readRestrictions(parser, baseRestrictions);
1921 } else if (TAG_DEVICE_POLICY_RESTRICTIONS.equals(tag)) {
1922 UserRestrictionsUtils.readRestrictions(parser, localRestrictions);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001923 } else if (TAG_ACCOUNT.equals(tag)) {
1924 type = parser.next();
1925 if (type == XmlPullParser.TEXT) {
1926 account = parser.getText();
1927 }
Amith Yamasani12747872015-12-07 14:19:49 -08001928 } else if (TAG_SEED_ACCOUNT_OPTIONS.equals(tag)) {
1929 seedAccountOptions = PersistableBundle.restoreFromXml(parser);
1930 persistSeedData = true;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001931 }
1932 }
1933 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001934
Amith Yamasani12747872015-12-07 14:19:49 -08001935 // Create the UserInfo object that gets passed around
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001936 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -07001937 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -07001938 userInfo.creationTime = creationTime;
1939 userInfo.lastLoggedInTime = lastLoggedInTime;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06001940 userInfo.lastLoggedInFingerprint = lastLoggedInFingerprint;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001941 userInfo.partial = partial;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001942 userInfo.guestToRemove = guestToRemove;
Kenny Guy2a764942014-04-02 13:29:20 +01001943 userInfo.profileGroupId = profileGroupId;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001944 userInfo.restrictedProfileParentId = restrictedProfileParentId;
Amith Yamasani12747872015-12-07 14:19:49 -08001945
1946 // Create the UserData object that's internal to this class
1947 UserData userData = new UserData();
1948 userData.info = userInfo;
1949 userData.account = account;
1950 userData.seedAccountName = seedAccountName;
1951 userData.seedAccountType = seedAccountType;
1952 userData.persistSeedData = persistSeedData;
1953 userData.seedAccountOptions = seedAccountOptions;
1954
Makoto Onuki068c54a2015-10-13 14:34:03 -07001955 synchronized (mRestrictionsLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001956 mBaseUserRestrictions.put(id, baseRestrictions);
1957 mDevicePolicyLocalUserRestrictions.put(id, localRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001958 }
Amith Yamasani12747872015-12-07 14:19:49 -08001959 return userData;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001960 } catch (IOException ioe) {
1961 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001962 } finally {
1963 if (fis != null) {
1964 try {
1965 fis.close();
1966 } catch (IOException e) {
1967 }
1968 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001969 }
1970 return null;
1971 }
1972
Amith Yamasani920ace02012-09-20 22:15:37 -07001973 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
1974 String valueString = parser.getAttributeValue(null, attr);
1975 if (valueString == null) return defaultValue;
1976 try {
1977 return Integer.parseInt(valueString);
1978 } catch (NumberFormatException nfe) {
1979 return defaultValue;
1980 }
1981 }
1982
1983 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
1984 String valueString = parser.getAttributeValue(null, attr);
1985 if (valueString == null) return defaultValue;
1986 try {
1987 return Long.parseLong(valueString);
1988 } catch (NumberFormatException nfe) {
1989 return defaultValue;
1990 }
1991 }
1992
Amith Yamasanib82add22013-07-09 11:24:44 -07001993 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001994 * Removes the app restrictions file for a specific package and user id, if it exists.
1995 */
1996 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
1997 synchronized (mPackagesLock) {
1998 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07001999 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002000 if (resFile.exists()) {
2001 resFile.delete();
2002 }
2003 }
2004 }
2005
Kenny Guya52dc3e2014-02-11 15:33:14 +00002006 @Override
Kenny Guy2a764942014-04-02 13:29:20 +01002007 public UserInfo createProfileForUser(String name, int flags, int userId) {
Kenny Guya52dc3e2014-02-11 15:33:14 +00002008 checkManageUsersPermission("Only the system can create users");
Kenny Guy2a764942014-04-02 13:29:20 +01002009 return createUserInternal(name, flags, userId);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002010 }
2011
Amith Yamasani258848d2012-08-10 17:06:33 -07002012 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07002013 public UserInfo createUser(String name, int flags) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002014 checkManageUsersPermission("Only the system can create users");
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00002015 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002016 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07002017
Jessica Hummelbe81c802014-04-22 15:49:22 +01002018 private UserInfo createUserInternal(String name, int flags, int parentId) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002019 if (hasUserRestriction(UserManager.DISALLOW_ADD_USER, UserHandle.getCallingUserId())) {
Julia Reynolds75175022014-06-26 16:35:00 -04002020 Log.w(LOG_TAG, "Cannot add user. DISALLOW_ADD_USER is enabled.");
2021 return null;
2022 }
phweisse9c44062016-02-10 12:57:38 +01002023 return createUserInternalUnchecked(name, flags, parentId);
2024 }
2025
2026 private UserInfo createUserInternalUnchecked(String name, int flags, int parentId) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07002027 if (ActivityManager.isLowRamDeviceStatic()) {
2028 return null;
2029 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07002030 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Nicolas Prevot12678a92015-05-13 12:15:03 -07002031 final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002032 final boolean isRestricted = (flags & UserInfo.FLAG_RESTRICTED) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002033 final long ident = Binder.clearCallingIdentity();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002034 UserInfo userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08002035 UserData userData;
Amith Yamasanibb054c92015-07-09 14:16:27 -07002036 final int userId;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002037 try {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002038 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002039 UserData parent = null;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002040 if (parentId != UserHandle.USER_NULL) {
2041 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002042 parent = getUserDataLU(parentId);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00002043 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002044 if (parent == null) return null;
2045 }
2046 if (isManagedProfile && !canAddMoreManagedProfiles(parentId, false)) {
2047 Log.e(LOG_TAG, "Cannot add more managed profiles for user " + parentId);
2048 return null;
2049 }
2050 if (!isGuest && !isManagedProfile && isUserLimitReached()) {
2051 // If we're not adding a guest user or a managed profile and the limit has
2052 // been reached, cannot add a user.
2053 return null;
2054 }
2055 // If we're adding a guest and there already exists one, bail.
2056 if (isGuest && findCurrentGuestUser() != null) {
2057 return null;
2058 }
2059 // In legacy mode, restricted profile's parent can only be the owner user
2060 if (isRestricted && !UserManager.isSplitSystemUser()
2061 && (parentId != UserHandle.USER_SYSTEM)) {
2062 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
2063 return null;
2064 }
2065 if (isRestricted && UserManager.isSplitSystemUser()) {
2066 if (parent == null) {
2067 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be "
2068 + "specified");
Nicolas Prevot12678a92015-05-13 12:15:03 -07002069 return null;
2070 }
Amith Yamasani12747872015-12-07 14:19:49 -08002071 if (!parent.info.canHaveProfile()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002072 Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be "
2073 + "created for the specified parent user id " + parentId);
Amith Yamasani95ab7842014-08-11 17:09:26 -07002074 return null;
2075 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002076 }
Suprabh Shuklacc30b0e72016-05-20 14:41:22 -07002077 if (!UserManager.isSplitSystemUser() && (flags & UserInfo.FLAG_EPHEMERAL) != 0
2078 && (flags & UserInfo.FLAG_DEMO) == 0) {
Lenka Trochtova024f9792016-02-17 13:55:17 +01002079 Log.e(LOG_TAG,
2080 "Ephemeral users are supported on split-system-user systems only.");
2081 return null;
2082 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002083 // In split system user mode, we assign the first human user the primary flag.
2084 // And if there is no device owner, we also assign the admin flag to primary user.
2085 if (UserManager.isSplitSystemUser()
2086 && !isGuest && !isManagedProfile && getPrimaryUser() == null) {
2087 flags |= UserInfo.FLAG_PRIMARY;
Makoto Onukie7927da2015-11-25 10:05:17 -08002088 synchronized (mUsersLock) {
2089 if (!mIsDeviceManaged) {
2090 flags |= UserInfo.FLAG_ADMIN;
2091 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07002092 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002093 }
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002094
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002095 userId = getNextAvailableId();
2096 Environment.getUserSystemDirectory(userId).mkdirs();
Lenka Trochtova02fee152015-12-22 14:26:18 +01002097 boolean ephemeralGuests = Resources.getSystem()
2098 .getBoolean(com.android.internal.R.bool.config_guestUserEphemeral);
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002099
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002100 synchronized (mUsersLock) {
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002101 // Add ephemeral flag to guests/users if required. Also inherit it from parent.
2102 if ((isGuest && ephemeralGuests) || mForceEphemeralUsers
2103 || (parent != null && parent.info.isEphemeral())) {
2104 flags |= UserInfo.FLAG_EPHEMERAL;
2105 }
2106
2107 userInfo = new UserInfo(userId, name, null, flags);
2108 userInfo.serialNumber = mNextSerialNumber++;
2109 long now = System.currentTimeMillis();
2110 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
2111 userInfo.partial = true;
Fyodor Kupolov83c24242016-03-31 13:30:42 -07002112 userInfo.lastLoggedInFingerprint = Build.FINGERPRINT;
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002113 userData = new UserData();
2114 userData.info = userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08002115 mUsers.put(userId, userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002116 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06002117 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002118 writeUserListLP();
2119 if (parent != null) {
2120 if (isManagedProfile) {
Amith Yamasani12747872015-12-07 14:19:49 -08002121 if (parent.info.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
2122 parent.info.profileGroupId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002123 writeUserLP(parent);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002124 }
Amith Yamasani12747872015-12-07 14:19:49 -08002125 userInfo.profileGroupId = parent.info.profileGroupId;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002126 } else if (isRestricted) {
Amith Yamasani12747872015-12-07 14:19:49 -08002127 if (parent.info.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) {
2128 parent.info.restrictedProfileParentId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002129 writeUserLP(parent);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002130 }
Amith Yamasani12747872015-12-07 14:19:49 -08002131 userInfo.restrictedProfileParentId = parent.info.restrictedProfileParentId;
Makoto Onuki068c54a2015-10-13 14:34:03 -07002132 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002133 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07002134 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002135 final StorageManager storage = mContext.getSystemService(StorageManager.class);
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002136 storage.createUserKey(userId, userInfo.serialNumber, userInfo.isEphemeral());
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002137 mPm.prepareUserData(userId, userInfo.serialNumber,
Jeff Sharkey47f71082016-02-01 17:03:54 -07002138 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002139 mPm.createNewUser(userId);
2140 userInfo.partial = false;
2141 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002142 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002143 }
2144 updateUserIds();
2145 Bundle restrictions = new Bundle();
Fyodor Kupolove04462c2015-11-30 15:02:53 -08002146 if (isGuest) {
2147 synchronized (mGuestRestrictions) {
2148 restrictions.putAll(mGuestRestrictions);
2149 }
2150 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002151 synchronized (mRestrictionsLock) {
2152 mBaseUserRestrictions.append(userId, restrictions);
2153 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002154 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
2155 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
2156 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
2157 android.Manifest.permission.MANAGE_USERS);
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -08002158 MetricsLogger.count(mContext, isGuest ? TRON_GUEST_CREATED : TRON_USER_CREATED, 1);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002159 } finally {
2160 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07002161 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002162 return userInfo;
2163 }
2164
Amith Yamasani0b285492011-04-14 17:35:23 -07002165 /**
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002166 * @hide
2167 */
Amith Yamasani12747872015-12-07 14:19:49 -08002168 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002169 public UserInfo createRestrictedProfile(String name, int parentUserId) {
2170 checkManageUsersPermission("setupRestrictedProfile");
2171 final UserInfo user = createProfileForUser(name, UserInfo.FLAG_RESTRICTED, parentUserId);
2172 if (user == null) {
2173 return null;
2174 }
Fyodor Kupolov9e912ba2016-02-09 18:29:43 -08002175 long identity = Binder.clearCallingIdentity();
2176 try {
2177 setUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, true, user.id);
2178 // Change the setting before applying the DISALLOW_SHARE_LOCATION restriction, otherwise
2179 // the putIntForUser() will fail.
2180 android.provider.Settings.Secure.putIntForUser(mContext.getContentResolver(),
2181 android.provider.Settings.Secure.LOCATION_MODE,
2182 android.provider.Settings.Secure.LOCATION_MODE_OFF, user.id);
2183 setUserRestriction(UserManager.DISALLOW_SHARE_LOCATION, true, user.id);
2184 } finally {
2185 Binder.restoreCallingIdentity(identity);
2186 }
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002187 return user;
2188 }
2189
2190 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07002191 * Find the current guest user. If the Guest user is partial,
2192 * then do not include it in the results as it is about to die.
Adam Lesinskieddeb492014-09-08 17:50:03 -07002193 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002194 private UserInfo findCurrentGuestUser() {
2195 synchronized (mUsersLock) {
2196 final int size = mUsers.size();
2197 for (int i = 0; i < size; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002198 final UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002199 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
2200 return user;
2201 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002202 }
2203 }
2204 return null;
2205 }
2206
2207 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07002208 * Mark this guest user for deletion to allow us to create another guest
2209 * and switch to that user before actually removing this guest.
2210 * @param userHandle the userid of the current guest
2211 * @return whether the user could be marked for deletion
2212 */
Amith Yamasani12747872015-12-07 14:19:49 -08002213 @Override
Amith Yamasani1df14732014-08-29 21:37:27 -07002214 public boolean markGuestForDeletion(int userHandle) {
2215 checkManageUsersPermission("Only the system can remove users");
2216 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
2217 UserManager.DISALLOW_REMOVE_USER, false)) {
2218 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
2219 return false;
2220 }
2221
2222 long ident = Binder.clearCallingIdentity();
2223 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002224 final UserData userData;
Amith Yamasani1df14732014-08-29 21:37:27 -07002225 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002226 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002227 userData = mUsers.get(userHandle);
2228 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002229 return false;
2230 }
Amith Yamasani1df14732014-08-29 21:37:27 -07002231 }
Amith Yamasani12747872015-12-07 14:19:49 -08002232 if (!userData.info.isGuest()) {
Amith Yamasani1df14732014-08-29 21:37:27 -07002233 return false;
2234 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002235 // We set this to a guest user that is to be removed. This is a temporary state
2236 // where we are allowed to add new Guest users, even if this one is still not
2237 // removed. This user will still show up in getUserInfo() calls.
2238 // If we don't get around to removing this Guest user, it will be purged on next
2239 // startup.
Amith Yamasani12747872015-12-07 14:19:49 -08002240 userData.info.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07002241 // Mark it as disabled, so that it isn't returned any more when
2242 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002243 userData.info.flags |= UserInfo.FLAG_DISABLED;
2244 writeUserLP(userData);
Amith Yamasani1df14732014-08-29 21:37:27 -07002245 }
2246 } finally {
2247 Binder.restoreCallingIdentity(ident);
2248 }
2249 return true;
2250 }
2251
2252 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002253 * Removes a user and all data directories created for that user. This method should be called
2254 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07002255 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07002256 */
Amith Yamasani12747872015-12-07 14:19:49 -08002257 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -07002258 public boolean removeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002259 checkManageUsersPermission("Only the system can remove users");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04002260 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
2261 UserManager.DISALLOW_REMOVE_USER, false)) {
2262 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
2263 return false;
2264 }
2265
Kenny Guyee58b4f2014-05-23 15:19:53 +01002266 long ident = Binder.clearCallingIdentity();
2267 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002268 final UserData userData;
Fyodor Kupolov0df68cd2015-10-01 13:54:22 -07002269 int currentUser = ActivityManager.getCurrentUser();
2270 if (currentUser == userHandle) {
2271 Log.w(LOG_TAG, "Current user cannot be removed");
2272 return false;
2273 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002274 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002275 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002276 userData = mUsers.get(userHandle);
2277 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002278 return false;
2279 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002280
Fyodor Kupolov82402752015-10-28 14:54:51 -07002281 // We remember deleted user IDs to prevent them from being
2282 // reused during the current boot; they can still be reused
2283 // after a reboot.
2284 mRemovingUserIds.put(userHandle, true);
2285 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002286
Kenny Guyee58b4f2014-05-23 15:19:53 +01002287 try {
2288 mAppOpsService.removeUser(userHandle);
2289 } catch (RemoteException e) {
2290 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
2291 }
2292 // Set this to a partially created user, so that the user will be purged
2293 // on next startup, in case the runtime stops now before stopping and
2294 // removing the user completely.
Amith Yamasani12747872015-12-07 14:19:49 -08002295 userData.info.partial = true;
Kenny Guyee58b4f2014-05-23 15:19:53 +01002296 // Mark it as disabled, so that it isn't returned any more when
2297 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002298 userData.info.flags |= UserInfo.FLAG_DISABLED;
2299 writeUserLP(userData);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002300 }
2301
Amith Yamasani12747872015-12-07 14:19:49 -08002302 if (userData.info.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
2303 && userData.info.isManagedProfile()) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002304 // Send broadcast to notify system that the user removed was a
2305 // managed user.
Amith Yamasani12747872015-12-07 14:19:49 -08002306 sendProfileRemovedBroadcast(userData.info.profileGroupId, userData.info.id);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002307 }
2308
2309 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
2310 int res;
2311 try {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07002312 res = ActivityManagerNative.getDefault().stopUser(userHandle, /* force= */ true,
2313 new IStopUserCallback.Stub() {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002314 @Override
2315 public void userStopped(int userId) {
2316 finishRemoveUser(userId);
2317 }
2318 @Override
2319 public void userStopAborted(int userId) {
2320 }
2321 });
2322 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002323 return false;
2324 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002325 return res == ActivityManager.USER_OP_SUCCESS;
2326 } finally {
2327 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002328 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002329 }
2330
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002331 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07002332 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002333 // Let other services shutdown any activity and clean up their state before completely
2334 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002335 long ident = Binder.clearCallingIdentity();
2336 try {
2337 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
2338 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002339 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
2340 android.Manifest.permission.MANAGE_USERS,
2341
2342 new BroadcastReceiver() {
2343 @Override
2344 public void onReceive(Context context, Intent intent) {
2345 if (DBG) {
2346 Slog.i(LOG_TAG,
2347 "USER_REMOVED broadcast sent, cleaning up user data "
2348 + userHandle);
2349 }
2350 new Thread() {
Amith Yamasani12747872015-12-07 14:19:49 -08002351 @Override
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002352 public void run() {
Amith Yamasani515d4062015-09-28 11:30:06 -07002353 // Clean up any ActivityManager state
2354 LocalServices.getService(ActivityManagerInternal.class)
2355 .onUserRemoved(userHandle);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002356 removeUserState(userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002357 }
2358 }.start();
2359 }
2360 },
2361
2362 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002363 } finally {
2364 Binder.restoreCallingIdentity(ident);
2365 }
Amith Yamasani2a003292012-08-14 18:25:45 -07002366 }
2367
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002368 private void removeUserState(final int userHandle) {
Paul Crowley91293792016-03-25 15:23:07 -07002369 try {
2370 mContext.getSystemService(StorageManager.class).destroyUserKey(userHandle);
2371 } catch (IllegalStateException e) {
2372 // This may be simply because the user was partially created.
2373 Slog.i(LOG_TAG,
2374 "Destroying key for user " + userHandle + " failed, continuing anyway", e);
2375 }
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002376
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002377 // Cleanup package manager settings
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002378 mPm.cleanUpUser(this, userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002379 // Remove this user from the list
Fyodor Kupolov82402752015-10-28 14:54:51 -07002380 synchronized (mUsersLock) {
2381 mUsers.remove(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08002382 mIsUserManaged.delete(userHandle);
Bart Searsc51e7252016-05-27 04:12:51 +00002383 mUnlockingOrUnlockedUsers.delete(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08002384 }
2385 synchronized (mRestrictionsLock) {
2386 mBaseUserRestrictions.remove(userHandle);
2387 mAppliedUserRestrictions.remove(userHandle);
2388 mCachedEffectiveUserRestrictions.remove(userHandle);
2389 mDevicePolicyLocalUserRestrictions.remove(userHandle);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002390 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002391 // Update the user list
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002392 synchronized (mPackagesLock) {
2393 writeUserListLP();
2394 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06002395 // Remove user file
2396 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
2397 userFile.delete();
Fyodor Kupolov82402752015-10-28 14:54:51 -07002398 updateUserIds();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002399
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002400 // Now that we've purged all the metadata above, destroy the actual data
2401 // on disk; if we battery pull in here we'll finish cleaning up when
2402 // reconciling after reboot.
2403 mPm.destroyUserData(userHandle,
2404 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
Amith Yamasani61f57372012-08-31 12:12:28 -07002405 }
2406
Kenny Guyf8d3a232014-05-15 16:09:52 +01002407 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01002408 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01002409 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
2410 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002411 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
Jeff Sharkeyaf6ec292015-12-17 11:19:00 -07002412 managedProfileIntent.putExtra(Intent.EXTRA_USER_HANDLE, removedUserId);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002413 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01002414 }
2415
Amith Yamasani2a003292012-08-14 18:25:45 -07002416 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002417 public Bundle getApplicationRestrictions(String packageName) {
2418 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
2419 }
2420
2421 @Override
2422 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002423 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07002424 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00002425 checkSystemOrRoot("get application restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002426 }
2427 synchronized (mPackagesLock) {
2428 // Read the restrictions from XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07002429 return readApplicationRestrictionsLP(packageName, userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002430 }
2431 }
2432
2433 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002434 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002435 int userId) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00002436 checkSystemOrRoot("set application restrictions");
Fyodor Kupolov0d88d542016-04-19 11:37:22 -07002437 if (restrictions != null) {
2438 restrictions.setDefusable(true);
2439 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002440 synchronized (mPackagesLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01002441 if (restrictions == null || restrictions.isEmpty()) {
2442 cleanAppRestrictionsForPackage(packageName, userId);
2443 } else {
2444 // Write the restrictions to XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07002445 writeApplicationRestrictionsLP(packageName, restrictions, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01002446 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002447 }
Robin Lee66e5d962014-04-09 16:44:21 +01002448
Fyodor Kupolovd2846122016-02-11 18:06:34 -08002449 // Notify package of changes via an intent - only sent to explicitly registered receivers.
2450 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
2451 changeIntent.setPackage(packageName);
2452 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
2453 mContext.sendBroadcastAsUser(changeIntent, UserHandle.of(userId));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002454 }
2455
2456 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07002457 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002458 try {
2459 return mContext.getPackageManager().getApplicationInfo(packageName,
Fyodor Kupolovd2846122016-02-11 18:06:34 -08002460 PackageManager.MATCH_UNINSTALLED_PACKAGES).uid;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002461 } catch (NameNotFoundException nnfe) {
2462 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07002463 } finally {
2464 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002465 }
2466 }
2467
Fyodor Kupolov82402752015-10-28 14:54:51 -07002468 private Bundle readApplicationRestrictionsLP(String packageName, int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002469 AtomicFile restrictionsFile =
2470 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
2471 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002472 return readApplicationRestrictionsLP(restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002473 }
2474
2475 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002476 static Bundle readApplicationRestrictionsLP(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002477 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002478 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002479 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07002480 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002481 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002482
2483 FileInputStream fis = null;
2484 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002485 fis = restrictionsFile.openRead();
2486 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002487 parser.setInput(fis, StandardCharsets.UTF_8.name());
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002488 XmlUtils.nextElement(parser);
2489 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002490 Slog.e(LOG_TAG, "Unable to read restrictions file "
2491 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002492 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002493 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002494 while (parser.next() != XmlPullParser.END_DOCUMENT) {
2495 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002496 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002497 } catch (IOException|XmlPullParserException e) {
2498 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002499 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002500 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002501 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002502 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002503 }
2504
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002505 private static void readEntry(Bundle restrictions, ArrayList<String> values,
2506 XmlPullParser parser) throws XmlPullParserException, IOException {
2507 int type = parser.getEventType();
2508 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
2509 String key = parser.getAttributeValue(null, ATTR_KEY);
2510 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
2511 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
2512 if (multiple != null) {
2513 values.clear();
2514 int count = Integer.parseInt(multiple);
2515 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
2516 if (type == XmlPullParser.START_TAG
2517 && parser.getName().equals(TAG_VALUE)) {
2518 values.add(parser.nextText().trim());
2519 count--;
2520 }
2521 }
2522 String [] valueStrings = new String[values.size()];
2523 values.toArray(valueStrings);
2524 restrictions.putStringArray(key, valueStrings);
2525 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
2526 restrictions.putBundle(key, readBundleEntry(parser, values));
2527 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
2528 final int outerDepth = parser.getDepth();
2529 ArrayList<Bundle> bundleList = new ArrayList<>();
2530 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2531 Bundle childBundle = readBundleEntry(parser, values);
2532 bundleList.add(childBundle);
2533 }
2534 restrictions.putParcelableArray(key,
2535 bundleList.toArray(new Bundle[bundleList.size()]));
2536 } else {
2537 String value = parser.nextText().trim();
2538 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
2539 restrictions.putBoolean(key, Boolean.parseBoolean(value));
2540 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
2541 restrictions.putInt(key, Integer.parseInt(value));
2542 } else {
2543 restrictions.putString(key, value);
2544 }
2545 }
2546 }
2547 }
2548
2549 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
2550 throws IOException, XmlPullParserException {
2551 Bundle childBundle = new Bundle();
2552 final int outerDepth = parser.getDepth();
2553 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2554 readEntry(childBundle, values, parser);
2555 }
2556 return childBundle;
2557 }
2558
Fyodor Kupolov82402752015-10-28 14:54:51 -07002559 private void writeApplicationRestrictionsLP(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002560 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002561 AtomicFile restrictionsFile = new AtomicFile(
2562 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07002563 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002564 writeApplicationRestrictionsLP(restrictions, restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002565 }
2566
2567 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002568 static void writeApplicationRestrictionsLP(Bundle restrictions, AtomicFile restrictionsFile) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002569 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002570 try {
2571 fos = restrictionsFile.startWrite();
2572 final BufferedOutputStream bos = new BufferedOutputStream(fos);
2573
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002574 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002575 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002576 serializer.startDocument(null, true);
2577 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2578
2579 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002580 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002581 serializer.endTag(null, TAG_RESTRICTIONS);
2582
2583 serializer.endDocument();
2584 restrictionsFile.finishWrite(fos);
2585 } catch (Exception e) {
2586 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002587 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
2588 }
2589 }
2590
2591 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
2592 throws IOException {
2593 for (String key : restrictions.keySet()) {
2594 Object value = restrictions.get(key);
2595 serializer.startTag(null, TAG_ENTRY);
2596 serializer.attribute(null, ATTR_KEY, key);
2597
2598 if (value instanceof Boolean) {
2599 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
2600 serializer.text(value.toString());
2601 } else if (value instanceof Integer) {
2602 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
2603 serializer.text(value.toString());
2604 } else if (value == null || value instanceof String) {
2605 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
2606 serializer.text(value != null ? (String) value : "");
2607 } else if (value instanceof Bundle) {
2608 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2609 writeBundle((Bundle) value, serializer);
2610 } else if (value instanceof Parcelable[]) {
2611 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
2612 Parcelable[] array = (Parcelable[]) value;
2613 for (Parcelable parcelable : array) {
2614 if (!(parcelable instanceof Bundle)) {
2615 throw new IllegalArgumentException("bundle-array can only hold Bundles");
2616 }
2617 serializer.startTag(null, TAG_ENTRY);
2618 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2619 writeBundle((Bundle) parcelable, serializer);
2620 serializer.endTag(null, TAG_ENTRY);
2621 }
2622 } else {
2623 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
2624 String[] values = (String[]) value;
2625 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
2626 for (String choice : values) {
2627 serializer.startTag(null, TAG_VALUE);
2628 serializer.text(choice != null ? choice : "");
2629 serializer.endTag(null, TAG_VALUE);
2630 }
2631 }
2632 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002633 }
2634 }
2635
2636 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07002637 public int getUserSerialNumber(int userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002638 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002639 if (!exists(userHandle)) return -1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002640 return getUserInfoLU(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07002641 }
2642 }
2643
2644 @Override
2645 public int getUserHandle(int userSerialNumber) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002646 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002647 for (int userId : mUserIds) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002648 UserInfo info = getUserInfoLU(userId);
Kenny Guy945f8832015-02-10 15:17:26 +00002649 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07002650 }
2651 // Not found
2652 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07002653 }
2654 }
2655
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002656 @Override
2657 public long getUserCreationTime(int userHandle) {
2658 int callingUserId = UserHandle.getCallingUserId();
2659 UserInfo userInfo = null;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002660 synchronized (mUsersLock) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002661 if (callingUserId == userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002662 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002663 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002664 UserInfo parent = getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002665 if (parent != null && parent.id == callingUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002666 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002667 }
2668 }
2669 }
2670 if (userInfo == null) {
2671 throw new SecurityException("userHandle can only be the calling user or a managed "
2672 + "profile associated with this user");
2673 }
2674 return userInfo.creationTime;
2675 }
2676
Amith Yamasani0b285492011-04-14 17:35:23 -07002677 /**
2678 * Caches the list of user ids in an array, adjusting the array size when necessary.
2679 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002680 private void updateUserIds() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002681 int num = 0;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002682 synchronized (mUsersLock) {
2683 final int userSize = mUsers.size();
2684 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002685 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002686 num++;
2687 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002688 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002689 final int[] newUsers = new int[num];
2690 int n = 0;
2691 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002692 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002693 newUsers[n++] = mUsers.keyAt(i);
2694 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002695 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002696 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07002697 }
2698 }
2699
2700 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002701 * Called right before a user is started. This gives us a chance to prepare
2702 * app storage and apply any user restrictions.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002703 */
2704 public void onBeforeStartUser(int userId) {
Jeff Sharkey47f71082016-02-01 17:03:54 -07002705 final int userSerial = getUserSerialNumber(userId);
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002706 mPm.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_DE);
Jeff Sharkey47f71082016-02-01 17:03:54 -07002707 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_DE);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002708
2709 if (userId != UserHandle.USER_SYSTEM) {
2710 synchronized (mRestrictionsLock) {
2711 applyUserRestrictionsLR(userId);
2712 }
Fyodor Kupolovb45d9832016-05-16 13:25:34 -07002713 UserInfo userInfo = getUserInfoNoChecks(userId);
2714 if (userInfo != null && !userInfo.isInitialized()) {
2715 mPm.onBeforeUserStartUninitialized(userId);
2716 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002717 }
Amith Yamasanieb437d42016-04-29 09:31:25 -07002718
2719 maybeInitializeDemoMode(userId);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002720 }
2721
2722 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002723 * Called right before a user is unlocked. This gives us a chance to prepare
2724 * app storage.
2725 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002726 public void onBeforeUnlockUser(@UserIdInt int userId) {
Jeff Sharkey47f71082016-02-01 17:03:54 -07002727 final int userSerial = getUserSerialNumber(userId);
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002728 mPm.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_CE);
Jeff Sharkey47f71082016-02-01 17:03:54 -07002729 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_CE);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002730 }
2731
2732 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002733 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasanieb437d42016-04-29 09:31:25 -07002734 * This is called with ActivityManagerService lock held.
Amith Yamasani920ace02012-09-20 22:15:37 -07002735 * @param userId the user that was just foregrounded
2736 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002737 public void onUserLoggedIn(@UserIdInt int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -08002738 UserData userData = getUserDataNoChecks(userId);
2739 if (userData == null || userData.info.partial) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002740 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
2741 return;
2742 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002743
2744 final long now = System.currentTimeMillis();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002745 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani12747872015-12-07 14:19:49 -08002746 userData.info.lastLoggedInTime = now;
Amith Yamasani920ace02012-09-20 22:15:37 -07002747 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002748 userData.info.lastLoggedInFingerprint = Build.FINGERPRINT;
2749 scheduleWriteUser(userData);
Amith Yamasani920ace02012-09-20 22:15:37 -07002750 }
2751
Amith Yamasanieb437d42016-04-29 09:31:25 -07002752 private void maybeInitializeDemoMode(int userId) {
2753 if (UserManager.isDeviceInDemoMode(mContext)) {
2754 String demoLauncher =
2755 mContext.getResources().getString(
2756 com.android.internal.R.string.config_demoModeLauncherComponent);
2757 if (!TextUtils.isEmpty(demoLauncher)) {
2758 ComponentName componentToEnable = ComponentName.unflattenFromString(demoLauncher);
2759 try {
2760 AppGlobals.getPackageManager().setComponentEnabledSetting(componentToEnable,
2761 PackageManager.COMPONENT_ENABLED_STATE_ENABLED, /* flags= */ 0,
2762 /* userId= */ userId);
2763 } catch (RemoteException re) {
2764 // Internal, shouldn't happen
2765 }
2766 }
2767 }
2768 }
2769
Amith Yamasani920ace02012-09-20 22:15:37 -07002770 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002771 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani742a6712011-05-04 14:49:28 -07002772 * TODO: May not be a good idea to recycle ids, in case it results in confusion
2773 * for data and battery stats collection, or unexpected cross-talk.
Amith Yamasani0b285492011-04-14 17:35:23 -07002774 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002775 private int getNextAvailableId() {
2776 synchronized (mUsersLock) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002777 int i = MIN_USER_ID;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002778 while (i < MAX_USER_ID) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002779 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002780 return i;
Amith Yamasani195263742012-08-21 15:40:12 -07002781 }
2782 i++;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002783 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002784 }
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002785 throw new IllegalStateException("No user id available!");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002786 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002787
Amith Yamasanifc95e702013-09-26 13:20:17 -07002788 private String packageToRestrictionsFileName(String packageName) {
2789 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
2790 }
2791
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002792 /**
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002793 * Enforce that serial number stored in user directory inode matches the
2794 * given expected value. Gracefully sets the serial number if currently
2795 * undefined.
2796 *
2797 * @throws IOException when problem extracting serial number, or serial
2798 * number is mismatched.
2799 */
2800 public static void enforceSerialNumber(File file, int serialNumber) throws IOException {
2801 final int foundSerial = getSerialNumber(file);
2802 Slog.v(LOG_TAG, "Found " + file + " with serial number " + foundSerial);
2803
2804 if (foundSerial == -1) {
2805 Slog.d(LOG_TAG, "Serial number missing on " + file + "; assuming current is valid");
2806 try {
2807 setSerialNumber(file, serialNumber);
2808 } catch (IOException e) {
2809 Slog.w(LOG_TAG, "Failed to set serial number on " + file, e);
2810 }
2811
2812 } else if (foundSerial != serialNumber) {
2813 throw new IOException("Found serial number " + foundSerial
2814 + " doesn't match expected " + serialNumber);
2815 }
2816 }
2817
2818 /**
2819 * Set serial number stored in user directory inode.
2820 *
2821 * @throws IOException if serial number was already set
2822 */
2823 private static void setSerialNumber(File file, int serialNumber)
2824 throws IOException {
2825 try {
2826 final byte[] buf = Integer.toString(serialNumber).getBytes(StandardCharsets.UTF_8);
2827 Os.setxattr(file.getAbsolutePath(), XATTR_SERIAL, buf, OsConstants.XATTR_CREATE);
2828 } catch (ErrnoException e) {
2829 throw e.rethrowAsIOException();
2830 }
2831 }
2832
2833 /**
2834 * Return serial number stored in user directory inode.
2835 *
2836 * @return parsed serial number, or -1 if not set
2837 */
2838 private static int getSerialNumber(File file) throws IOException {
2839 try {
2840 final byte[] buf = new byte[256];
2841 final int len = Os.getxattr(file.getAbsolutePath(), XATTR_SERIAL, buf);
2842 final String serial = new String(buf, 0, len);
2843 try {
2844 return Integer.parseInt(serial);
2845 } catch (NumberFormatException e) {
2846 throw new IOException("Bad serial number: " + serial);
2847 }
2848 } catch (ErrnoException e) {
2849 if (e.errno == OsConstants.ENODATA) {
2850 return -1;
2851 } else {
2852 throw e.rethrowAsIOException();
2853 }
2854 }
2855 }
2856
Amith Yamasani920ace02012-09-20 22:15:37 -07002857 @Override
Amith Yamasani12747872015-12-07 14:19:49 -08002858 public void setSeedAccountData(int userId, String accountName, String accountType,
2859 PersistableBundle accountOptions, boolean persist) {
2860 checkManageUsersPermission("Require MANAGE_USERS permission to set user seed data");
2861 synchronized (mPackagesLock) {
2862 final UserData userData;
2863 synchronized (mUsersLock) {
2864 userData = getUserDataLU(userId);
2865 if (userData == null) {
2866 Slog.e(LOG_TAG, "No such user for settings seed data u=" + userId);
2867 return;
2868 }
2869 userData.seedAccountName = accountName;
2870 userData.seedAccountType = accountType;
2871 userData.seedAccountOptions = accountOptions;
2872 userData.persistSeedData = persist;
2873 }
2874 if (persist) {
2875 writeUserLP(userData);
2876 }
2877 }
2878 }
2879
2880 @Override
2881 public String getSeedAccountName() throws RemoteException {
2882 checkManageUsersPermission("Cannot get seed account information");
2883 synchronized (mUsersLock) {
2884 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
2885 return userData.seedAccountName;
2886 }
2887 }
2888
2889 @Override
2890 public String getSeedAccountType() throws RemoteException {
2891 checkManageUsersPermission("Cannot get seed account information");
2892 synchronized (mUsersLock) {
2893 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
2894 return userData.seedAccountType;
2895 }
2896 }
2897
2898 @Override
2899 public PersistableBundle getSeedAccountOptions() throws RemoteException {
2900 checkManageUsersPermission("Cannot get seed account information");
2901 synchronized (mUsersLock) {
2902 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
2903 return userData.seedAccountOptions;
2904 }
2905 }
2906
2907 @Override
2908 public void clearSeedAccountData() throws RemoteException {
2909 checkManageUsersPermission("Cannot clear seed account information");
2910 synchronized (mPackagesLock) {
2911 UserData userData;
2912 synchronized (mUsersLock) {
2913 userData = getUserDataLU(UserHandle.getCallingUserId());
2914 if (userData == null) return;
2915 userData.clearSeedAccountData();
2916 }
2917 writeUserLP(userData);
2918 }
2919 }
2920
2921 @Override
2922 public boolean someUserHasSeedAccount(String accountName, String accountType)
2923 throws RemoteException {
2924 checkManageUsersPermission("Cannot check seed account information");
2925 synchronized (mUsersLock) {
2926 final int userSize = mUsers.size();
2927 for (int i = 0; i < userSize; i++) {
2928 final UserData data = mUsers.valueAt(i);
2929 if (data.info.isInitialized()) continue;
2930 if (data.seedAccountName == null || !data.seedAccountName.equals(accountName)) {
2931 continue;
2932 }
2933 if (data.seedAccountType == null || !data.seedAccountType.equals(accountType)) {
2934 continue;
2935 }
2936 return true;
2937 }
2938 }
2939 return false;
2940 }
2941
2942 @Override
Todd Kennedy60459ab2015-10-30 11:32:16 -07002943 public void onShellCommand(FileDescriptor in, FileDescriptor out,
2944 FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
2945 (new Shell()).exec(this, in, out, err, args, resultReceiver);
2946 }
2947
2948 int onShellCommand(Shell shell, String cmd) {
2949 if (cmd == null) {
2950 return shell.handleDefaultCommands(cmd);
2951 }
2952
2953 final PrintWriter pw = shell.getOutPrintWriter();
2954 try {
2955 switch(cmd) {
2956 case "list":
2957 return runList(pw);
2958 }
2959 } catch (RemoteException e) {
2960 pw.println("Remote exception: " + e);
2961 }
2962 return -1;
2963 }
2964
2965 private int runList(PrintWriter pw) throws RemoteException {
2966 final IActivityManager am = ActivityManagerNative.getDefault();
2967 final List<UserInfo> users = getUsers(false);
2968 if (users == null) {
2969 pw.println("Error: couldn't get users");
2970 return 1;
2971 } else {
2972 pw.println("Users:");
2973 for (int i = 0; i < users.size(); i++) {
Jeff Sharkeye17ac152015-11-06 22:40:29 -08002974 String running = am.isUserRunning(users.get(i).id, 0) ? " running" : "";
Todd Kennedy60459ab2015-10-30 11:32:16 -07002975 pw.println("\t" + users.get(i).toString() + running);
2976 }
2977 return 0;
2978 }
2979 }
2980
2981 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -07002982 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2983 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2984 != PackageManager.PERMISSION_GRANTED) {
2985 pw.println("Permission Denial: can't dump UserManager from from pid="
2986 + Binder.getCallingPid()
2987 + ", uid=" + Binder.getCallingUid()
2988 + " without permission "
2989 + android.Manifest.permission.DUMP);
2990 return;
2991 }
2992
2993 long now = System.currentTimeMillis();
2994 StringBuilder sb = new StringBuilder();
2995 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002996 synchronized (mUsersLock) {
2997 pw.println("Users:");
2998 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002999 UserData userData = mUsers.valueAt(i);
3000 if (userData == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003001 continue;
3002 }
Amith Yamasani12747872015-12-07 14:19:49 -08003003 UserInfo userInfo = userData.info;
3004 final int userId = userInfo.id;
3005 pw.print(" "); pw.print(userInfo);
3006 pw.print(" serialNo="); pw.print(userInfo.serialNumber);
Makoto Onukie7927da2015-11-25 10:05:17 -08003007 if (mRemovingUserIds.get(userId)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003008 pw.print(" <removing> ");
3009 }
Amith Yamasani12747872015-12-07 14:19:49 -08003010 if (userInfo.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003011 pw.print(" <partial>");
3012 }
3013 pw.println();
3014 pw.print(" Created: ");
Amith Yamasani12747872015-12-07 14:19:49 -08003015 if (userInfo.creationTime == 0) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003016 pw.println("<unknown>");
3017 } else {
3018 sb.setLength(0);
Amith Yamasani12747872015-12-07 14:19:49 -08003019 TimeUtils.formatDuration(now - userInfo.creationTime, sb);
Fyodor Kupolov82402752015-10-28 14:54:51 -07003020 sb.append(" ago");
3021 pw.println(sb);
3022 }
3023 pw.print(" Last logged in: ");
Amith Yamasani12747872015-12-07 14:19:49 -08003024 if (userInfo.lastLoggedInTime == 0) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003025 pw.println("<unknown>");
3026 } else {
3027 sb.setLength(0);
Amith Yamasani12747872015-12-07 14:19:49 -08003028 TimeUtils.formatDuration(now - userInfo.lastLoggedInTime, sb);
Fyodor Kupolov82402752015-10-28 14:54:51 -07003029 sb.append(" ago");
3030 pw.println(sb);
3031 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003032 pw.print(" Last logged in fingerprint: ");
3033 pw.println(userInfo.lastLoggedInFingerprint);
Makoto Onukie7927da2015-11-25 10:05:17 -08003034 pw.print(" Has profile owner: ");
3035 pw.println(mIsUserManaged.get(userId));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003036 pw.println(" Restrictions:");
3037 synchronized (mRestrictionsLock) {
3038 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003039 pw, " ", mBaseUserRestrictions.get(userInfo.id));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003040 pw.println(" Device policy local restrictions:");
3041 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003042 pw, " ", mDevicePolicyLocalUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003043 pw.println(" Effective restrictions:");
3044 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003045 pw, " ", mCachedEffectiveUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003046 }
Amith Yamasani12747872015-12-07 14:19:49 -08003047
3048 if (userData.account != null) {
3049 pw.print(" Account name: " + userData.account);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08003050 pw.println();
3051 }
Amith Yamasani12747872015-12-07 14:19:49 -08003052
3053 if (userData.seedAccountName != null) {
3054 pw.print(" Seed account name: " + userData.seedAccountName);
3055 pw.println();
3056 if (userData.seedAccountType != null) {
3057 pw.print(" account type: " + userData.seedAccountType);
3058 pw.println();
3059 }
3060 if (userData.seedAccountOptions != null) {
3061 pw.print(" account options exist");
3062 pw.println();
3063 }
3064 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003065 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003066 }
Amith Yamasani12747872015-12-07 14:19:49 -08003067 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003068 pw.println(" Device policy global restrictions:");
3069 synchronized (mRestrictionsLock) {
3070 UserRestrictionsUtils
3071 .dumpRestrictions(pw, " ", mDevicePolicyGlobalUserRestrictions);
3072 }
Makoto Onukia4f11972015-10-01 13:19:58 -07003073 pw.println();
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01003074 pw.println(" Global restrictions owner id:" + mGlobalRestrictionOwnerUserId);
3075 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003076 pw.println(" Guest restrictions:");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003077 synchronized (mGuestRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003078 UserRestrictionsUtils.dumpRestrictions(pw, " ", mGuestRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003079 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003080 synchronized (mUsersLock) {
3081 pw.println();
3082 pw.println(" Device managed: " + mIsDeviceManaged);
3083 }
Amith Yamasani12747872015-12-07 14:19:49 -08003084 // Dump some capabilities
3085 pw.println();
3086 pw.println(" Max users: " + UserManager.getMaxSupportedUsers());
3087 pw.println(" Supports switchable users: " + UserManager.supportsMultipleUsers());
Lenka Trochtova02fee152015-12-22 14:26:18 +01003088 pw.println(" All guests ephemeral: " + Resources.getSystem().getBoolean(
3089 com.android.internal.R.bool.config_guestUserEphemeral));
Amith Yamasani920ace02012-09-20 22:15:37 -07003090 }
3091 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08003092
3093 final class MainHandler extends Handler {
3094
3095 @Override
3096 public void handleMessage(Message msg) {
3097 switch (msg.what) {
3098 case WRITE_USER_MSG:
3099 removeMessages(WRITE_USER_MSG, msg.obj);
3100 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08003101 int userId = ((UserData) msg.obj).info.id;
3102 UserData userData = getUserDataNoChecks(userId);
3103 if (userData != null) {
3104 writeUserLP(userData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08003105 }
3106 }
3107 }
3108 }
3109 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07003110
3111 /**
3112 * @param userId
3113 * @return whether the user has been initialized yet
3114 */
3115 boolean isInitialized(int userId) {
3116 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
3117 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003118
3119 private class LocalService extends UserManagerInternal {
Makoto Onuki068c54a2015-10-13 14:34:03 -07003120 @Override
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003121 public void setDevicePolicyUserRestrictions(int userId, @NonNull Bundle localRestrictions,
3122 @Nullable Bundle globalRestrictions) {
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08003123 UserManagerService.this.setDevicePolicyUserRestrictionsInner(userId, localRestrictions,
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003124 globalRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003125 }
3126
3127 @Override
3128 public Bundle getBaseUserRestrictions(int userId) {
3129 synchronized (mRestrictionsLock) {
3130 return mBaseUserRestrictions.get(userId);
3131 }
3132 }
3133
3134 @Override
3135 public void setBaseUserRestrictionsByDpmsForMigration(
3136 int userId, Bundle baseRestrictions) {
3137 synchronized (mRestrictionsLock) {
3138 mBaseUserRestrictions.put(userId, new Bundle(baseRestrictions));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003139 invalidateEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003140 }
3141
Amith Yamasani12747872015-12-07 14:19:49 -08003142 final UserData userData = getUserDataNoChecks(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003143 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08003144 if (userData != null) {
3145 writeUserLP(userData);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003146 } else {
3147 Slog.w(LOG_TAG, "UserInfo not found for " + userId);
3148 }
3149 }
3150 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08003151
3152 @Override
3153 public boolean getUserRestriction(int userId, String key) {
3154 return getUserRestrictions(userId).getBoolean(key);
3155 }
3156
3157 @Override
3158 public void addUserRestrictionsListener(UserRestrictionsListener listener) {
3159 synchronized (mUserRestrictionsListeners) {
3160 mUserRestrictionsListeners.add(listener);
3161 }
3162 }
3163
3164 @Override
3165 public void removeUserRestrictionsListener(UserRestrictionsListener listener) {
3166 synchronized (mUserRestrictionsListeners) {
3167 mUserRestrictionsListeners.remove(listener);
3168 }
3169 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003170
3171 @Override
3172 public void setDeviceManaged(boolean isManaged) {
3173 synchronized (mUsersLock) {
3174 mIsDeviceManaged = isManaged;
3175 }
3176 }
3177
3178 @Override
3179 public void setUserManaged(int userId, boolean isManaged) {
3180 synchronized (mUsersLock) {
3181 mIsUserManaged.put(userId, isManaged);
3182 }
3183 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01003184
3185 @Override
3186 public void setUserIcon(int userId, Bitmap bitmap) {
3187 long ident = Binder.clearCallingIdentity();
3188 try {
3189 synchronized (mPackagesLock) {
3190 UserData userData = getUserDataNoChecks(userId);
3191 if (userData == null || userData.info.partial) {
3192 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
3193 return;
3194 }
3195 writeBitmapLP(userData.info, bitmap);
3196 writeUserLP(userData);
3197 }
3198 sendUserInfoChangedBroadcast(userId);
3199 } finally {
3200 Binder.restoreCallingIdentity(ident);
3201 }
3202 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01003203
3204 @Override
3205 public void setForceEphemeralUsers(boolean forceEphemeralUsers) {
3206 synchronized (mUsersLock) {
3207 mForceEphemeralUsers = forceEphemeralUsers;
3208 }
3209 }
3210
3211 @Override
3212 public void removeAllUsers() {
3213 if (UserHandle.USER_SYSTEM == ActivityManager.getCurrentUser()) {
3214 // Remove the non-system users straight away.
3215 removeNonSystemUsers();
3216 } else {
3217 // Switch to the system user first and then remove the other users.
3218 BroadcastReceiver userSwitchedReceiver = new BroadcastReceiver() {
3219 @Override
3220 public void onReceive(Context context, Intent intent) {
3221 int userId =
3222 intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3223 if (userId != UserHandle.USER_SYSTEM) {
3224 return;
3225 }
3226 mContext.unregisterReceiver(this);
3227 removeNonSystemUsers();
3228 }
3229 };
3230 IntentFilter userSwitchedFilter = new IntentFilter();
3231 userSwitchedFilter.addAction(Intent.ACTION_USER_SWITCHED);
3232 mContext.registerReceiver(
3233 userSwitchedReceiver, userSwitchedFilter, null, mHandler);
3234
3235 // Switch to the system user.
3236 ActivityManager am =
3237 (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
3238 am.switchUser(UserHandle.USER_SYSTEM);
3239 }
3240 }
phweisse9c44062016-02-10 12:57:38 +01003241
3242 @Override
Lenka Trochtova1ddda472016-02-12 10:42:12 +01003243 public void onEphemeralUserStop(int userId) {
3244 synchronized (mUsersLock) {
3245 UserInfo userInfo = getUserInfoLU(userId);
3246 if (userInfo != null && userInfo.isEphemeral()) {
3247 // Do not allow switching back to the ephemeral user again as the user is going
3248 // to be deleted.
3249 userInfo.flags |= UserInfo.FLAG_DISABLED;
3250 if (userInfo.isGuest()) {
3251 // Indicate that the guest will be deleted after it stops.
3252 userInfo.guestToRemove = true;
3253 }
3254 }
3255 }
3256 }
3257
3258 @Override
phweisse9c44062016-02-10 12:57:38 +01003259 public UserInfo createUserEvenWhenDisallowed(String name, int flags) {
3260 UserInfo user = createUserInternalUnchecked(name, flags, UserHandle.USER_NULL);
3261 // Keep this in sync with UserManager.createUser
3262 if (user != null && !user.isAdmin()) {
3263 setUserRestriction(UserManager.DISALLOW_SMS, true, user.id);
3264 setUserRestriction(UserManager.DISALLOW_OUTGOING_CALLS, true, user.id);
3265 }
3266 return user;
3267 }
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003268
3269 @Override
Bart Searsc51e7252016-05-27 04:12:51 +00003270 public void setUserUnlockingOrUnlocked(int userId, boolean unlockingOrUnlocked) {
3271 synchronized (mUsersLock) {
3272 mUnlockingOrUnlockedUsers.put(userId, unlockingOrUnlocked);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003273 }
3274 }
3275
3276 @Override
3277 public boolean isUserUnlockingOrUnlocked(int userId) {
Bart Searsc51e7252016-05-27 04:12:51 +00003278 synchronized (mUsersLock) {
3279 return mUnlockingOrUnlockedUsers.get(userId);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003280 }
3281 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01003282 }
3283
3284 /* Remove all the users except of the system one. */
3285 private void removeNonSystemUsers() {
3286 ArrayList<UserInfo> usersToRemove = new ArrayList<>();
3287 synchronized (mUsersLock) {
3288 final int userSize = mUsers.size();
3289 for (int i = 0; i < userSize; i++) {
3290 UserInfo ui = mUsers.valueAt(i).info;
3291 if (ui.id != UserHandle.USER_SYSTEM) {
3292 usersToRemove.add(ui);
3293 }
3294 }
3295 }
3296 for (UserInfo ui: usersToRemove) {
3297 removeUser(ui.id);
3298 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003299 }
Todd Kennedy60459ab2015-10-30 11:32:16 -07003300
3301 private class Shell extends ShellCommand {
3302 @Override
3303 public int onCommand(String cmd) {
3304 return onShellCommand(this, cmd);
3305 }
3306
3307 @Override
3308 public void onHelp() {
3309 final PrintWriter pw = getOutPrintWriter();
3310 pw.println("User manager (user) commands:");
3311 pw.println(" help");
3312 pw.println(" Print this help text.");
3313 pw.println("");
3314 pw.println(" list");
3315 pw.println(" Prints all users on the system.");
3316 }
3317 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003318
3319 private static void debug(String message) {
3320 Log.d(LOG_TAG, message +
3321 (DBG_WITH_STACKTRACE ? " called at\n" + Debug.getCallers(10, " ") : ""));
3322 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003323}