blob: b9167905612d668ada86070c664c921c2ef12758 [file] [log] [blame]
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
Benjamin Franzf02420c2016-04-04 18:52:21 +010019import static android.content.Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS;
20import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
21
Xiaohui Chenb3b92582015-12-07 11:22:13 -080022import android.Manifest;
Xiaohui Chen594f2082015-08-18 11:04:20 -070023import android.annotation.NonNull;
Makoto Onuki068c54a2015-10-13 14:34:03 -070024import android.annotation.Nullable;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -060025import android.annotation.UserIdInt;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070026import android.app.Activity;
Amith Yamasani2a003292012-08-14 18:25:45 -070027import android.app.ActivityManager;
Amith Yamasani515d4062015-09-28 11:30:06 -070028import android.app.ActivityManagerInternal;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070029import android.app.ActivityManagerNative;
Todd Kennedy60459ab2015-10-30 11:32:16 -070030import android.app.IActivityManager;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070031import android.app.IStopUserCallback;
Benjamin Franzf02420c2016-04-04 18:52:21 +010032import android.app.KeyguardManager;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070033import android.content.BroadcastReceiver;
Amith Yamasani258848d2012-08-10 17:06:33 -070034import android.content.Context;
35import android.content.Intent;
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +010036import android.content.IntentFilter;
Benjamin Franzf02420c2016-04-04 18:52:21 +010037import android.content.IntentSender;
Amith Yamasani0b285492011-04-14 17:35:23 -070038import android.content.pm.PackageManager;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -080039import android.content.pm.PackageManager.NameNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070040import android.content.pm.UserInfo;
Lenka Trochtova02fee152015-12-22 14:26:18 +010041import android.content.res.Resources;
Amith Yamasanie928d7d2012-09-17 21:46:51 -070042import android.graphics.Bitmap;
Amith Yamasani258848d2012-08-10 17:06:33 -070043import android.os.Binder;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -060044import android.os.Build;
Amith Yamasanie4cf7342012-12-17 11:12:09 -080045import android.os.Bundle;
Makoto Onuki1a2cd742015-11-16 13:51:27 -080046import android.os.Debug;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070047import android.os.Environment;
48import android.os.FileUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080049import android.os.Handler;
Svet Ganov9cea80cd2016-02-16 11:47:00 -080050import android.os.IBinder;
Amith Yamasani258848d2012-08-10 17:06:33 -070051import android.os.IUserManager;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -080052import android.os.Message;
Adrian Roos1bdff912015-02-17 15:51:35 +010053import android.os.ParcelFileDescriptor;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070054import android.os.Parcelable;
Amith Yamasani12747872015-12-07 14:19:49 -080055import android.os.PersistableBundle;
Amith Yamasani258848d2012-08-10 17:06:33 -070056import android.os.Process;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070057import android.os.RemoteException;
Todd Kennedy60459ab2015-10-30 11:32:16 -070058import android.os.ResultReceiver;
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +010059import android.os.SELinux;
Jason Monk62062992014-05-06 09:55:28 -040060import android.os.ServiceManager;
Todd Kennedy60459ab2015-10-30 11:32:16 -070061import android.os.ShellCommand;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070062import android.os.UserHandle;
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070063import android.os.UserManager;
Makoto Onuki068c54a2015-10-13 14:34:03 -070064import android.os.UserManagerInternal;
Makoto Onukid45a4a22015-11-02 17:17:38 -080065import android.os.UserManagerInternal.UserRestrictionsListener;
Paul Crowley85e4e812015-05-19 12:42:00 +010066import android.os.storage.StorageManager;
Jeff Sharkey6dce4962015-07-03 18:08:41 -070067import android.system.ErrnoException;
68import android.system.Os;
69import android.system.OsConstants;
Amith Yamasani2a003292012-08-14 18:25:45 -070070import android.util.AtomicFile;
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -070071import android.util.IntArray;
Amith Yamasani655d0e22013-06-12 14:19:10 -070072import android.util.Log;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070073import android.util.Slog;
74import android.util.SparseArray;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080075import android.util.SparseBooleanArray;
Fyodor Kupolovac06a492016-05-25 14:45:29 -070076import android.util.SparseIntArray;
Amith Yamasani920ace02012-09-20 22:15:37 -070077import android.util.TimeUtils;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070078import android.util.Xml;
79
Makoto Onuki068c54a2015-10-13 14:34:03 -070080import com.android.internal.annotations.GuardedBy;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070081import com.android.internal.annotations.VisibleForTesting;
Jason Monk62062992014-05-06 09:55:28 -040082import com.android.internal.app.IAppOpsService;
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -080083import com.android.internal.logging.MetricsLogger;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080084import com.android.internal.util.FastXmlSerializer;
Makoto Onuki068c54a2015-10-13 14:34:03 -070085import com.android.internal.util.Preconditions;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070086import com.android.internal.util.XmlUtils;
Clara Bayarri10ad84a2015-12-01 17:38:05 +000087import com.android.internal.widget.LockPatternUtils;
Amith Yamasani515d4062015-09-28 11:30:06 -070088import com.android.server.LocalServices;
Fyodor Kupolovac06a492016-05-25 14:45:29 -070089import com.android.server.am.UserState;
Jeff Sharkey47f71082016-02-01 17:03:54 -070090
91import libcore.io.IoUtils;
92import libcore.util.Objects;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080093
94import org.xmlpull.v1.XmlPullParser;
95import org.xmlpull.v1.XmlPullParserException;
96import org.xmlpull.v1.XmlSerializer;
97
Amith Yamasani4b2e9342011-03-31 12:38:53 -070098import java.io.BufferedOutputStream;
99import java.io.File;
Amith Yamasani920ace02012-09-20 22:15:37 -0700100import java.io.FileDescriptor;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700101import java.io.FileInputStream;
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700102import java.io.FileNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700103import java.io.FileOutputStream;
104import java.io.IOException;
Amith Yamasani920ace02012-09-20 22:15:37 -0700105import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100106import java.nio.charset.StandardCharsets;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700107import java.util.ArrayList;
108import java.util.List;
109
Makoto Onuki068c54a2015-10-13 14:34:03 -0700110/**
111 * Service for {@link UserManager}.
112 *
113 * Method naming convention:
Fyodor Kupolov82402752015-10-28 14:54:51 -0700114 * <ul>
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800115 * <li> Methods suffixed with "LP" should be called within the {@link #mPackagesLock} lock.
Fyodor Kupolov82402752015-10-28 14:54:51 -0700116 * <li> Methods suffixed with "LR" should be called within the {@link #mRestrictionsLock} lock.
117 * <li> Methods suffixed with "LU" should be called within the {@link #mUsersLock} lock.
118 * </ul>
Makoto Onuki068c54a2015-10-13 14:34:03 -0700119 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700120public class UserManagerService extends IUserManager.Stub {
Amith Yamasani2a003292012-08-14 18:25:45 -0700121 private static final String LOG_TAG = "UserManagerService";
Makoto Onuki81c61ea2016-01-22 11:22:26 -0800122 static final boolean DBG = false; // DO NOT SUBMIT WITH TRUE
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800123 private static final boolean DBG_WITH_STACKTRACE = false; // DO NOT SUBMIT WITH TRUE
Amith Yamasani16389312012-10-17 21:20:14 -0700124
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700125 private static final String TAG_NAME = "name";
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800126 private static final String TAG_ACCOUNT = "account";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700127 private static final String ATTR_FLAGS = "flags";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700128 private static final String ATTR_ICON_PATH = "icon";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700129 private static final String ATTR_ID = "id";
Amith Yamasani920ace02012-09-20 22:15:37 -0700130 private static final String ATTR_CREATION_TIME = "created";
131 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -0600132 private static final String ATTR_LAST_LOGGED_IN_FINGERPRINT = "lastLoggedInFingerprint";
Amith Yamasani2a003292012-08-14 18:25:45 -0700133 private static final String ATTR_SERIAL_NO = "serialNumber";
134 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700135 private static final String ATTR_PARTIAL = "partial";
Adam Lesinskieddeb492014-09-08 17:50:03 -0700136 private static final String ATTR_GUEST_TO_REMOVE = "guestToRemove";
Amith Yamasani6f34b412012-10-22 18:19:27 -0700137 private static final String ATTR_USER_VERSION = "version";
Kenny Guy2a764942014-04-02 13:29:20 +0100138 private static final String ATTR_PROFILE_GROUP_ID = "profileGroupId";
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700139 private static final String ATTR_RESTRICTED_PROFILE_PARENT_ID = "restrictedProfileParentId";
Amith Yamasani12747872015-12-07 14:19:49 -0800140 private static final String ATTR_SEED_ACCOUNT_NAME = "seedAccountName";
141 private static final String ATTR_SEED_ACCOUNT_TYPE = "seedAccountType";
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530142 private static final String TAG_GUEST_RESTRICTIONS = "guestRestrictions";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700143 private static final String TAG_USERS = "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700144 private static final String TAG_USER = "user";
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800145 private static final String TAG_RESTRICTIONS = "restrictions";
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800146 private static final String TAG_DEVICE_POLICY_RESTRICTIONS = "device_policy_restrictions";
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +0100147 private static final String TAG_GLOBAL_RESTRICTION_OWNER_ID = "globalRestrictionOwnerUserId";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800148 private static final String TAG_ENTRY = "entry";
149 private static final String TAG_VALUE = "value";
Amith Yamasani12747872015-12-07 14:19:49 -0800150 private static final String TAG_SEED_ACCOUNT_OPTIONS = "seedAccountOptions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800151 private static final String ATTR_KEY = "key";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700152 private static final String ATTR_VALUE_TYPE = "type";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800153 private static final String ATTR_MULTIPLE = "m";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700154
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700155 private static final String ATTR_TYPE_STRING_ARRAY = "sa";
156 private static final String ATTR_TYPE_STRING = "s";
157 private static final String ATTR_TYPE_BOOLEAN = "b";
Amith Yamasani5b5aa402014-06-01 20:10:14 -0700158 private static final String ATTR_TYPE_INTEGER = "i";
Fyodor Kupolov262f9952015-03-23 18:55:11 -0700159 private static final String ATTR_TYPE_BUNDLE = "B";
160 private static final String ATTR_TYPE_BUNDLE_ARRAY = "BA";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700161
Amith Yamasani0b285492011-04-14 17:35:23 -0700162 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700163 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700164 private static final String USER_PHOTO_FILENAME = "photo.png";
Adrian Roos1bdff912015-02-17 15:51:35 +0100165 private static final String USER_PHOTO_FILENAME_TMP = USER_PHOTO_FILENAME + ".tmp";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700166
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800167 private static final String RESTRICTIONS_FILE_PREFIX = "res_";
Amith Yamasanifc95e702013-09-26 13:20:17 -0700168 private static final String XML_SUFFIX = ".xml";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800169
Amith Yamasani634cf312012-10-04 17:34:21 -0700170 private static final int MIN_USER_ID = 10;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700171 // We need to keep process uid within Integer.MAX_VALUE.
172 private static final int MAX_USER_ID = Integer.MAX_VALUE / UserHandle.PER_USER_RANGE;
Amith Yamasani634cf312012-10-04 17:34:21 -0700173
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700174 private static final int USER_VERSION = 6;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700175
Amith Yamasani920ace02012-09-20 22:15:37 -0700176 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
177
Nicolas Prevotb8186812015-08-06 15:00:03 +0100178 // Maximum number of managed profiles permitted per user is 1. This cannot be increased
Amith Yamasani95ab7842014-08-11 17:09:26 -0700179 // without first making sure that the rest of the framework is prepared for it.
180 private static final int MAX_MANAGED_PROFILES = 1;
181
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800182 static final int WRITE_USER_MSG = 1;
183 static final int WRITE_USER_DELAY = 2*1000; // 2 seconds
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530184
Jeff Sharkey6dce4962015-07-03 18:08:41 -0700185 private static final String XATTR_SERIAL = "user.serial";
186
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -0800187 // Tron counters
188 private static final String TRON_GUEST_CREATED = "users_guest_created";
189 private static final String TRON_USER_CREATED = "users_user_created";
190
Dianne Hackborn4428e172012-08-24 17:43:05 -0700191 private final Context mContext;
192 private final PackageManagerService mPm;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700193 private final Object mPackagesLock;
Fyodor Kupolov82402752015-10-28 14:54:51 -0700194 // Short-term lock for internal state, when interaction/sync with PM is not required
195 private final Object mUsersLock = new Object();
196 private final Object mRestrictionsLock = new Object();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700197
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800198 private final Handler mHandler;
199
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700200 private final File mUsersDir;
201 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700202
Svet Ganov9cea80cd2016-02-16 11:47:00 -0800203 private static final IBinder mUserRestriconToken = new Binder();
204
Makoto Onuki068c54a2015-10-13 14:34:03 -0700205 /**
Amith Yamasani12747872015-12-07 14:19:49 -0800206 * User-related information that is used for persisting to flash. Only UserInfo is
207 * directly exposed to other system apps.
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800208 */
Amith Yamasani12747872015-12-07 14:19:49 -0800209 private static class UserData {
210 // Basic user information and properties
211 UserInfo info;
212 // Account name used when there is a strong association between a user and an account
213 String account;
214 // Account information for seeding into a newly created user. This could also be
215 // used for login validation for an existing user, for updating their credentials.
216 // In the latter case, data may not need to be persisted as it is only valid for the
217 // current login session.
218 String seedAccountName;
219 String seedAccountType;
220 PersistableBundle seedAccountOptions;
221 // Whether to perist the seed account information to be available after a boot
222 boolean persistSeedData;
223
224 void clearSeedAccountData() {
225 seedAccountName = null;
226 seedAccountType = null;
227 seedAccountOptions = null;
228 persistSeedData = false;
229 }
230 }
231
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800232 @GuardedBy("mUsersLock")
Amith Yamasani12747872015-12-07 14:19:49 -0800233 private final SparseArray<UserData> mUsers = new SparseArray<>();
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800234
235 /**
Makoto Onuki068c54a2015-10-13 14:34:03 -0700236 * User restrictions set via UserManager. This doesn't include restrictions set by
237 * device owner / profile owners.
238 *
239 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
240 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
241 * maybe shared between {@link #mBaseUserRestrictions} and
242 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
243 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700244 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700245 */
246 @GuardedBy("mRestrictionsLock")
247 private final SparseArray<Bundle> mBaseUserRestrictions = new SparseArray<>();
248
249 /**
250 * Cached user restrictions that are in effect -- i.e. {@link #mBaseUserRestrictions} combined
251 * with device / profile owner restrictions. We'll initialize it lazily; use
252 * {@link #getEffectiveUserRestrictions} to access it.
253 *
254 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
255 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
256 * maybe shared between {@link #mBaseUserRestrictions} and
257 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
258 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700259 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700260 */
261 @GuardedBy("mRestrictionsLock")
262 private final SparseArray<Bundle> mCachedEffectiveUserRestrictions = new SparseArray<>();
263
Makoto Onuki4f160732015-10-27 17:15:38 -0700264 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800265 * User restrictions that have already been applied in
266 * {@link #updateUserRestrictionsInternalLR(Bundle, int)}. We use it to detect restrictions
267 * that have changed since the last
268 * {@link #updateUserRestrictionsInternalLR(Bundle, int)} call.
Makoto Onuki4f160732015-10-27 17:15:38 -0700269 */
270 @GuardedBy("mRestrictionsLock")
271 private final SparseArray<Bundle> mAppliedUserRestrictions = new SparseArray<>();
272
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800273 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800274 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
275 * that should be applied to all users, including guests.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800276 */
277 @GuardedBy("mRestrictionsLock")
278 private Bundle mDevicePolicyGlobalUserRestrictions;
279
280 /**
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +0100281 * Id of the user that set global restrictions.
282 */
283 @GuardedBy("mRestrictionsLock")
284 private int mGlobalRestrictionOwnerUserId = UserHandle.USER_NULL;
285
286 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800287 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
288 * for each user.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800289 */
290 @GuardedBy("mRestrictionsLock")
291 private final SparseArray<Bundle> mDevicePolicyLocalUserRestrictions = new SparseArray<>();
292
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800293 @GuardedBy("mGuestRestrictions")
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530294 private final Bundle mGuestRestrictions = new Bundle();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800295
296 /**
297 * Set of user IDs being actively removed. Removed IDs linger in this set
298 * for several seconds to work around a VFS caching issue.
299 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700300 @GuardedBy("mUsersLock")
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800301 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700302
Fyodor Kupolov82402752015-10-28 14:54:51 -0700303 @GuardedBy("mUsersLock")
Amith Yamasani0b285492011-04-14 17:35:23 -0700304 private int[] mUserIds;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800305 @GuardedBy("mPackagesLock")
Amith Yamasani2a003292012-08-14 18:25:45 -0700306 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700307 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700308
Jason Monk62062992014-05-06 09:55:28 -0400309 private IAppOpsService mAppOpsService;
310
Makoto Onuki068c54a2015-10-13 14:34:03 -0700311 private final LocalService mLocalService;
312
Makoto Onukie7927da2015-11-25 10:05:17 -0800313 @GuardedBy("mUsersLock")
314 private boolean mIsDeviceManaged;
315
316 @GuardedBy("mUsersLock")
317 private final SparseBooleanArray mIsUserManaged = new SparseBooleanArray();
318
Makoto Onukid45a4a22015-11-02 17:17:38 -0800319 @GuardedBy("mUserRestrictionsListeners")
320 private final ArrayList<UserRestrictionsListener> mUserRestrictionsListeners =
321 new ArrayList<>();
322
Clara Bayarria1771112015-12-18 16:29:18 +0000323 private final LockPatternUtils mLockPatternUtils;
324
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +0100325 /**
326 * Whether all users should be created ephemeral.
327 */
328 @GuardedBy("mUsersLock")
329 private boolean mForceEphemeralUsers;
330
Fyodor Kupolovac06a492016-05-25 14:45:29 -0700331 @GuardedBy("mUserStates")
332 private final SparseIntArray mUserStates = new SparseIntArray();
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -0700333
Amith Yamasani258848d2012-08-10 17:06:33 -0700334 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700335
Dianne Hackborn4428e172012-08-24 17:43:05 -0700336 public static UserManagerService getInstance() {
337 synchronized (UserManagerService.class) {
338 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700339 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700340 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700341
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800342 @VisibleForTesting
343 UserManagerService(File dataDir) {
344 this(null, null, new Object(), dataDir);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700345 }
346
Dianne Hackborn4428e172012-08-24 17:43:05 -0700347 /**
348 * Called by package manager to create the service. This is closely
349 * associated with the package manager, and the given lock is the
350 * package manager's own lock.
351 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800352 UserManagerService(Context context, PackageManagerService pm, Object packagesLock) {
353 this(context, pm, packagesLock, Environment.getDataDirectory());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700354 }
355
Dianne Hackborn4428e172012-08-24 17:43:05 -0700356 private UserManagerService(Context context, PackageManagerService pm,
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800357 Object packagesLock, File dataDir) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700358 mContext = context;
359 mPm = pm;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700360 mPackagesLock = packagesLock;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800361 mHandler = new MainHandler();
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800362 synchronized (mPackagesLock) {
363 mUsersDir = new File(dataDir, USER_INFO_DIR);
364 mUsersDir.mkdirs();
365 // Make zeroth user directory, for services to migrate their files to that location
366 File userZeroDir = new File(mUsersDir, String.valueOf(UserHandle.USER_SYSTEM));
367 userZeroDir.mkdirs();
368 FileUtils.setPermissions(mUsersDir.toString(),
369 FileUtils.S_IRWXU | FileUtils.S_IRWXG | FileUtils.S_IROTH | FileUtils.S_IXOTH,
370 -1, -1);
371 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
372 initDefaultGuestRestrictions();
373 readUserListLP();
374 sInstance = this;
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700375 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700376 mLocalService = new LocalService();
377 LocalServices.addService(UserManagerInternal.class, mLocalService);
Clara Bayarria1771112015-12-18 16:29:18 +0000378 mLockPatternUtils = new LockPatternUtils(mContext);
Fyodor Kupolovac06a492016-05-25 14:45:29 -0700379 mUserStates.put(UserHandle.USER_SYSTEM, UserState.STATE_BOOTING);
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700380 }
381
382 void systemReady() {
Lenka Trochtovac4dd0212015-11-18 12:22:06 +0100383 // Prune out any partially created, partially removed and ephemeral users.
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800384 ArrayList<UserInfo> partials = new ArrayList<>();
385 synchronized (mUsersLock) {
386 final int userSize = mUsers.size();
387 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800388 UserInfo ui = mUsers.valueAt(i).info;
Lenka Trochtovac4dd0212015-11-18 12:22:06 +0100389 if ((ui.partial || ui.guestToRemove || ui.isEphemeral()) && i != 0) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800390 partials.add(ui);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700391 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700392 }
Dianne Hackborn4428e172012-08-24 17:43:05 -0700393 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800394 final int partialsSize = partials.size();
395 for (int i = 0; i < partialsSize; i++) {
396 UserInfo ui = partials.get(i);
397 Slog.w(LOG_TAG, "Removing partially created user " + ui.id
398 + " (name=" + ui.name + ")");
399 removeUserState(ui.id);
400 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800401
Jason Monk62062992014-05-06 09:55:28 -0400402 mAppOpsService = IAppOpsService.Stub.asInterface(
403 ServiceManager.getService(Context.APP_OPS_SERVICE));
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800404
405 synchronized (mRestrictionsLock) {
406 applyUserRestrictionsLR(UserHandle.USER_SYSTEM);
Jason Monk62062992014-05-06 09:55:28 -0400407 }
Samuel Tand9453b82016-03-14 15:57:02 -0700408
409 UserInfo currentGuestUser = findCurrentGuestUser();
410 if (currentGuestUser != null && !hasUserRestriction(
411 UserManager.DISALLOW_CONFIG_WIFI, currentGuestUser.id)) {
412 // If a guest user currently exists, apply the DISALLOW_CONFIG_WIFI option
413 // to it, in case this guest was created in a previous version where this
414 // user restriction was not a default guest restriction.
415 setUserRestriction(UserManager.DISALLOW_CONFIG_WIFI, true, currentGuestUser.id);
416 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700417 }
418
419 @Override
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800420 public String getUserAccount(int userId) {
421 checkManageUserAndAcrossUsersFullPermission("get user account");
422 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800423 return mUsers.get(userId).account;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800424 }
425 }
426
427 @Override
428 public void setUserAccount(int userId, String accountName) {
429 checkManageUserAndAcrossUsersFullPermission("set user account");
Amith Yamasani12747872015-12-07 14:19:49 -0800430 UserData userToUpdate = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800431 synchronized (mPackagesLock) {
432 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800433 final UserData userData = mUsers.get(userId);
434 if (userData == null) {
435 Slog.e(LOG_TAG, "User not found for setting user account: u" + userId);
436 return;
437 }
438 String currentAccount = userData.account;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800439 if (!Objects.equal(currentAccount, accountName)) {
Amith Yamasani12747872015-12-07 14:19:49 -0800440 userData.account = accountName;
441 userToUpdate = userData;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800442 }
443 }
444
445 if (userToUpdate != null) {
446 writeUserLP(userToUpdate);
447 }
448 }
449 }
450
451 @Override
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700452 public UserInfo getPrimaryUser() {
453 checkManageUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700454 synchronized (mUsersLock) {
Amith Yamasani515d4062015-09-28 11:30:06 -0700455 final int userSize = mUsers.size();
456 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800457 UserInfo ui = mUsers.valueAt(i).info;
Xiaohui Chend3e9e182015-11-18 13:37:32 -0800458 if (ui.isPrimary() && !mRemovingUserIds.get(ui.id)) {
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700459 return ui;
460 }
461 }
462 }
463 return null;
464 }
465
466 @Override
Xiaohui Chen594f2082015-08-18 11:04:20 -0700467 public @NonNull List<UserInfo> getUsers(boolean excludeDying) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700468 checkManageUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700469 synchronized (mUsersLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700470 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasani515d4062015-09-28 11:30:06 -0700471 final int userSize = mUsers.size();
472 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800473 UserInfo ui = mUsers.valueAt(i).info;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700474 if (ui.partial) {
475 continue;
476 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800477 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Amith Yamasani6f48d6e2016-03-23 14:28:25 -0700478 users.add(userWithName(ui));
Amith Yamasani920ace02012-09-20 22:15:37 -0700479 }
Amith Yamasani13593602012-03-22 16:16:17 -0700480 }
481 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700482 }
Amith Yamasani13593602012-03-22 16:16:17 -0700483 }
484
Amith Yamasani258848d2012-08-10 17:06:33 -0700485 @Override
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100486 public List<UserInfo> getProfiles(int userId, boolean enabledOnly) {
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700487 boolean returnFullInfo = true;
Amith Yamasani4f582632014-02-19 14:31:52 -0800488 if (userId != UserHandle.getCallingUserId()) {
489 checkManageUsersPermission("getting profiles related to user " + userId);
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700490 } else {
491 returnFullInfo = hasManageUsersPermission();
Amith Yamasani4f582632014-02-19 14:31:52 -0800492 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700493 final long ident = Binder.clearCallingIdentity();
494 try {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700495 synchronized (mUsersLock) {
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700496 return getProfilesLU(userId, enabledOnly, returnFullInfo);
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100497 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700498 } finally {
499 Binder.restoreCallingIdentity(ident);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000500 }
501 }
502
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700503 @Override
504 public int[] getProfileIds(int userId, boolean enabledOnly) {
505 if (userId != UserHandle.getCallingUserId()) {
506 checkManageUsersPermission("getting profiles related to user " + userId);
507 }
508 final long ident = Binder.clearCallingIdentity();
509 try {
510 synchronized (mUsersLock) {
511 return getProfileIdsLU(userId, enabledOnly).toArray();
512 }
513 } finally {
514 Binder.restoreCallingIdentity(ident);
515 }
516 }
517
Amith Yamasanibe465322014-04-24 13:45:17 -0700518 /** Assume permissions already checked and caller's identity cleared */
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700519 private List<UserInfo> getProfilesLU(int userId, boolean enabledOnly, boolean fullInfo) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700520 IntArray profileIds = getProfileIdsLU(userId, enabledOnly);
521 ArrayList<UserInfo> users = new ArrayList<>(profileIds.size());
522 for (int i = 0; i < profileIds.size(); i++) {
523 int profileId = profileIds.get(i);
524 UserInfo userInfo = mUsers.get(profileId).info;
525 // If full info is not required - clear PII data to prevent 3P apps from reading it
526 if (!fullInfo) {
527 userInfo = new UserInfo(userInfo);
528 userInfo.name = null;
529 userInfo.iconPath = null;
530 } else {
531 userInfo = userWithName(userInfo);
532 }
533 users.add(userInfo);
534 }
535 return users;
536 }
537
538 /**
539 * Assume permissions already checked and caller's identity cleared
540 */
541 private IntArray getProfileIdsLU(int userId, boolean enabledOnly) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700542 UserInfo user = getUserInfoLU(userId);
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700543 IntArray result = new IntArray(mUsers.size());
Amith Yamasanidda003f2014-08-28 18:06:51 -0700544 if (user == null) {
545 // Probably a dying user
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700546 return result;
Amith Yamasanidda003f2014-08-28 18:06:51 -0700547 }
Amith Yamasani515d4062015-09-28 11:30:06 -0700548 final int userSize = mUsers.size();
549 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800550 UserInfo profile = mUsers.valueAt(i).info;
Amith Yamasanibe465322014-04-24 13:45:17 -0700551 if (!isProfileOf(user, profile)) {
552 continue;
553 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100554 if (enabledOnly && !profile.isEnabled()) {
555 continue;
Amith Yamasanibe465322014-04-24 13:45:17 -0700556 }
Amith Yamasani70fcf0c2014-07-11 08:40:19 -0700557 if (mRemovingUserIds.get(profile.id)) {
558 continue;
559 }
Tony Mak80189cd2016-04-05 17:21:42 +0100560 if (profile.partial) {
561 continue;
562 }
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700563 result.add(profile.id);
Amith Yamasanibe465322014-04-24 13:45:17 -0700564 }
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700565 return result;
Amith Yamasanibe465322014-04-24 13:45:17 -0700566 }
567
Jessica Hummelbe81c802014-04-22 15:49:22 +0100568 @Override
Andres Moralesc5548c02015-08-05 10:23:12 -0700569 public int getCredentialOwnerProfile(int userHandle) {
570 checkManageUsersPermission("get the credential owner");
Clara Bayarria1771112015-12-18 16:29:18 +0000571 if (!mLockPatternUtils.isSeparateProfileChallengeEnabled(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700572 synchronized (mUsersLock) {
573 UserInfo profileParent = getProfileParentLU(userHandle);
Andres Moralesc5548c02015-08-05 10:23:12 -0700574 if (profileParent != null) {
575 return profileParent.id;
576 }
577 }
578 }
579
580 return userHandle;
581 }
582
583 @Override
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700584 public boolean isSameProfileGroup(int userId, int otherUserId) {
585 if (userId == otherUserId) return true;
586 checkManageUsersPermission("check if in the same profile group");
587 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700588 return isSameProfileGroupLP(userId, otherUserId);
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700589 }
590 }
591
Fyodor Kupolov82402752015-10-28 14:54:51 -0700592 private boolean isSameProfileGroupLP(int userId, int otherUserId) {
593 synchronized (mUsersLock) {
594 UserInfo userInfo = getUserInfoLU(userId);
595 if (userInfo == null || userInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
596 return false;
597 }
598 UserInfo otherUserInfo = getUserInfoLU(otherUserId);
599 if (otherUserInfo == null
600 || otherUserInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
601 return false;
602 }
603 return userInfo.profileGroupId == otherUserInfo.profileGroupId;
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700604 }
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700605 }
606
607 @Override
Jessica Hummelbe81c802014-04-22 15:49:22 +0100608 public UserInfo getProfileParent(int userHandle) {
609 checkManageUsersPermission("get the profile parent");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700610 synchronized (mUsersLock) {
611 return getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700612 }
613 }
614
Fyodor Kupolov82402752015-10-28 14:54:51 -0700615 private UserInfo getProfileParentLU(int userHandle) {
616 UserInfo profile = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700617 if (profile == null) {
618 return null;
619 }
620 int parentUserId = profile.profileGroupId;
621 if (parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
622 return null;
623 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700624 return getUserInfoLU(parentUserId);
Jessica Hummelbe81c802014-04-22 15:49:22 +0100625 }
626 }
627
Fyodor Kupolov82402752015-10-28 14:54:51 -0700628 private static boolean isProfileOf(UserInfo user, UserInfo profile) {
Kenny Guy2a764942014-04-02 13:29:20 +0100629 return user.id == profile.id ||
630 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
631 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000632 }
633
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000634 private void broadcastProfileAvailabilityChanges(UserHandle profileHandle,
Rubin Xuf13c9802016-01-21 18:06:00 +0000635 UserHandle parentHandle, boolean inQuietMode) {
Rubin Xue95057a2016-04-01 16:49:25 +0100636 Intent intent = new Intent();
637 if (inQuietMode) {
638 intent.setAction(Intent.ACTION_MANAGED_PROFILE_UNAVAILABLE);
639 } else {
640 intent.setAction(Intent.ACTION_MANAGED_PROFILE_AVAILABLE);
641 }
Rubin Xuf13c9802016-01-21 18:06:00 +0000642 intent.putExtra(Intent.EXTRA_QUIET_MODE, inQuietMode);
643 intent.putExtra(Intent.EXTRA_USER, profileHandle);
644 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileHandle.getIdentifier());
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000645 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Rubin Xuf13c9802016-01-21 18:06:00 +0000646 mContext.sendBroadcastAsUser(intent, parentHandle);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000647 }
648
649 @Override
650 public void setQuietModeEnabled(int userHandle, boolean enableQuietMode) {
651 checkManageUsersPermission("silence profile");
652 boolean changed = false;
653 UserInfo profile, parent;
654 synchronized (mPackagesLock) {
655 synchronized (mUsersLock) {
656 profile = getUserInfoLU(userHandle);
657 parent = getProfileParentLU(userHandle);
658
659 }
660 if (profile == null || !profile.isManagedProfile()) {
661 throw new IllegalArgumentException("User " + userHandle + " is not a profile");
662 }
663 if (profile.isQuietModeEnabled() != enableQuietMode) {
664 profile.flags ^= UserInfo.FLAG_QUIET_MODE;
Amith Yamasani12747872015-12-07 14:19:49 -0800665 writeUserLP(getUserDataLU(profile.id));
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000666 changed = true;
667 }
668 }
669 if (changed) {
Rubin Xuf13c9802016-01-21 18:06:00 +0000670 long identity = Binder.clearCallingIdentity();
671 try {
672 if (enableQuietMode) {
Rubin Xuf8451b92016-04-01 15:50:58 +0100673 LocalServices.getService(ActivityManagerInternal.class)
674 .killForegroundAppsForUser(userHandle);
Rubin Xuf13c9802016-01-21 18:06:00 +0000675 ActivityManagerNative.getDefault().stopUser(userHandle, /* force */true, null);
676 } else {
677 ActivityManagerNative.getDefault().startUserInBackground(userHandle);
678 }
679 } catch (RemoteException e) {
680 Slog.e(LOG_TAG, "fail to start/stop user for quiet mode", e);
681 } finally {
682 Binder.restoreCallingIdentity(identity);
683 }
684
685 broadcastProfileAvailabilityChanges(profile.getUserHandle(), parent.getUserHandle(),
686 enableQuietMode);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000687 }
688 }
689
690 @Override
691 public boolean isQuietModeEnabled(int userHandle) {
692 synchronized (mPackagesLock) {
693 UserInfo info;
694 synchronized (mUsersLock) {
695 info = getUserInfoLU(userHandle);
696 }
697 if (info == null || !info.isManagedProfile()) {
Rubin Xuf13c9802016-01-21 18:06:00 +0000698 return false;
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000699 }
700 return info.isQuietModeEnabled();
701 }
702 }
703
Kenny Guya52dc3e2014-02-11 15:33:14 +0000704 @Override
Benjamin Franzf02420c2016-04-04 18:52:21 +0100705 public boolean trySetQuietModeDisabled(int userHandle, IntentSender target) {
Jeff Sharkeyce18c812016-04-27 16:00:41 -0600706 if (StorageManager.isUserKeyUnlocked(userHandle)
Ricky Wai9cc7ad62016-05-11 18:00:20 +0100707 || !mLockPatternUtils.isSecure(userHandle)) {
Benjamin Franzf02420c2016-04-04 18:52:21 +0100708 // if the user is already unlocked, no need to show a profile challenge
709 setQuietModeEnabled(userHandle, false);
710 return true;
711 }
712
713 long identity = Binder.clearCallingIdentity();
714 try {
715 // otherwise, we show a profile challenge to trigger decryption of the user
716 final KeyguardManager km = (KeyguardManager) mContext.getSystemService(
717 Context.KEYGUARD_SERVICE);
Ricky Wai7881cf82016-04-15 17:20:12 +0100718 // We should use userHandle not credentialOwnerUserId here, as even if it is unified
719 // lock, confirm screenlock page will know and show personal challenge, and unlock
720 // work profile when personal challenge is correct
Benjamin Franzf02420c2016-04-04 18:52:21 +0100721 final Intent unlockIntent = km.createConfirmDeviceCredentialIntent(null, null,
722 userHandle);
723 if (unlockIntent == null) {
724 return false;
725 }
726 if (target != null) {
727 unlockIntent.putExtra(Intent.EXTRA_INTENT, target);
728 }
729 unlockIntent.setFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
730 mContext.startActivity(unlockIntent);
731 } finally {
732 Binder.restoreCallingIdentity(identity);
733 }
734 return false;
735 }
736
737 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100738 public void setUserEnabled(int userId) {
739 checkManageUsersPermission("enable user");
740 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700741 UserInfo info;
742 synchronized (mUsersLock) {
743 info = getUserInfoLU(userId);
744 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100745 if (info != null && !info.isEnabled()) {
746 info.flags ^= UserInfo.FLAG_DISABLED;
Amith Yamasani12747872015-12-07 14:19:49 -0800747 writeUserLP(getUserDataLU(info.id));
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100748 }
749 }
750 }
751
752 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700753 public UserInfo getUserInfo(int userId) {
Tony Mak8673b282016-03-21 21:10:59 +0000754 checkManageUsersPermission("query user");
755 synchronized (mUsersLock) {
Amith Yamasani6f48d6e2016-03-23 14:28:25 -0700756 return userWithName(getUserInfoLU(userId));
757 }
758 }
759
760 /**
761 * Returns a UserInfo object with the name filled in, for Owner, or the original
762 * if the name is already set.
763 */
764 private UserInfo userWithName(UserInfo orig) {
765 if (orig != null && orig.name == null && orig.id == UserHandle.USER_SYSTEM) {
766 UserInfo withName = new UserInfo(orig);
767 withName.name = getOwnerName();
768 return withName;
769 } else {
770 return orig;
Tony Mak8673b282016-03-21 21:10:59 +0000771 }
772 }
773
774 @Override
775 public boolean isManagedProfile(int userId) {
Tony Makb531d082016-03-16 14:49:52 +0000776 int callingUserId = UserHandle.getCallingUserId();
777 if (callingUserId != userId && !hasManageUsersPermission()) {
778 synchronized (mPackagesLock) {
779 if (!isSameProfileGroupLP(callingUserId, userId)) {
780 throw new SecurityException(
Tony Mak8673b282016-03-21 21:10:59 +0000781 "You need MANAGE_USERS permission to: check if specified user a " +
782 "managed profile outside your profile group");
Tony Makb531d082016-03-16 14:49:52 +0000783 }
784 }
Tony Mak4dc008c2016-03-16 10:46:49 +0000785 }
Fyodor Kupolov82402752015-10-28 14:54:51 -0700786 synchronized (mUsersLock) {
Tony Mak8673b282016-03-21 21:10:59 +0000787 UserInfo userInfo = getUserInfoLU(userId);
788 return userInfo != null && userInfo.isManagedProfile();
Amith Yamasani13593602012-03-22 16:16:17 -0700789 }
790 }
791
Amith Yamasani71e6c692013-03-24 17:39:28 -0700792 @Override
793 public boolean isRestricted() {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700794 synchronized (mUsersLock) {
795 return getUserInfoLU(UserHandle.getCallingUserId()).isRestricted();
Amith Yamasani71e6c692013-03-24 17:39:28 -0700796 }
797 }
798
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700799 @Override
800 public boolean canHaveRestrictedProfile(int userId) {
801 checkManageUsersPermission("canHaveRestrictedProfile");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700802 synchronized (mUsersLock) {
803 final UserInfo userInfo = getUserInfoLU(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700804 if (userInfo == null || !userInfo.canHaveProfile()) {
805 return false;
806 }
807 if (!userInfo.isAdmin()) {
808 return false;
809 }
Makoto Onukie7927da2015-11-25 10:05:17 -0800810 // restricted profile can be created if there is no DO set and the admin user has no PO;
811 return !mIsDeviceManaged && !mIsUserManaged.get(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700812 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700813 }
814
Amith Yamasani195263742012-08-21 15:40:12 -0700815 /*
816 * Should be locked on mUsers before calling this.
817 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700818 private UserInfo getUserInfoLU(int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -0800819 final UserData userData = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -0700820 // If it is partial and not in the process of being removed, return as unknown user.
Amith Yamasani12747872015-12-07 14:19:49 -0800821 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700822 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
823 return null;
824 }
Amith Yamasani12747872015-12-07 14:19:49 -0800825 return userData != null ? userData.info : null;
826 }
827
828 private UserData getUserDataLU(int userId) {
829 final UserData userData = mUsers.get(userId);
830 // If it is partial and not in the process of being removed, return as unknown user.
831 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
832 return null;
833 }
834 return userData;
Amith Yamasani195263742012-08-21 15:40:12 -0700835 }
836
Fyodor Kupolov82402752015-10-28 14:54:51 -0700837 /**
838 * Obtains {@link #mUsersLock} and return UserInfo from mUsers.
839 * <p>No permissions checking or any addition checks are made</p>
840 */
841 private UserInfo getUserInfoNoChecks(int userId) {
842 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800843 final UserData userData = mUsers.get(userId);
844 return userData != null ? userData.info : null;
845 }
846 }
847
848 /**
849 * Obtains {@link #mUsersLock} and return UserData from mUsers.
850 * <p>No permissions checking or any addition checks are made</p>
851 */
852 private UserData getUserDataNoChecks(int userId) {
853 synchronized (mUsersLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700854 return mUsers.get(userId);
855 }
856 }
857
Amith Yamasani236b2b52015-08-18 14:32:14 -0700858 /** Called by PackageManagerService */
Amith Yamasani13593602012-03-22 16:16:17 -0700859 public boolean exists(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700860 return getUserInfoNoChecks(userId) != null;
Amith Yamasani13593602012-03-22 16:16:17 -0700861 }
862
Amith Yamasani258848d2012-08-10 17:06:33 -0700863 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700864 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700865 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700866 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700867 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800868 UserData userData = getUserDataNoChecks(userId);
869 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700870 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
871 return;
872 }
Amith Yamasani12747872015-12-07 14:19:49 -0800873 if (name != null && !name.equals(userData.info.name)) {
874 userData.info.name = name;
875 writeUserLP(userData);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700876 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -0700877 }
878 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700879 if (changed) {
880 sendUserInfoChangedBroadcast(userId);
881 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700882 }
883
Amith Yamasani258848d2012-08-10 17:06:33 -0700884 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700885 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700886 checkManageUsersPermission("update users");
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +0100887 if (hasUserRestriction(UserManager.DISALLOW_SET_USER_ICON, userId)) {
888 Log.w(LOG_TAG, "Cannot set user icon. DISALLOW_SET_USER_ICON is enabled.");
889 return;
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700890 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +0100891 mLocalService.setUserIcon(userId, bitmap);
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700892 }
893
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +0100894
895
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700896 private void sendUserInfoChangedBroadcast(int userId) {
897 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
898 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
899 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -0700900 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700901 }
902
Amith Yamasani258848d2012-08-10 17:06:33 -0700903 @Override
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +0100904 public ParcelFileDescriptor getUserIcon(int targetUserId) {
Adrian Roos1bdff912015-02-17 15:51:35 +0100905 String iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700906 synchronized (mPackagesLock) {
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +0100907 UserInfo targetUserInfo = getUserInfoNoChecks(targetUserId);
908 if (targetUserInfo == null || targetUserInfo.partial) {
909 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + targetUserId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700910 return null;
911 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +0100912
913 final int callingUserId = UserHandle.getCallingUserId();
914 final int callingGroupId = getUserInfoNoChecks(callingUserId).profileGroupId;
915 final int targetGroupId = targetUserInfo.profileGroupId;
916 final boolean sameGroup = (callingGroupId != UserInfo.NO_PROFILE_GROUP_ID
917 && callingGroupId == targetGroupId);
918 if ((callingUserId != targetUserId) && !sameGroup) {
Nicolas Prevot88cc3462014-05-14 14:51:48 +0100919 checkManageUsersPermission("get the icon of a user who is not related");
920 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +0100921
922 if (targetUserInfo.iconPath == null) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700923 return null;
924 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +0100925 iconPath = targetUserInfo.iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700926 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100927
928 try {
929 return ParcelFileDescriptor.open(
930 new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
931 } catch (FileNotFoundException e) {
932 Log.e(LOG_TAG, "Couldn't find icon file", e);
933 }
934 return null;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700935 }
936
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700937 public void makeInitialized(int userId) {
938 checkManageUsersPermission("makeInitialized");
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800939 boolean scheduleWriteUser = false;
Amith Yamasani12747872015-12-07 14:19:49 -0800940 UserData userData;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800941 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800942 userData = mUsers.get(userId);
943 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700944 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800945 return;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700946 }
Amith Yamasani12747872015-12-07 14:19:49 -0800947 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
948 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800949 scheduleWriteUser = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700950 }
951 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800952 if (scheduleWriteUser) {
Amith Yamasani12747872015-12-07 14:19:49 -0800953 scheduleWriteUser(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800954 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700955 }
956
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700957 /**
958 * If default guest restrictions haven't been initialized yet, add the basic
959 * restrictions.
960 */
961 private void initDefaultGuestRestrictions() {
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800962 synchronized (mGuestRestrictions) {
963 if (mGuestRestrictions.isEmpty()) {
Samuel Tand9453b82016-03-14 15:57:02 -0700964 mGuestRestrictions.putBoolean(UserManager.DISALLOW_CONFIG_WIFI, true);
Fyodor Kupolove04462c2015-11-30 15:02:53 -0800965 mGuestRestrictions.putBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, true);
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800966 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
967 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
968 }
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700969 }
970 }
971
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800972 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530973 public Bundle getDefaultGuestRestrictions() {
974 checkManageUsersPermission("getDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800975 synchronized (mGuestRestrictions) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530976 return new Bundle(mGuestRestrictions);
977 }
978 }
979
980 @Override
981 public void setDefaultGuestRestrictions(Bundle restrictions) {
982 checkManageUsersPermission("setDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800983 synchronized (mGuestRestrictions) {
984 mGuestRestrictions.clear();
985 mGuestRestrictions.putAll(restrictions);
986 }
987 synchronized (mPackagesLock) {
988 writeUserListLP();
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530989 }
990 }
991
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800992 /**
993 * See {@link UserManagerInternal#setDevicePolicyUserRestrictions(int, Bundle, Bundle)}
994 */
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800995 void setDevicePolicyUserRestrictionsInner(int userId, @NonNull Bundle local,
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800996 @Nullable Bundle global) {
997 Preconditions.checkNotNull(local);
998 boolean globalChanged = false;
999 boolean localChanged;
1000 synchronized (mRestrictionsLock) {
1001 if (global != null) {
1002 // Update global.
1003 globalChanged = !UserRestrictionsUtils.areEqual(
1004 mDevicePolicyGlobalUserRestrictions, global);
1005 if (globalChanged) {
1006 mDevicePolicyGlobalUserRestrictions = global;
1007 }
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001008 // Remember the global restriction owner userId to be able to make a distinction
1009 // in getUserRestrictionSource on who set local policies.
1010 mGlobalRestrictionOwnerUserId = userId;
1011 } else {
Zoltan Szatmary-Ban8a5536d2016-05-27 17:56:44 +01001012 if (mGlobalRestrictionOwnerUserId == userId) {
1013 // When profile owner sets restrictions it passes null global bundle and we
1014 // reset global restriction owner userId.
1015 // This means this user used to have DO, but now the DO is gone and the user
1016 // instead has PO.
1017 mGlobalRestrictionOwnerUserId = UserHandle.USER_NULL;
1018 }
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 }
Lenka Trochtova024f9792016-02-17 13:55:17 +01002077 if (!UserManager.isSplitSystemUser() && (flags & UserInfo.FLAG_EPHEMERAL) != 0) {
2078 Log.e(LOG_TAG,
2079 "Ephemeral users are supported on split-system-user systems only.");
2080 return null;
2081 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002082 // In split system user mode, we assign the first human user the primary flag.
2083 // And if there is no device owner, we also assign the admin flag to primary user.
2084 if (UserManager.isSplitSystemUser()
2085 && !isGuest && !isManagedProfile && getPrimaryUser() == null) {
2086 flags |= UserInfo.FLAG_PRIMARY;
Makoto Onukie7927da2015-11-25 10:05:17 -08002087 synchronized (mUsersLock) {
2088 if (!mIsDeviceManaged) {
2089 flags |= UserInfo.FLAG_ADMIN;
2090 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07002091 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002092 }
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002093
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002094 userId = getNextAvailableId();
2095 Environment.getUserSystemDirectory(userId).mkdirs();
Lenka Trochtova02fee152015-12-22 14:26:18 +01002096 boolean ephemeralGuests = Resources.getSystem()
2097 .getBoolean(com.android.internal.R.bool.config_guestUserEphemeral);
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002098
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002099 synchronized (mUsersLock) {
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002100 // Add ephemeral flag to guests/users if required. Also inherit it from parent.
2101 if ((isGuest && ephemeralGuests) || mForceEphemeralUsers
2102 || (parent != null && parent.info.isEphemeral())) {
2103 flags |= UserInfo.FLAG_EPHEMERAL;
2104 }
2105
2106 userInfo = new UserInfo(userId, name, null, flags);
2107 userInfo.serialNumber = mNextSerialNumber++;
2108 long now = System.currentTimeMillis();
2109 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
2110 userInfo.partial = true;
Fyodor Kupolov83c24242016-03-31 13:30:42 -07002111 userInfo.lastLoggedInFingerprint = Build.FINGERPRINT;
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002112 userData = new UserData();
2113 userData.info = userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08002114 mUsers.put(userId, userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002115 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06002116 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002117 writeUserListLP();
2118 if (parent != null) {
2119 if (isManagedProfile) {
Amith Yamasani12747872015-12-07 14:19:49 -08002120 if (parent.info.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
2121 parent.info.profileGroupId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002122 writeUserLP(parent);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002123 }
Amith Yamasani12747872015-12-07 14:19:49 -08002124 userInfo.profileGroupId = parent.info.profileGroupId;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002125 } else if (isRestricted) {
Amith Yamasani12747872015-12-07 14:19:49 -08002126 if (parent.info.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) {
2127 parent.info.restrictedProfileParentId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002128 writeUserLP(parent);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002129 }
Amith Yamasani12747872015-12-07 14:19:49 -08002130 userInfo.restrictedProfileParentId = parent.info.restrictedProfileParentId;
Makoto Onuki068c54a2015-10-13 14:34:03 -07002131 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002132 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07002133 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002134 final StorageManager storage = mContext.getSystemService(StorageManager.class);
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002135 storage.createUserKey(userId, userInfo.serialNumber, userInfo.isEphemeral());
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002136 mPm.prepareUserData(userId, userInfo.serialNumber,
Jeff Sharkey47f71082016-02-01 17:03:54 -07002137 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002138 mPm.createNewUser(userId);
2139 userInfo.partial = false;
2140 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002141 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002142 }
2143 updateUserIds();
2144 Bundle restrictions = new Bundle();
Fyodor Kupolove04462c2015-11-30 15:02:53 -08002145 if (isGuest) {
2146 synchronized (mGuestRestrictions) {
2147 restrictions.putAll(mGuestRestrictions);
2148 }
2149 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002150 synchronized (mRestrictionsLock) {
2151 mBaseUserRestrictions.append(userId, restrictions);
2152 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002153 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
2154 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
2155 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
2156 android.Manifest.permission.MANAGE_USERS);
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -08002157 MetricsLogger.count(mContext, isGuest ? TRON_GUEST_CREATED : TRON_USER_CREATED, 1);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002158 } finally {
2159 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07002160 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002161 return userInfo;
2162 }
2163
Amith Yamasani0b285492011-04-14 17:35:23 -07002164 /**
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002165 * @hide
2166 */
Amith Yamasani12747872015-12-07 14:19:49 -08002167 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002168 public UserInfo createRestrictedProfile(String name, int parentUserId) {
2169 checkManageUsersPermission("setupRestrictedProfile");
2170 final UserInfo user = createProfileForUser(name, UserInfo.FLAG_RESTRICTED, parentUserId);
2171 if (user == null) {
2172 return null;
2173 }
Fyodor Kupolov9e912ba2016-02-09 18:29:43 -08002174 long identity = Binder.clearCallingIdentity();
2175 try {
2176 setUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, true, user.id);
2177 // Change the setting before applying the DISALLOW_SHARE_LOCATION restriction, otherwise
2178 // the putIntForUser() will fail.
2179 android.provider.Settings.Secure.putIntForUser(mContext.getContentResolver(),
2180 android.provider.Settings.Secure.LOCATION_MODE,
2181 android.provider.Settings.Secure.LOCATION_MODE_OFF, user.id);
2182 setUserRestriction(UserManager.DISALLOW_SHARE_LOCATION, true, user.id);
2183 } finally {
2184 Binder.restoreCallingIdentity(identity);
2185 }
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002186 return user;
2187 }
2188
2189 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07002190 * Find the current guest user. If the Guest user is partial,
2191 * then do not include it in the results as it is about to die.
Adam Lesinskieddeb492014-09-08 17:50:03 -07002192 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002193 private UserInfo findCurrentGuestUser() {
2194 synchronized (mUsersLock) {
2195 final int size = mUsers.size();
2196 for (int i = 0; i < size; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002197 final UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002198 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
2199 return user;
2200 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002201 }
2202 }
2203 return null;
2204 }
2205
2206 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07002207 * Mark this guest user for deletion to allow us to create another guest
2208 * and switch to that user before actually removing this guest.
2209 * @param userHandle the userid of the current guest
2210 * @return whether the user could be marked for deletion
2211 */
Amith Yamasani12747872015-12-07 14:19:49 -08002212 @Override
Amith Yamasani1df14732014-08-29 21:37:27 -07002213 public boolean markGuestForDeletion(int userHandle) {
2214 checkManageUsersPermission("Only the system can remove users");
2215 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
2216 UserManager.DISALLOW_REMOVE_USER, false)) {
2217 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
2218 return false;
2219 }
2220
2221 long ident = Binder.clearCallingIdentity();
2222 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002223 final UserData userData;
Amith Yamasani1df14732014-08-29 21:37:27 -07002224 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002225 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002226 userData = mUsers.get(userHandle);
2227 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002228 return false;
2229 }
Amith Yamasani1df14732014-08-29 21:37:27 -07002230 }
Amith Yamasani12747872015-12-07 14:19:49 -08002231 if (!userData.info.isGuest()) {
Amith Yamasani1df14732014-08-29 21:37:27 -07002232 return false;
2233 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002234 // We set this to a guest user that is to be removed. This is a temporary state
2235 // where we are allowed to add new Guest users, even if this one is still not
2236 // removed. This user will still show up in getUserInfo() calls.
2237 // If we don't get around to removing this Guest user, it will be purged on next
2238 // startup.
Amith Yamasani12747872015-12-07 14:19:49 -08002239 userData.info.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07002240 // Mark it as disabled, so that it isn't returned any more when
2241 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002242 userData.info.flags |= UserInfo.FLAG_DISABLED;
2243 writeUserLP(userData);
Amith Yamasani1df14732014-08-29 21:37:27 -07002244 }
2245 } finally {
2246 Binder.restoreCallingIdentity(ident);
2247 }
2248 return true;
2249 }
2250
2251 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002252 * Removes a user and all data directories created for that user. This method should be called
2253 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07002254 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07002255 */
Amith Yamasani12747872015-12-07 14:19:49 -08002256 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -07002257 public boolean removeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002258 checkManageUsersPermission("Only the system can remove users");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04002259 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
2260 UserManager.DISALLOW_REMOVE_USER, false)) {
2261 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
2262 return false;
2263 }
2264
Kenny Guyee58b4f2014-05-23 15:19:53 +01002265 long ident = Binder.clearCallingIdentity();
2266 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002267 final UserData userData;
Fyodor Kupolov0df68cd2015-10-01 13:54:22 -07002268 int currentUser = ActivityManager.getCurrentUser();
2269 if (currentUser == userHandle) {
2270 Log.w(LOG_TAG, "Current user cannot be removed");
2271 return false;
2272 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002273 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002274 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002275 userData = mUsers.get(userHandle);
2276 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002277 return false;
2278 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002279
Fyodor Kupolov82402752015-10-28 14:54:51 -07002280 // We remember deleted user IDs to prevent them from being
2281 // reused during the current boot; they can still be reused
2282 // after a reboot.
2283 mRemovingUserIds.put(userHandle, true);
2284 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002285
Kenny Guyee58b4f2014-05-23 15:19:53 +01002286 try {
2287 mAppOpsService.removeUser(userHandle);
2288 } catch (RemoteException e) {
2289 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
2290 }
2291 // Set this to a partially created user, so that the user will be purged
2292 // on next startup, in case the runtime stops now before stopping and
2293 // removing the user completely.
Amith Yamasani12747872015-12-07 14:19:49 -08002294 userData.info.partial = true;
Kenny Guyee58b4f2014-05-23 15:19:53 +01002295 // Mark it as disabled, so that it isn't returned any more when
2296 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002297 userData.info.flags |= UserInfo.FLAG_DISABLED;
2298 writeUserLP(userData);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002299 }
2300
Amith Yamasani12747872015-12-07 14:19:49 -08002301 if (userData.info.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
2302 && userData.info.isManagedProfile()) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002303 // Send broadcast to notify system that the user removed was a
2304 // managed user.
Amith Yamasani12747872015-12-07 14:19:49 -08002305 sendProfileRemovedBroadcast(userData.info.profileGroupId, userData.info.id);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002306 }
2307
2308 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
2309 int res;
2310 try {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07002311 res = ActivityManagerNative.getDefault().stopUser(userHandle, /* force= */ true,
2312 new IStopUserCallback.Stub() {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002313 @Override
2314 public void userStopped(int userId) {
2315 finishRemoveUser(userId);
2316 }
2317 @Override
2318 public void userStopAborted(int userId) {
2319 }
2320 });
2321 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002322 return false;
2323 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002324 return res == ActivityManager.USER_OP_SUCCESS;
2325 } finally {
2326 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002327 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002328 }
2329
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002330 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07002331 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002332 // Let other services shutdown any activity and clean up their state before completely
2333 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002334 long ident = Binder.clearCallingIdentity();
2335 try {
2336 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
2337 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002338 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
2339 android.Manifest.permission.MANAGE_USERS,
2340
2341 new BroadcastReceiver() {
2342 @Override
2343 public void onReceive(Context context, Intent intent) {
2344 if (DBG) {
2345 Slog.i(LOG_TAG,
2346 "USER_REMOVED broadcast sent, cleaning up user data "
2347 + userHandle);
2348 }
2349 new Thread() {
Amith Yamasani12747872015-12-07 14:19:49 -08002350 @Override
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002351 public void run() {
Amith Yamasani515d4062015-09-28 11:30:06 -07002352 // Clean up any ActivityManager state
2353 LocalServices.getService(ActivityManagerInternal.class)
2354 .onUserRemoved(userHandle);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002355 removeUserState(userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002356 }
2357 }.start();
2358 }
2359 },
2360
2361 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002362 } finally {
2363 Binder.restoreCallingIdentity(ident);
2364 }
Amith Yamasani2a003292012-08-14 18:25:45 -07002365 }
2366
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002367 private void removeUserState(final int userHandle) {
Paul Crowley91293792016-03-25 15:23:07 -07002368 try {
2369 mContext.getSystemService(StorageManager.class).destroyUserKey(userHandle);
2370 } catch (IllegalStateException e) {
2371 // This may be simply because the user was partially created.
2372 Slog.i(LOG_TAG,
2373 "Destroying key for user " + userHandle + " failed, continuing anyway", e);
2374 }
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002375
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002376 // Cleanup package manager settings
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002377 mPm.cleanUpUser(this, userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002378 // Remove this user from the list
Fyodor Kupolov82402752015-10-28 14:54:51 -07002379 synchronized (mUsersLock) {
2380 mUsers.remove(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08002381 mIsUserManaged.delete(userHandle);
Fyodor Kupolovac06a492016-05-25 14:45:29 -07002382 }
2383 synchronized (mUserStates) {
2384 mUserStates.delete(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08002385 }
2386 synchronized (mRestrictionsLock) {
2387 mBaseUserRestrictions.remove(userHandle);
2388 mAppliedUserRestrictions.remove(userHandle);
2389 mCachedEffectiveUserRestrictions.remove(userHandle);
2390 mDevicePolicyLocalUserRestrictions.remove(userHandle);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002391 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002392 // Update the user list
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002393 synchronized (mPackagesLock) {
2394 writeUserListLP();
2395 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06002396 // Remove user file
2397 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
2398 userFile.delete();
Fyodor Kupolov82402752015-10-28 14:54:51 -07002399 updateUserIds();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002400
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002401 // Now that we've purged all the metadata above, destroy the actual data
2402 // on disk; if we battery pull in here we'll finish cleaning up when
2403 // reconciling after reboot.
2404 mPm.destroyUserData(userHandle,
2405 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
Amith Yamasani61f57372012-08-31 12:12:28 -07002406 }
2407
Kenny Guyf8d3a232014-05-15 16:09:52 +01002408 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01002409 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01002410 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
2411 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002412 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
Jeff Sharkeyaf6ec292015-12-17 11:19:00 -07002413 managedProfileIntent.putExtra(Intent.EXTRA_USER_HANDLE, removedUserId);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002414 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01002415 }
2416
Amith Yamasani2a003292012-08-14 18:25:45 -07002417 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002418 public Bundle getApplicationRestrictions(String packageName) {
2419 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
2420 }
2421
2422 @Override
2423 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002424 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07002425 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00002426 checkSystemOrRoot("get application restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002427 }
2428 synchronized (mPackagesLock) {
2429 // Read the restrictions from XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07002430 return readApplicationRestrictionsLP(packageName, userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002431 }
2432 }
2433
2434 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002435 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002436 int userId) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00002437 checkSystemOrRoot("set application restrictions");
Fyodor Kupolov0d88d542016-04-19 11:37:22 -07002438 if (restrictions != null) {
2439 restrictions.setDefusable(true);
2440 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002441 synchronized (mPackagesLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01002442 if (restrictions == null || restrictions.isEmpty()) {
2443 cleanAppRestrictionsForPackage(packageName, userId);
2444 } else {
2445 // Write the restrictions to XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07002446 writeApplicationRestrictionsLP(packageName, restrictions, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01002447 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002448 }
Robin Lee66e5d962014-04-09 16:44:21 +01002449
Fyodor Kupolovd2846122016-02-11 18:06:34 -08002450 // Notify package of changes via an intent - only sent to explicitly registered receivers.
2451 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
2452 changeIntent.setPackage(packageName);
2453 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
2454 mContext.sendBroadcastAsUser(changeIntent, UserHandle.of(userId));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002455 }
2456
2457 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07002458 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002459 try {
2460 return mContext.getPackageManager().getApplicationInfo(packageName,
Fyodor Kupolovd2846122016-02-11 18:06:34 -08002461 PackageManager.MATCH_UNINSTALLED_PACKAGES).uid;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002462 } catch (NameNotFoundException nnfe) {
2463 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07002464 } finally {
2465 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002466 }
2467 }
2468
Fyodor Kupolov82402752015-10-28 14:54:51 -07002469 private Bundle readApplicationRestrictionsLP(String packageName, int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002470 AtomicFile restrictionsFile =
2471 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
2472 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002473 return readApplicationRestrictionsLP(restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002474 }
2475
2476 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002477 static Bundle readApplicationRestrictionsLP(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002478 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002479 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002480 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07002481 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002482 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002483
2484 FileInputStream fis = null;
2485 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002486 fis = restrictionsFile.openRead();
2487 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002488 parser.setInput(fis, StandardCharsets.UTF_8.name());
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002489 XmlUtils.nextElement(parser);
2490 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002491 Slog.e(LOG_TAG, "Unable to read restrictions file "
2492 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002493 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002494 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002495 while (parser.next() != XmlPullParser.END_DOCUMENT) {
2496 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002497 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002498 } catch (IOException|XmlPullParserException e) {
2499 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002500 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002501 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002502 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002503 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002504 }
2505
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002506 private static void readEntry(Bundle restrictions, ArrayList<String> values,
2507 XmlPullParser parser) throws XmlPullParserException, IOException {
2508 int type = parser.getEventType();
2509 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
2510 String key = parser.getAttributeValue(null, ATTR_KEY);
2511 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
2512 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
2513 if (multiple != null) {
2514 values.clear();
2515 int count = Integer.parseInt(multiple);
2516 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
2517 if (type == XmlPullParser.START_TAG
2518 && parser.getName().equals(TAG_VALUE)) {
2519 values.add(parser.nextText().trim());
2520 count--;
2521 }
2522 }
2523 String [] valueStrings = new String[values.size()];
2524 values.toArray(valueStrings);
2525 restrictions.putStringArray(key, valueStrings);
2526 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
2527 restrictions.putBundle(key, readBundleEntry(parser, values));
2528 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
2529 final int outerDepth = parser.getDepth();
2530 ArrayList<Bundle> bundleList = new ArrayList<>();
2531 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2532 Bundle childBundle = readBundleEntry(parser, values);
2533 bundleList.add(childBundle);
2534 }
2535 restrictions.putParcelableArray(key,
2536 bundleList.toArray(new Bundle[bundleList.size()]));
2537 } else {
2538 String value = parser.nextText().trim();
2539 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
2540 restrictions.putBoolean(key, Boolean.parseBoolean(value));
2541 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
2542 restrictions.putInt(key, Integer.parseInt(value));
2543 } else {
2544 restrictions.putString(key, value);
2545 }
2546 }
2547 }
2548 }
2549
2550 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
2551 throws IOException, XmlPullParserException {
2552 Bundle childBundle = new Bundle();
2553 final int outerDepth = parser.getDepth();
2554 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2555 readEntry(childBundle, values, parser);
2556 }
2557 return childBundle;
2558 }
2559
Fyodor Kupolov82402752015-10-28 14:54:51 -07002560 private void writeApplicationRestrictionsLP(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002561 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002562 AtomicFile restrictionsFile = new AtomicFile(
2563 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07002564 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002565 writeApplicationRestrictionsLP(restrictions, restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002566 }
2567
2568 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002569 static void writeApplicationRestrictionsLP(Bundle restrictions, AtomicFile restrictionsFile) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002570 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002571 try {
2572 fos = restrictionsFile.startWrite();
2573 final BufferedOutputStream bos = new BufferedOutputStream(fos);
2574
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002575 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002576 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002577 serializer.startDocument(null, true);
2578 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2579
2580 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002581 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002582 serializer.endTag(null, TAG_RESTRICTIONS);
2583
2584 serializer.endDocument();
2585 restrictionsFile.finishWrite(fos);
2586 } catch (Exception e) {
2587 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002588 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
2589 }
2590 }
2591
2592 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
2593 throws IOException {
2594 for (String key : restrictions.keySet()) {
2595 Object value = restrictions.get(key);
2596 serializer.startTag(null, TAG_ENTRY);
2597 serializer.attribute(null, ATTR_KEY, key);
2598
2599 if (value instanceof Boolean) {
2600 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
2601 serializer.text(value.toString());
2602 } else if (value instanceof Integer) {
2603 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
2604 serializer.text(value.toString());
2605 } else if (value == null || value instanceof String) {
2606 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
2607 serializer.text(value != null ? (String) value : "");
2608 } else if (value instanceof Bundle) {
2609 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2610 writeBundle((Bundle) value, serializer);
2611 } else if (value instanceof Parcelable[]) {
2612 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
2613 Parcelable[] array = (Parcelable[]) value;
2614 for (Parcelable parcelable : array) {
2615 if (!(parcelable instanceof Bundle)) {
2616 throw new IllegalArgumentException("bundle-array can only hold Bundles");
2617 }
2618 serializer.startTag(null, TAG_ENTRY);
2619 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2620 writeBundle((Bundle) parcelable, serializer);
2621 serializer.endTag(null, TAG_ENTRY);
2622 }
2623 } else {
2624 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
2625 String[] values = (String[]) value;
2626 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
2627 for (String choice : values) {
2628 serializer.startTag(null, TAG_VALUE);
2629 serializer.text(choice != null ? choice : "");
2630 serializer.endTag(null, TAG_VALUE);
2631 }
2632 }
2633 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002634 }
2635 }
2636
2637 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07002638 public int getUserSerialNumber(int userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002639 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002640 if (!exists(userHandle)) return -1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002641 return getUserInfoLU(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07002642 }
2643 }
2644
2645 @Override
2646 public int getUserHandle(int userSerialNumber) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002647 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002648 for (int userId : mUserIds) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002649 UserInfo info = getUserInfoLU(userId);
Kenny Guy945f8832015-02-10 15:17:26 +00002650 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07002651 }
2652 // Not found
2653 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07002654 }
2655 }
2656
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002657 @Override
2658 public long getUserCreationTime(int userHandle) {
2659 int callingUserId = UserHandle.getCallingUserId();
2660 UserInfo userInfo = null;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002661 synchronized (mUsersLock) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002662 if (callingUserId == userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002663 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002664 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002665 UserInfo parent = getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002666 if (parent != null && parent.id == callingUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002667 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002668 }
2669 }
2670 }
2671 if (userInfo == null) {
2672 throw new SecurityException("userHandle can only be the calling user or a managed "
2673 + "profile associated with this user");
2674 }
2675 return userInfo.creationTime;
2676 }
2677
Amith Yamasani0b285492011-04-14 17:35:23 -07002678 /**
2679 * Caches the list of user ids in an array, adjusting the array size when necessary.
2680 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002681 private void updateUserIds() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002682 int num = 0;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002683 synchronized (mUsersLock) {
2684 final int userSize = mUsers.size();
2685 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002686 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002687 num++;
2688 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002689 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002690 final int[] newUsers = new int[num];
2691 int n = 0;
2692 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002693 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002694 newUsers[n++] = mUsers.keyAt(i);
2695 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002696 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002697 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07002698 }
2699 }
2700
2701 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002702 * Called right before a user is started. This gives us a chance to prepare
2703 * app storage and apply any user restrictions.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002704 */
2705 public void onBeforeStartUser(int userId) {
Jeff Sharkey47f71082016-02-01 17:03:54 -07002706 final int userSerial = getUserSerialNumber(userId);
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002707 mPm.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_DE);
Jeff Sharkey47f71082016-02-01 17:03:54 -07002708 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_DE);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002709
2710 if (userId != UserHandle.USER_SYSTEM) {
2711 synchronized (mRestrictionsLock) {
2712 applyUserRestrictionsLR(userId);
2713 }
Fyodor Kupolovb45d9832016-05-16 13:25:34 -07002714 UserInfo userInfo = getUserInfoNoChecks(userId);
2715 if (userInfo != null && !userInfo.isInitialized()) {
2716 mPm.onBeforeUserStartUninitialized(userId);
2717 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002718 }
2719 }
2720
2721 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002722 * Called right before a user is unlocked. This gives us a chance to prepare
2723 * app storage.
2724 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002725 public void onBeforeUnlockUser(@UserIdInt int userId) {
Jeff Sharkey47f71082016-02-01 17:03:54 -07002726 final int userSerial = getUserSerialNumber(userId);
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002727 mPm.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_CE);
Jeff Sharkey47f71082016-02-01 17:03:54 -07002728 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_CE);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002729 }
2730
2731 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002732 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasani920ace02012-09-20 22:15:37 -07002733 * @param userId the user that was just foregrounded
2734 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002735 public void onUserLoggedIn(@UserIdInt int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -08002736 UserData userData = getUserDataNoChecks(userId);
2737 if (userData == null || userData.info.partial) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002738 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
2739 return;
2740 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002741
2742 final long now = System.currentTimeMillis();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002743 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani12747872015-12-07 14:19:49 -08002744 userData.info.lastLoggedInTime = now;
Amith Yamasani920ace02012-09-20 22:15:37 -07002745 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002746 userData.info.lastLoggedInFingerprint = Build.FINGERPRINT;
2747 scheduleWriteUser(userData);
Amith Yamasani920ace02012-09-20 22:15:37 -07002748 }
2749
2750 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002751 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani742a6712011-05-04 14:49:28 -07002752 * TODO: May not be a good idea to recycle ids, in case it results in confusion
2753 * for data and battery stats collection, or unexpected cross-talk.
Amith Yamasani0b285492011-04-14 17:35:23 -07002754 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002755 private int getNextAvailableId() {
2756 synchronized (mUsersLock) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002757 int i = MIN_USER_ID;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002758 while (i < MAX_USER_ID) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002759 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002760 return i;
Amith Yamasani195263742012-08-21 15:40:12 -07002761 }
2762 i++;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002763 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002764 }
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002765 throw new IllegalStateException("No user id available!");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002766 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002767
Amith Yamasanifc95e702013-09-26 13:20:17 -07002768 private String packageToRestrictionsFileName(String packageName) {
2769 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
2770 }
2771
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002772 /**
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002773 * Enforce that serial number stored in user directory inode matches the
2774 * given expected value. Gracefully sets the serial number if currently
2775 * undefined.
2776 *
2777 * @throws IOException when problem extracting serial number, or serial
2778 * number is mismatched.
2779 */
2780 public static void enforceSerialNumber(File file, int serialNumber) throws IOException {
2781 final int foundSerial = getSerialNumber(file);
2782 Slog.v(LOG_TAG, "Found " + file + " with serial number " + foundSerial);
2783
2784 if (foundSerial == -1) {
2785 Slog.d(LOG_TAG, "Serial number missing on " + file + "; assuming current is valid");
2786 try {
2787 setSerialNumber(file, serialNumber);
2788 } catch (IOException e) {
2789 Slog.w(LOG_TAG, "Failed to set serial number on " + file, e);
2790 }
2791
2792 } else if (foundSerial != serialNumber) {
2793 throw new IOException("Found serial number " + foundSerial
2794 + " doesn't match expected " + serialNumber);
2795 }
2796 }
2797
2798 /**
2799 * Set serial number stored in user directory inode.
2800 *
2801 * @throws IOException if serial number was already set
2802 */
2803 private static void setSerialNumber(File file, int serialNumber)
2804 throws IOException {
2805 try {
2806 final byte[] buf = Integer.toString(serialNumber).getBytes(StandardCharsets.UTF_8);
2807 Os.setxattr(file.getAbsolutePath(), XATTR_SERIAL, buf, OsConstants.XATTR_CREATE);
2808 } catch (ErrnoException e) {
2809 throw e.rethrowAsIOException();
2810 }
2811 }
2812
2813 /**
2814 * Return serial number stored in user directory inode.
2815 *
2816 * @return parsed serial number, or -1 if not set
2817 */
2818 private static int getSerialNumber(File file) throws IOException {
2819 try {
2820 final byte[] buf = new byte[256];
2821 final int len = Os.getxattr(file.getAbsolutePath(), XATTR_SERIAL, buf);
2822 final String serial = new String(buf, 0, len);
2823 try {
2824 return Integer.parseInt(serial);
2825 } catch (NumberFormatException e) {
2826 throw new IOException("Bad serial number: " + serial);
2827 }
2828 } catch (ErrnoException e) {
2829 if (e.errno == OsConstants.ENODATA) {
2830 return -1;
2831 } else {
2832 throw e.rethrowAsIOException();
2833 }
2834 }
2835 }
2836
Amith Yamasani920ace02012-09-20 22:15:37 -07002837 @Override
Amith Yamasani12747872015-12-07 14:19:49 -08002838 public void setSeedAccountData(int userId, String accountName, String accountType,
2839 PersistableBundle accountOptions, boolean persist) {
2840 checkManageUsersPermission("Require MANAGE_USERS permission to set user seed data");
2841 synchronized (mPackagesLock) {
2842 final UserData userData;
2843 synchronized (mUsersLock) {
2844 userData = getUserDataLU(userId);
2845 if (userData == null) {
2846 Slog.e(LOG_TAG, "No such user for settings seed data u=" + userId);
2847 return;
2848 }
2849 userData.seedAccountName = accountName;
2850 userData.seedAccountType = accountType;
2851 userData.seedAccountOptions = accountOptions;
2852 userData.persistSeedData = persist;
2853 }
2854 if (persist) {
2855 writeUserLP(userData);
2856 }
2857 }
2858 }
2859
2860 @Override
2861 public String getSeedAccountName() throws RemoteException {
2862 checkManageUsersPermission("Cannot get seed account information");
2863 synchronized (mUsersLock) {
2864 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
2865 return userData.seedAccountName;
2866 }
2867 }
2868
2869 @Override
2870 public String getSeedAccountType() throws RemoteException {
2871 checkManageUsersPermission("Cannot get seed account information");
2872 synchronized (mUsersLock) {
2873 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
2874 return userData.seedAccountType;
2875 }
2876 }
2877
2878 @Override
2879 public PersistableBundle getSeedAccountOptions() throws RemoteException {
2880 checkManageUsersPermission("Cannot get seed account information");
2881 synchronized (mUsersLock) {
2882 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
2883 return userData.seedAccountOptions;
2884 }
2885 }
2886
2887 @Override
2888 public void clearSeedAccountData() throws RemoteException {
2889 checkManageUsersPermission("Cannot clear seed account information");
2890 synchronized (mPackagesLock) {
2891 UserData userData;
2892 synchronized (mUsersLock) {
2893 userData = getUserDataLU(UserHandle.getCallingUserId());
2894 if (userData == null) return;
2895 userData.clearSeedAccountData();
2896 }
2897 writeUserLP(userData);
2898 }
2899 }
2900
2901 @Override
2902 public boolean someUserHasSeedAccount(String accountName, String accountType)
2903 throws RemoteException {
2904 checkManageUsersPermission("Cannot check seed account information");
2905 synchronized (mUsersLock) {
2906 final int userSize = mUsers.size();
2907 for (int i = 0; i < userSize; i++) {
2908 final UserData data = mUsers.valueAt(i);
2909 if (data.info.isInitialized()) continue;
2910 if (data.seedAccountName == null || !data.seedAccountName.equals(accountName)) {
2911 continue;
2912 }
2913 if (data.seedAccountType == null || !data.seedAccountType.equals(accountType)) {
2914 continue;
2915 }
2916 return true;
2917 }
2918 }
2919 return false;
2920 }
2921
2922 @Override
Todd Kennedy60459ab2015-10-30 11:32:16 -07002923 public void onShellCommand(FileDescriptor in, FileDescriptor out,
2924 FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
2925 (new Shell()).exec(this, in, out, err, args, resultReceiver);
2926 }
2927
2928 int onShellCommand(Shell shell, String cmd) {
2929 if (cmd == null) {
2930 return shell.handleDefaultCommands(cmd);
2931 }
2932
2933 final PrintWriter pw = shell.getOutPrintWriter();
2934 try {
2935 switch(cmd) {
2936 case "list":
2937 return runList(pw);
2938 }
2939 } catch (RemoteException e) {
2940 pw.println("Remote exception: " + e);
2941 }
2942 return -1;
2943 }
2944
2945 private int runList(PrintWriter pw) throws RemoteException {
2946 final IActivityManager am = ActivityManagerNative.getDefault();
2947 final List<UserInfo> users = getUsers(false);
2948 if (users == null) {
2949 pw.println("Error: couldn't get users");
2950 return 1;
2951 } else {
2952 pw.println("Users:");
2953 for (int i = 0; i < users.size(); i++) {
Jeff Sharkeye17ac152015-11-06 22:40:29 -08002954 String running = am.isUserRunning(users.get(i).id, 0) ? " running" : "";
Todd Kennedy60459ab2015-10-30 11:32:16 -07002955 pw.println("\t" + users.get(i).toString() + running);
2956 }
2957 return 0;
2958 }
2959 }
2960
2961 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -07002962 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2963 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2964 != PackageManager.PERMISSION_GRANTED) {
2965 pw.println("Permission Denial: can't dump UserManager from from pid="
2966 + Binder.getCallingPid()
2967 + ", uid=" + Binder.getCallingUid()
2968 + " without permission "
2969 + android.Manifest.permission.DUMP);
2970 return;
2971 }
2972
2973 long now = System.currentTimeMillis();
2974 StringBuilder sb = new StringBuilder();
2975 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002976 synchronized (mUsersLock) {
2977 pw.println("Users:");
2978 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002979 UserData userData = mUsers.valueAt(i);
2980 if (userData == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002981 continue;
2982 }
Amith Yamasani12747872015-12-07 14:19:49 -08002983 UserInfo userInfo = userData.info;
2984 final int userId = userInfo.id;
2985 pw.print(" "); pw.print(userInfo);
2986 pw.print(" serialNo="); pw.print(userInfo.serialNumber);
Makoto Onukie7927da2015-11-25 10:05:17 -08002987 if (mRemovingUserIds.get(userId)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002988 pw.print(" <removing> ");
2989 }
Amith Yamasani12747872015-12-07 14:19:49 -08002990 if (userInfo.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002991 pw.print(" <partial>");
2992 }
2993 pw.println();
2994 pw.print(" Created: ");
Amith Yamasani12747872015-12-07 14:19:49 -08002995 if (userInfo.creationTime == 0) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002996 pw.println("<unknown>");
2997 } else {
2998 sb.setLength(0);
Amith Yamasani12747872015-12-07 14:19:49 -08002999 TimeUtils.formatDuration(now - userInfo.creationTime, sb);
Fyodor Kupolov82402752015-10-28 14:54:51 -07003000 sb.append(" ago");
3001 pw.println(sb);
3002 }
3003 pw.print(" Last logged in: ");
Amith Yamasani12747872015-12-07 14:19:49 -08003004 if (userInfo.lastLoggedInTime == 0) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003005 pw.println("<unknown>");
3006 } else {
3007 sb.setLength(0);
Amith Yamasani12747872015-12-07 14:19:49 -08003008 TimeUtils.formatDuration(now - userInfo.lastLoggedInTime, sb);
Fyodor Kupolov82402752015-10-28 14:54:51 -07003009 sb.append(" ago");
3010 pw.println(sb);
3011 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003012 pw.print(" Last logged in fingerprint: ");
3013 pw.println(userInfo.lastLoggedInFingerprint);
Makoto Onukie7927da2015-11-25 10:05:17 -08003014 pw.print(" Has profile owner: ");
3015 pw.println(mIsUserManaged.get(userId));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003016 pw.println(" Restrictions:");
3017 synchronized (mRestrictionsLock) {
3018 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003019 pw, " ", mBaseUserRestrictions.get(userInfo.id));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003020 pw.println(" Device policy local restrictions:");
3021 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003022 pw, " ", mDevicePolicyLocalUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003023 pw.println(" Effective restrictions:");
3024 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003025 pw, " ", mCachedEffectiveUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003026 }
Amith Yamasani12747872015-12-07 14:19:49 -08003027
3028 if (userData.account != null) {
3029 pw.print(" Account name: " + userData.account);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08003030 pw.println();
3031 }
Amith Yamasani12747872015-12-07 14:19:49 -08003032
3033 if (userData.seedAccountName != null) {
3034 pw.print(" Seed account name: " + userData.seedAccountName);
3035 pw.println();
3036 if (userData.seedAccountType != null) {
3037 pw.print(" account type: " + userData.seedAccountType);
3038 pw.println();
3039 }
3040 if (userData.seedAccountOptions != null) {
3041 pw.print(" account options exist");
3042 pw.println();
3043 }
3044 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003045 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003046 }
Amith Yamasani12747872015-12-07 14:19:49 -08003047 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003048 pw.println(" Device policy global restrictions:");
3049 synchronized (mRestrictionsLock) {
3050 UserRestrictionsUtils
3051 .dumpRestrictions(pw, " ", mDevicePolicyGlobalUserRestrictions);
3052 }
Makoto Onukia4f11972015-10-01 13:19:58 -07003053 pw.println();
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01003054 pw.println(" Global restrictions owner id:" + mGlobalRestrictionOwnerUserId);
3055 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003056 pw.println(" Guest restrictions:");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003057 synchronized (mGuestRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003058 UserRestrictionsUtils.dumpRestrictions(pw, " ", mGuestRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003059 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003060 synchronized (mUsersLock) {
3061 pw.println();
3062 pw.println(" Device managed: " + mIsDeviceManaged);
3063 }
Fyodor Kupolovac06a492016-05-25 14:45:29 -07003064 synchronized (mUserStates) {
3065 pw.println(" Started users state: " + mUserStates);
3066 }
Amith Yamasani12747872015-12-07 14:19:49 -08003067 // Dump some capabilities
3068 pw.println();
3069 pw.println(" Max users: " + UserManager.getMaxSupportedUsers());
3070 pw.println(" Supports switchable users: " + UserManager.supportsMultipleUsers());
Lenka Trochtova02fee152015-12-22 14:26:18 +01003071 pw.println(" All guests ephemeral: " + Resources.getSystem().getBoolean(
3072 com.android.internal.R.bool.config_guestUserEphemeral));
Amith Yamasani920ace02012-09-20 22:15:37 -07003073 }
3074 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08003075
3076 final class MainHandler extends Handler {
3077
3078 @Override
3079 public void handleMessage(Message msg) {
3080 switch (msg.what) {
3081 case WRITE_USER_MSG:
3082 removeMessages(WRITE_USER_MSG, msg.obj);
3083 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08003084 int userId = ((UserData) msg.obj).info.id;
3085 UserData userData = getUserDataNoChecks(userId);
3086 if (userData != null) {
3087 writeUserLP(userData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08003088 }
3089 }
3090 }
3091 }
3092 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07003093
3094 /**
3095 * @param userId
3096 * @return whether the user has been initialized yet
3097 */
3098 boolean isInitialized(int userId) {
3099 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
3100 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003101
3102 private class LocalService extends UserManagerInternal {
Makoto Onuki068c54a2015-10-13 14:34:03 -07003103 @Override
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003104 public void setDevicePolicyUserRestrictions(int userId, @NonNull Bundle localRestrictions,
3105 @Nullable Bundle globalRestrictions) {
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08003106 UserManagerService.this.setDevicePolicyUserRestrictionsInner(userId, localRestrictions,
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003107 globalRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003108 }
3109
3110 @Override
3111 public Bundle getBaseUserRestrictions(int userId) {
3112 synchronized (mRestrictionsLock) {
3113 return mBaseUserRestrictions.get(userId);
3114 }
3115 }
3116
3117 @Override
3118 public void setBaseUserRestrictionsByDpmsForMigration(
3119 int userId, Bundle baseRestrictions) {
3120 synchronized (mRestrictionsLock) {
3121 mBaseUserRestrictions.put(userId, new Bundle(baseRestrictions));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003122 invalidateEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003123 }
3124
Amith Yamasani12747872015-12-07 14:19:49 -08003125 final UserData userData = getUserDataNoChecks(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003126 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08003127 if (userData != null) {
3128 writeUserLP(userData);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003129 } else {
3130 Slog.w(LOG_TAG, "UserInfo not found for " + userId);
3131 }
3132 }
3133 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08003134
3135 @Override
3136 public boolean getUserRestriction(int userId, String key) {
3137 return getUserRestrictions(userId).getBoolean(key);
3138 }
3139
3140 @Override
3141 public void addUserRestrictionsListener(UserRestrictionsListener listener) {
3142 synchronized (mUserRestrictionsListeners) {
3143 mUserRestrictionsListeners.add(listener);
3144 }
3145 }
3146
3147 @Override
3148 public void removeUserRestrictionsListener(UserRestrictionsListener listener) {
3149 synchronized (mUserRestrictionsListeners) {
3150 mUserRestrictionsListeners.remove(listener);
3151 }
3152 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003153
3154 @Override
3155 public void setDeviceManaged(boolean isManaged) {
3156 synchronized (mUsersLock) {
3157 mIsDeviceManaged = isManaged;
3158 }
3159 }
3160
3161 @Override
3162 public void setUserManaged(int userId, boolean isManaged) {
3163 synchronized (mUsersLock) {
3164 mIsUserManaged.put(userId, isManaged);
3165 }
3166 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01003167
3168 @Override
3169 public void setUserIcon(int userId, Bitmap bitmap) {
3170 long ident = Binder.clearCallingIdentity();
3171 try {
3172 synchronized (mPackagesLock) {
3173 UserData userData = getUserDataNoChecks(userId);
3174 if (userData == null || userData.info.partial) {
3175 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
3176 return;
3177 }
3178 writeBitmapLP(userData.info, bitmap);
3179 writeUserLP(userData);
3180 }
3181 sendUserInfoChangedBroadcast(userId);
3182 } finally {
3183 Binder.restoreCallingIdentity(ident);
3184 }
3185 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01003186
3187 @Override
3188 public void setForceEphemeralUsers(boolean forceEphemeralUsers) {
3189 synchronized (mUsersLock) {
3190 mForceEphemeralUsers = forceEphemeralUsers;
3191 }
3192 }
3193
3194 @Override
3195 public void removeAllUsers() {
3196 if (UserHandle.USER_SYSTEM == ActivityManager.getCurrentUser()) {
3197 // Remove the non-system users straight away.
3198 removeNonSystemUsers();
3199 } else {
3200 // Switch to the system user first and then remove the other users.
3201 BroadcastReceiver userSwitchedReceiver = new BroadcastReceiver() {
3202 @Override
3203 public void onReceive(Context context, Intent intent) {
3204 int userId =
3205 intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3206 if (userId != UserHandle.USER_SYSTEM) {
3207 return;
3208 }
3209 mContext.unregisterReceiver(this);
3210 removeNonSystemUsers();
3211 }
3212 };
3213 IntentFilter userSwitchedFilter = new IntentFilter();
3214 userSwitchedFilter.addAction(Intent.ACTION_USER_SWITCHED);
3215 mContext.registerReceiver(
3216 userSwitchedReceiver, userSwitchedFilter, null, mHandler);
3217
3218 // Switch to the system user.
3219 ActivityManager am =
3220 (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
3221 am.switchUser(UserHandle.USER_SYSTEM);
3222 }
3223 }
phweisse9c44062016-02-10 12:57:38 +01003224
3225 @Override
Lenka Trochtova1ddda472016-02-12 10:42:12 +01003226 public void onEphemeralUserStop(int userId) {
3227 synchronized (mUsersLock) {
3228 UserInfo userInfo = getUserInfoLU(userId);
3229 if (userInfo != null && userInfo.isEphemeral()) {
3230 // Do not allow switching back to the ephemeral user again as the user is going
3231 // to be deleted.
3232 userInfo.flags |= UserInfo.FLAG_DISABLED;
3233 if (userInfo.isGuest()) {
3234 // Indicate that the guest will be deleted after it stops.
3235 userInfo.guestToRemove = true;
3236 }
3237 }
3238 }
3239 }
3240
3241 @Override
phweisse9c44062016-02-10 12:57:38 +01003242 public UserInfo createUserEvenWhenDisallowed(String name, int flags) {
3243 UserInfo user = createUserInternalUnchecked(name, flags, UserHandle.USER_NULL);
3244 // Keep this in sync with UserManager.createUser
3245 if (user != null && !user.isAdmin()) {
3246 setUserRestriction(UserManager.DISALLOW_SMS, true, user.id);
3247 setUserRestriction(UserManager.DISALLOW_OUTGOING_CALLS, true, user.id);
3248 }
3249 return user;
3250 }
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003251
3252 @Override
Fyodor Kupolovac06a492016-05-25 14:45:29 -07003253 public boolean isUserRunning(int userId) {
3254 synchronized (mUserStates) {
3255 return mUserStates.get(userId, -1) >= 0;
3256 }
3257 }
3258
3259 @Override
3260 public void setUserState(int userId, int userState) {
3261 synchronized (mUserStates) {
3262 mUserStates.put(userId, userState);
3263 }
3264 }
3265
3266 @Override
3267 public void removeUserState(int userId) {
3268 synchronized (mUserStates) {
3269 mUserStates.delete(userId);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003270 }
3271 }
3272
3273 @Override
3274 public boolean isUserUnlockingOrUnlocked(int userId) {
Fyodor Kupolovac06a492016-05-25 14:45:29 -07003275 synchronized (mUserStates) {
3276 int state = mUserStates.get(userId, -1);
3277 return (state == UserState.STATE_RUNNING_UNLOCKING)
3278 || (state == UserState.STATE_RUNNING_UNLOCKED);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003279 }
3280 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01003281 }
3282
3283 /* Remove all the users except of the system one. */
3284 private void removeNonSystemUsers() {
3285 ArrayList<UserInfo> usersToRemove = new ArrayList<>();
3286 synchronized (mUsersLock) {
3287 final int userSize = mUsers.size();
3288 for (int i = 0; i < userSize; i++) {
3289 UserInfo ui = mUsers.valueAt(i).info;
3290 if (ui.id != UserHandle.USER_SYSTEM) {
3291 usersToRemove.add(ui);
3292 }
3293 }
3294 }
3295 for (UserInfo ui: usersToRemove) {
3296 removeUser(ui.id);
3297 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003298 }
Todd Kennedy60459ab2015-10-30 11:32:16 -07003299
3300 private class Shell extends ShellCommand {
3301 @Override
3302 public int onCommand(String cmd) {
3303 return onShellCommand(this, cmd);
3304 }
3305
3306 @Override
3307 public void onHelp() {
3308 final PrintWriter pw = getOutPrintWriter();
3309 pw.println("User manager (user) commands:");
3310 pw.println(" help");
3311 pw.println(" Print this help text.");
3312 pw.println("");
3313 pw.println(" list");
3314 pw.println(" Prints all users on the system.");
3315 }
3316 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003317
3318 private static void debug(String message) {
3319 Log.d(LOG_TAG, message +
3320 (DBG_WITH_STACKTRACE ? " called at\n" + Debug.getCallers(10, " ") : ""));
3321 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003322}