blob: 9b918f3fb99358ed8f5ba9f782f83c9067707608 [file] [log] [blame]
Tony Mak8673b282016-03-21 21:10:59 +00001
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002/*
3 * Copyright (C) 2011 The Android Open Source Project
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18package com.android.server.pm;
19
Benjamin Franzf02420c2016-04-04 18:52:21 +010020import static android.content.Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS;
21import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
22
Xiaohui Chenb3b92582015-12-07 11:22:13 -080023import android.Manifest;
Xiaohui Chen594f2082015-08-18 11:04:20 -070024import android.annotation.NonNull;
Makoto Onuki068c54a2015-10-13 14:34:03 -070025import android.annotation.Nullable;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -060026import android.annotation.UserIdInt;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070027import android.app.Activity;
Amith Yamasani2a003292012-08-14 18:25:45 -070028import android.app.ActivityManager;
Amith Yamasani515d4062015-09-28 11:30:06 -070029import android.app.ActivityManagerInternal;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070030import android.app.ActivityManagerNative;
Todd Kennedy60459ab2015-10-30 11:32:16 -070031import android.app.IActivityManager;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070032import android.app.IStopUserCallback;
Benjamin Franzf02420c2016-04-04 18:52:21 +010033import android.app.KeyguardManager;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070034import android.content.BroadcastReceiver;
Amith Yamasani258848d2012-08-10 17:06:33 -070035import android.content.Context;
36import android.content.Intent;
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +010037import android.content.IntentFilter;
Benjamin Franzf02420c2016-04-04 18:52:21 +010038import android.content.IntentSender;
Amith Yamasani0b285492011-04-14 17:35:23 -070039import android.content.pm.PackageManager;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -080040import android.content.pm.PackageManager.NameNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070041import android.content.pm.UserInfo;
Lenka Trochtova02fee152015-12-22 14:26:18 +010042import android.content.res.Resources;
Amith Yamasanie928d7d2012-09-17 21:46:51 -070043import android.graphics.Bitmap;
Amith Yamasani258848d2012-08-10 17:06:33 -070044import android.os.Binder;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -060045import android.os.Build;
Amith Yamasanie4cf7342012-12-17 11:12:09 -080046import android.os.Bundle;
Makoto Onuki1a2cd742015-11-16 13:51:27 -080047import android.os.Debug;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070048import android.os.Environment;
49import android.os.FileUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080050import android.os.Handler;
Svet Ganov9cea80cd2016-02-16 11:47:00 -080051import android.os.IBinder;
Amith Yamasani258848d2012-08-10 17:06:33 -070052import android.os.IUserManager;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -080053import android.os.Message;
Adrian Roos1bdff912015-02-17 15:51:35 +010054import android.os.ParcelFileDescriptor;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070055import android.os.Parcelable;
Amith Yamasani12747872015-12-07 14:19:49 -080056import android.os.PersistableBundle;
Amith Yamasani258848d2012-08-10 17:06:33 -070057import android.os.Process;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070058import android.os.RemoteException;
Todd Kennedy60459ab2015-10-30 11:32:16 -070059import android.os.ResultReceiver;
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +010060import android.os.SELinux;
Jason Monk62062992014-05-06 09:55:28 -040061import android.os.ServiceManager;
Todd Kennedy60459ab2015-10-30 11:32:16 -070062import android.os.ShellCommand;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070063import android.os.UserHandle;
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070064import android.os.UserManager;
Makoto Onuki068c54a2015-10-13 14:34:03 -070065import android.os.UserManagerInternal;
Makoto Onukid45a4a22015-11-02 17:17:38 -080066import android.os.UserManagerInternal.UserRestrictionsListener;
Paul Crowley85e4e812015-05-19 12:42:00 +010067import android.os.storage.StorageManager;
Jeff Sharkey6dce4962015-07-03 18:08:41 -070068import android.os.storage.VolumeInfo;
69import android.system.ErrnoException;
70import android.system.Os;
71import android.system.OsConstants;
Amith Yamasani2a003292012-08-14 18:25:45 -070072import android.util.AtomicFile;
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -070073import android.util.IntArray;
Amith Yamasani655d0e22013-06-12 14:19:10 -070074import android.util.Log;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070075import android.util.Slog;
76import android.util.SparseArray;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080077import android.util.SparseBooleanArray;
Amith Yamasani920ace02012-09-20 22:15:37 -070078import android.util.TimeUtils;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070079import android.util.Xml;
80
Makoto Onuki068c54a2015-10-13 14:34:03 -070081import com.android.internal.annotations.GuardedBy;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070082import com.android.internal.annotations.VisibleForTesting;
Jason Monk62062992014-05-06 09:55:28 -040083import com.android.internal.app.IAppOpsService;
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -080084import com.android.internal.logging.MetricsLogger;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080085import com.android.internal.util.FastXmlSerializer;
Makoto Onuki068c54a2015-10-13 14:34:03 -070086import com.android.internal.util.Preconditions;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070087import com.android.internal.util.XmlUtils;
Clara Bayarri10ad84a2015-12-01 17:38:05 +000088import com.android.internal.widget.LockPatternUtils;
Amith Yamasani515d4062015-09-28 11:30:06 -070089import com.android.server.LocalServices;
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";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800147 private static final String TAG_ENTRY = "entry";
148 private static final String TAG_VALUE = "value";
Amith Yamasani12747872015-12-07 14:19:49 -0800149 private static final String TAG_SEED_ACCOUNT_OPTIONS = "seedAccountOptions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800150 private static final String ATTR_KEY = "key";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700151 private static final String ATTR_VALUE_TYPE = "type";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800152 private static final String ATTR_MULTIPLE = "m";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700153
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700154 private static final String ATTR_TYPE_STRING_ARRAY = "sa";
155 private static final String ATTR_TYPE_STRING = "s";
156 private static final String ATTR_TYPE_BOOLEAN = "b";
Amith Yamasani5b5aa402014-06-01 20:10:14 -0700157 private static final String ATTR_TYPE_INTEGER = "i";
Fyodor Kupolov262f9952015-03-23 18:55:11 -0700158 private static final String ATTR_TYPE_BUNDLE = "B";
159 private static final String ATTR_TYPE_BUNDLE_ARRAY = "BA";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700160
Amith Yamasani0b285492011-04-14 17:35:23 -0700161 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700162 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700163 private static final String USER_PHOTO_FILENAME = "photo.png";
Adrian Roos1bdff912015-02-17 15:51:35 +0100164 private static final String USER_PHOTO_FILENAME_TMP = USER_PHOTO_FILENAME + ".tmp";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700165
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800166 private static final String RESTRICTIONS_FILE_PREFIX = "res_";
Amith Yamasanifc95e702013-09-26 13:20:17 -0700167 private static final String XML_SUFFIX = ".xml";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800168
Amith Yamasani634cf312012-10-04 17:34:21 -0700169 private static final int MIN_USER_ID = 10;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700170 // We need to keep process uid within Integer.MAX_VALUE.
171 private static final int MAX_USER_ID = Integer.MAX_VALUE / UserHandle.PER_USER_RANGE;
Amith Yamasani634cf312012-10-04 17:34:21 -0700172
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700173 private static final int USER_VERSION = 6;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700174
Amith Yamasani920ace02012-09-20 22:15:37 -0700175 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
176
Nicolas Prevotb8186812015-08-06 15:00:03 +0100177 // Maximum number of managed profiles permitted per user is 1. This cannot be increased
Amith Yamasani95ab7842014-08-11 17:09:26 -0700178 // without first making sure that the rest of the framework is prepared for it.
179 private static final int MAX_MANAGED_PROFILES = 1;
180
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800181 static final int WRITE_USER_MSG = 1;
182 static final int WRITE_USER_DELAY = 2*1000; // 2 seconds
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530183
Jeff Sharkey6dce4962015-07-03 18:08:41 -0700184 private static final String XATTR_SERIAL = "user.serial";
185
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -0800186 // Tron counters
187 private static final String TRON_GUEST_CREATED = "users_guest_created";
188 private static final String TRON_USER_CREATED = "users_user_created";
189
Dianne Hackborn4428e172012-08-24 17:43:05 -0700190 private final Context mContext;
191 private final PackageManagerService mPm;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700192 private final Object mPackagesLock;
Fyodor Kupolov82402752015-10-28 14:54:51 -0700193 // Short-term lock for internal state, when interaction/sync with PM is not required
194 private final Object mUsersLock = new Object();
195 private final Object mRestrictionsLock = new Object();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700196
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800197 private final Handler mHandler;
198
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700199 private final File mUsersDir;
200 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700201
Svet Ganov9cea80cd2016-02-16 11:47:00 -0800202 private static final IBinder mUserRestriconToken = new Binder();
203
Makoto Onuki068c54a2015-10-13 14:34:03 -0700204 /**
Amith Yamasani12747872015-12-07 14:19:49 -0800205 * User-related information that is used for persisting to flash. Only UserInfo is
206 * directly exposed to other system apps.
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800207 */
Amith Yamasani12747872015-12-07 14:19:49 -0800208 private static class UserData {
209 // Basic user information and properties
210 UserInfo info;
211 // Account name used when there is a strong association between a user and an account
212 String account;
213 // Account information for seeding into a newly created user. This could also be
214 // used for login validation for an existing user, for updating their credentials.
215 // In the latter case, data may not need to be persisted as it is only valid for the
216 // current login session.
217 String seedAccountName;
218 String seedAccountType;
219 PersistableBundle seedAccountOptions;
220 // Whether to perist the seed account information to be available after a boot
221 boolean persistSeedData;
222
223 void clearSeedAccountData() {
224 seedAccountName = null;
225 seedAccountType = null;
226 seedAccountOptions = null;
227 persistSeedData = false;
228 }
229 }
230
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800231 @GuardedBy("mUsersLock")
Amith Yamasani12747872015-12-07 14:19:49 -0800232 private final SparseArray<UserData> mUsers = new SparseArray<>();
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800233
234 /**
Makoto Onuki068c54a2015-10-13 14:34:03 -0700235 * User restrictions set via UserManager. This doesn't include restrictions set by
236 * device owner / profile owners.
237 *
238 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
239 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
240 * maybe shared between {@link #mBaseUserRestrictions} and
241 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
242 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700243 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700244 */
245 @GuardedBy("mRestrictionsLock")
246 private final SparseArray<Bundle> mBaseUserRestrictions = new SparseArray<>();
247
248 /**
249 * Cached user restrictions that are in effect -- i.e. {@link #mBaseUserRestrictions} combined
250 * with device / profile owner restrictions. We'll initialize it lazily; use
251 * {@link #getEffectiveUserRestrictions} to access it.
252 *
253 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
254 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
255 * maybe shared between {@link #mBaseUserRestrictions} and
256 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
257 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700258 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700259 */
260 @GuardedBy("mRestrictionsLock")
261 private final SparseArray<Bundle> mCachedEffectiveUserRestrictions = new SparseArray<>();
262
Makoto Onuki4f160732015-10-27 17:15:38 -0700263 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800264 * User restrictions that have already been applied in
265 * {@link #updateUserRestrictionsInternalLR(Bundle, int)}. We use it to detect restrictions
266 * that have changed since the last
267 * {@link #updateUserRestrictionsInternalLR(Bundle, int)} call.
Makoto Onuki4f160732015-10-27 17:15:38 -0700268 */
269 @GuardedBy("mRestrictionsLock")
270 private final SparseArray<Bundle> mAppliedUserRestrictions = new SparseArray<>();
271
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800272 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800273 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
274 * that should be applied to all users, including guests.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800275 */
276 @GuardedBy("mRestrictionsLock")
277 private Bundle mDevicePolicyGlobalUserRestrictions;
278
279 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800280 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
281 * for each user.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800282 */
283 @GuardedBy("mRestrictionsLock")
284 private final SparseArray<Bundle> mDevicePolicyLocalUserRestrictions = new SparseArray<>();
285
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800286 @GuardedBy("mGuestRestrictions")
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530287 private final Bundle mGuestRestrictions = new Bundle();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800288
289 /**
290 * Set of user IDs being actively removed. Removed IDs linger in this set
291 * for several seconds to work around a VFS caching issue.
292 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700293 @GuardedBy("mUsersLock")
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800294 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700295
Fyodor Kupolov82402752015-10-28 14:54:51 -0700296 @GuardedBy("mUsersLock")
Amith Yamasani0b285492011-04-14 17:35:23 -0700297 private int[] mUserIds;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800298 @GuardedBy("mPackagesLock")
Amith Yamasani2a003292012-08-14 18:25:45 -0700299 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700300 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700301
Jason Monk62062992014-05-06 09:55:28 -0400302 private IAppOpsService mAppOpsService;
303
Makoto Onuki068c54a2015-10-13 14:34:03 -0700304 private final LocalService mLocalService;
305
Makoto Onukie7927da2015-11-25 10:05:17 -0800306 @GuardedBy("mUsersLock")
307 private boolean mIsDeviceManaged;
308
309 @GuardedBy("mUsersLock")
310 private final SparseBooleanArray mIsUserManaged = new SparseBooleanArray();
311
Makoto Onukid45a4a22015-11-02 17:17:38 -0800312 @GuardedBy("mUserRestrictionsListeners")
313 private final ArrayList<UserRestrictionsListener> mUserRestrictionsListeners =
314 new ArrayList<>();
315
Clara Bayarria1771112015-12-18 16:29:18 +0000316 private final LockPatternUtils mLockPatternUtils;
317
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +0100318 /**
319 * Whether all users should be created ephemeral.
320 */
321 @GuardedBy("mUsersLock")
322 private boolean mForceEphemeralUsers;
323
Amith Yamasani258848d2012-08-10 17:06:33 -0700324 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700325
Dianne Hackborn4428e172012-08-24 17:43:05 -0700326 public static UserManagerService getInstance() {
327 synchronized (UserManagerService.class) {
328 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700329 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700330 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700331
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800332 @VisibleForTesting
333 UserManagerService(File dataDir) {
334 this(null, null, new Object(), dataDir);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700335 }
336
Dianne Hackborn4428e172012-08-24 17:43:05 -0700337 /**
338 * Called by package manager to create the service. This is closely
339 * associated with the package manager, and the given lock is the
340 * package manager's own lock.
341 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800342 UserManagerService(Context context, PackageManagerService pm, Object packagesLock) {
343 this(context, pm, packagesLock, Environment.getDataDirectory());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700344 }
345
Dianne Hackborn4428e172012-08-24 17:43:05 -0700346 private UserManagerService(Context context, PackageManagerService pm,
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800347 Object packagesLock, File dataDir) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700348 mContext = context;
349 mPm = pm;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700350 mPackagesLock = packagesLock;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800351 mHandler = new MainHandler();
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800352 synchronized (mPackagesLock) {
353 mUsersDir = new File(dataDir, USER_INFO_DIR);
354 mUsersDir.mkdirs();
355 // Make zeroth user directory, for services to migrate their files to that location
356 File userZeroDir = new File(mUsersDir, String.valueOf(UserHandle.USER_SYSTEM));
357 userZeroDir.mkdirs();
358 FileUtils.setPermissions(mUsersDir.toString(),
359 FileUtils.S_IRWXU | FileUtils.S_IRWXG | FileUtils.S_IROTH | FileUtils.S_IXOTH,
360 -1, -1);
361 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
362 initDefaultGuestRestrictions();
363 readUserListLP();
364 sInstance = this;
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700365 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700366 mLocalService = new LocalService();
367 LocalServices.addService(UserManagerInternal.class, mLocalService);
Clara Bayarria1771112015-12-18 16:29:18 +0000368 mLockPatternUtils = new LockPatternUtils(mContext);
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700369 }
370
371 void systemReady() {
Lenka Trochtovac4dd0212015-11-18 12:22:06 +0100372 // Prune out any partially created, partially removed and ephemeral users.
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800373 ArrayList<UserInfo> partials = new ArrayList<>();
374 synchronized (mUsersLock) {
375 final int userSize = mUsers.size();
376 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800377 UserInfo ui = mUsers.valueAt(i).info;
Lenka Trochtovac4dd0212015-11-18 12:22:06 +0100378 if ((ui.partial || ui.guestToRemove || ui.isEphemeral()) && i != 0) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800379 partials.add(ui);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700380 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700381 }
Dianne Hackborn4428e172012-08-24 17:43:05 -0700382 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800383 final int partialsSize = partials.size();
384 for (int i = 0; i < partialsSize; i++) {
385 UserInfo ui = partials.get(i);
386 Slog.w(LOG_TAG, "Removing partially created user " + ui.id
387 + " (name=" + ui.name + ")");
388 removeUserState(ui.id);
389 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800390
Jason Monk62062992014-05-06 09:55:28 -0400391 mAppOpsService = IAppOpsService.Stub.asInterface(
392 ServiceManager.getService(Context.APP_OPS_SERVICE));
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800393
394 synchronized (mRestrictionsLock) {
395 applyUserRestrictionsLR(UserHandle.USER_SYSTEM);
Jason Monk62062992014-05-06 09:55:28 -0400396 }
Samuel Tand9453b82016-03-14 15:57:02 -0700397
398 UserInfo currentGuestUser = findCurrentGuestUser();
399 if (currentGuestUser != null && !hasUserRestriction(
400 UserManager.DISALLOW_CONFIG_WIFI, currentGuestUser.id)) {
401 // If a guest user currently exists, apply the DISALLOW_CONFIG_WIFI option
402 // to it, in case this guest was created in a previous version where this
403 // user restriction was not a default guest restriction.
404 setUserRestriction(UserManager.DISALLOW_CONFIG_WIFI, true, currentGuestUser.id);
405 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700406 }
407
408 @Override
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800409 public String getUserAccount(int userId) {
410 checkManageUserAndAcrossUsersFullPermission("get user account");
411 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800412 return mUsers.get(userId).account;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800413 }
414 }
415
416 @Override
417 public void setUserAccount(int userId, String accountName) {
418 checkManageUserAndAcrossUsersFullPermission("set user account");
Amith Yamasani12747872015-12-07 14:19:49 -0800419 UserData userToUpdate = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800420 synchronized (mPackagesLock) {
421 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800422 final UserData userData = mUsers.get(userId);
423 if (userData == null) {
424 Slog.e(LOG_TAG, "User not found for setting user account: u" + userId);
425 return;
426 }
427 String currentAccount = userData.account;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800428 if (!Objects.equal(currentAccount, accountName)) {
Amith Yamasani12747872015-12-07 14:19:49 -0800429 userData.account = accountName;
430 userToUpdate = userData;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800431 }
432 }
433
434 if (userToUpdate != null) {
435 writeUserLP(userToUpdate);
436 }
437 }
438 }
439
440 @Override
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700441 public UserInfo getPrimaryUser() {
442 checkManageUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700443 synchronized (mUsersLock) {
Amith Yamasani515d4062015-09-28 11:30:06 -0700444 final int userSize = mUsers.size();
445 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800446 UserInfo ui = mUsers.valueAt(i).info;
Xiaohui Chend3e9e182015-11-18 13:37:32 -0800447 if (ui.isPrimary() && !mRemovingUserIds.get(ui.id)) {
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700448 return ui;
449 }
450 }
451 }
452 return null;
453 }
454
455 @Override
Xiaohui Chen594f2082015-08-18 11:04:20 -0700456 public @NonNull List<UserInfo> getUsers(boolean excludeDying) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700457 checkManageUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700458 synchronized (mUsersLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700459 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasani515d4062015-09-28 11:30:06 -0700460 final int userSize = mUsers.size();
461 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800462 UserInfo ui = mUsers.valueAt(i).info;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700463 if (ui.partial) {
464 continue;
465 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800466 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Amith Yamasani6f48d6e2016-03-23 14:28:25 -0700467 users.add(userWithName(ui));
Amith Yamasani920ace02012-09-20 22:15:37 -0700468 }
Amith Yamasani13593602012-03-22 16:16:17 -0700469 }
470 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700471 }
Amith Yamasani13593602012-03-22 16:16:17 -0700472 }
473
Amith Yamasani258848d2012-08-10 17:06:33 -0700474 @Override
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100475 public List<UserInfo> getProfiles(int userId, boolean enabledOnly) {
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700476 boolean returnFullInfo = true;
Amith Yamasani4f582632014-02-19 14:31:52 -0800477 if (userId != UserHandle.getCallingUserId()) {
478 checkManageUsersPermission("getting profiles related to user " + userId);
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700479 } else {
480 returnFullInfo = hasManageUsersPermission();
Amith Yamasani4f582632014-02-19 14:31:52 -0800481 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700482 final long ident = Binder.clearCallingIdentity();
483 try {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700484 synchronized (mUsersLock) {
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700485 return getProfilesLU(userId, enabledOnly, returnFullInfo);
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100486 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700487 } finally {
488 Binder.restoreCallingIdentity(ident);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000489 }
490 }
491
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700492 @Override
493 public int[] getProfileIds(int userId, boolean enabledOnly) {
494 if (userId != UserHandle.getCallingUserId()) {
495 checkManageUsersPermission("getting profiles related to user " + userId);
496 }
497 final long ident = Binder.clearCallingIdentity();
498 try {
499 synchronized (mUsersLock) {
500 return getProfileIdsLU(userId, enabledOnly).toArray();
501 }
502 } finally {
503 Binder.restoreCallingIdentity(ident);
504 }
505 }
506
Amith Yamasanibe465322014-04-24 13:45:17 -0700507 /** Assume permissions already checked and caller's identity cleared */
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700508 private List<UserInfo> getProfilesLU(int userId, boolean enabledOnly, boolean fullInfo) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700509 IntArray profileIds = getProfileIdsLU(userId, enabledOnly);
510 ArrayList<UserInfo> users = new ArrayList<>(profileIds.size());
511 for (int i = 0; i < profileIds.size(); i++) {
512 int profileId = profileIds.get(i);
513 UserInfo userInfo = mUsers.get(profileId).info;
514 // If full info is not required - clear PII data to prevent 3P apps from reading it
515 if (!fullInfo) {
516 userInfo = new UserInfo(userInfo);
517 userInfo.name = null;
518 userInfo.iconPath = null;
519 } else {
520 userInfo = userWithName(userInfo);
521 }
522 users.add(userInfo);
523 }
524 return users;
525 }
526
527 /**
528 * Assume permissions already checked and caller's identity cleared
529 */
530 private IntArray getProfileIdsLU(int userId, boolean enabledOnly) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700531 UserInfo user = getUserInfoLU(userId);
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700532 IntArray result = new IntArray(mUsers.size());
Amith Yamasanidda003f2014-08-28 18:06:51 -0700533 if (user == null) {
534 // Probably a dying user
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700535 return result;
Amith Yamasanidda003f2014-08-28 18:06:51 -0700536 }
Amith Yamasani515d4062015-09-28 11:30:06 -0700537 final int userSize = mUsers.size();
538 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800539 UserInfo profile = mUsers.valueAt(i).info;
Amith Yamasanibe465322014-04-24 13:45:17 -0700540 if (!isProfileOf(user, profile)) {
541 continue;
542 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100543 if (enabledOnly && !profile.isEnabled()) {
544 continue;
Amith Yamasanibe465322014-04-24 13:45:17 -0700545 }
Amith Yamasani70fcf0c2014-07-11 08:40:19 -0700546 if (mRemovingUserIds.get(profile.id)) {
547 continue;
548 }
Tony Mak80189cd2016-04-05 17:21:42 +0100549 if (profile.partial) {
550 continue;
551 }
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700552 result.add(profile.id);
Amith Yamasanibe465322014-04-24 13:45:17 -0700553 }
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700554 return result;
Amith Yamasanibe465322014-04-24 13:45:17 -0700555 }
556
Jessica Hummelbe81c802014-04-22 15:49:22 +0100557 @Override
Andres Moralesc5548c02015-08-05 10:23:12 -0700558 public int getCredentialOwnerProfile(int userHandle) {
559 checkManageUsersPermission("get the credential owner");
Clara Bayarria1771112015-12-18 16:29:18 +0000560 if (!mLockPatternUtils.isSeparateProfileChallengeEnabled(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700561 synchronized (mUsersLock) {
562 UserInfo profileParent = getProfileParentLU(userHandle);
Andres Moralesc5548c02015-08-05 10:23:12 -0700563 if (profileParent != null) {
564 return profileParent.id;
565 }
566 }
567 }
568
569 return userHandle;
570 }
571
572 @Override
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700573 public boolean isSameProfileGroup(int userId, int otherUserId) {
574 if (userId == otherUserId) return true;
575 checkManageUsersPermission("check if in the same profile group");
576 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700577 return isSameProfileGroupLP(userId, otherUserId);
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700578 }
579 }
580
Fyodor Kupolov82402752015-10-28 14:54:51 -0700581 private boolean isSameProfileGroupLP(int userId, int otherUserId) {
582 synchronized (mUsersLock) {
583 UserInfo userInfo = getUserInfoLU(userId);
584 if (userInfo == null || userInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
585 return false;
586 }
587 UserInfo otherUserInfo = getUserInfoLU(otherUserId);
588 if (otherUserInfo == null
589 || otherUserInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
590 return false;
591 }
592 return userInfo.profileGroupId == otherUserInfo.profileGroupId;
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700593 }
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700594 }
595
596 @Override
Jessica Hummelbe81c802014-04-22 15:49:22 +0100597 public UserInfo getProfileParent(int userHandle) {
598 checkManageUsersPermission("get the profile parent");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700599 synchronized (mUsersLock) {
600 return getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700601 }
602 }
603
Fyodor Kupolov82402752015-10-28 14:54:51 -0700604 private UserInfo getProfileParentLU(int userHandle) {
605 UserInfo profile = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700606 if (profile == null) {
607 return null;
608 }
609 int parentUserId = profile.profileGroupId;
610 if (parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
611 return null;
612 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700613 return getUserInfoLU(parentUserId);
Jessica Hummelbe81c802014-04-22 15:49:22 +0100614 }
615 }
616
Fyodor Kupolov82402752015-10-28 14:54:51 -0700617 private static boolean isProfileOf(UserInfo user, UserInfo profile) {
Kenny Guy2a764942014-04-02 13:29:20 +0100618 return user.id == profile.id ||
619 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
620 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000621 }
622
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000623 private void broadcastProfileAvailabilityChanges(UserHandle profileHandle,
Rubin Xuf13c9802016-01-21 18:06:00 +0000624 UserHandle parentHandle, boolean inQuietMode) {
Rubin Xue95057a2016-04-01 16:49:25 +0100625 Intent intent = new Intent();
626 if (inQuietMode) {
627 intent.setAction(Intent.ACTION_MANAGED_PROFILE_UNAVAILABLE);
628 } else {
629 intent.setAction(Intent.ACTION_MANAGED_PROFILE_AVAILABLE);
630 }
Rubin Xuf13c9802016-01-21 18:06:00 +0000631 intent.putExtra(Intent.EXTRA_QUIET_MODE, inQuietMode);
632 intent.putExtra(Intent.EXTRA_USER, profileHandle);
633 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileHandle.getIdentifier());
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000634 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Rubin Xuf13c9802016-01-21 18:06:00 +0000635 mContext.sendBroadcastAsUser(intent, parentHandle);
Rubin Xue95057a2016-04-01 16:49:25 +0100636
637 //TODO: remove once Launcher3 is updated.
638 Intent oldIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_AVAILABILITY_CHANGED);
639 oldIntent.putExtra(Intent.EXTRA_QUIET_MODE, inQuietMode);
640 oldIntent.putExtra(Intent.EXTRA_USER, profileHandle);
641 oldIntent.putExtra(Intent.EXTRA_USER_HANDLE, profileHandle.getIdentifier());
642 oldIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
643 mContext.sendBroadcastAsUser(oldIntent, parentHandle);
644
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000645 }
646
647 @Override
648 public void setQuietModeEnabled(int userHandle, boolean enableQuietMode) {
649 checkManageUsersPermission("silence profile");
650 boolean changed = false;
651 UserInfo profile, parent;
652 synchronized (mPackagesLock) {
653 synchronized (mUsersLock) {
654 profile = getUserInfoLU(userHandle);
655 parent = getProfileParentLU(userHandle);
656
657 }
658 if (profile == null || !profile.isManagedProfile()) {
659 throw new IllegalArgumentException("User " + userHandle + " is not a profile");
660 }
661 if (profile.isQuietModeEnabled() != enableQuietMode) {
662 profile.flags ^= UserInfo.FLAG_QUIET_MODE;
Amith Yamasani12747872015-12-07 14:19:49 -0800663 writeUserLP(getUserDataLU(profile.id));
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000664 changed = true;
665 }
666 }
667 if (changed) {
Rubin Xuf13c9802016-01-21 18:06:00 +0000668 long identity = Binder.clearCallingIdentity();
669 try {
670 if (enableQuietMode) {
671 ActivityManagerNative.getDefault().stopUser(userHandle, /* force */true, null);
672 } else {
673 ActivityManagerNative.getDefault().startUserInBackground(userHandle);
674 }
675 } catch (RemoteException e) {
676 Slog.e(LOG_TAG, "fail to start/stop user for quiet mode", e);
677 } finally {
678 Binder.restoreCallingIdentity(identity);
679 }
680
681 broadcastProfileAvailabilityChanges(profile.getUserHandle(), parent.getUserHandle(),
682 enableQuietMode);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000683 }
684 }
685
686 @Override
687 public boolean isQuietModeEnabled(int userHandle) {
688 synchronized (mPackagesLock) {
689 UserInfo info;
690 synchronized (mUsersLock) {
691 info = getUserInfoLU(userHandle);
692 }
693 if (info == null || !info.isManagedProfile()) {
Rubin Xuf13c9802016-01-21 18:06:00 +0000694 return false;
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000695 }
696 return info.isQuietModeEnabled();
697 }
698 }
699
Kenny Guya52dc3e2014-02-11 15:33:14 +0000700 @Override
Benjamin Franzf02420c2016-04-04 18:52:21 +0100701 public boolean trySetQuietModeDisabled(int userHandle, IntentSender target) {
702 if (mContext.getSystemService(StorageManager.class).isUserKeyUnlocked(userHandle)
703 || !mLockPatternUtils.isSecure(userHandle)
704 || !mLockPatternUtils.isSeparateProfileChallengeEnabled(userHandle)) {
705 // if the user is already unlocked, no need to show a profile challenge
706 setQuietModeEnabled(userHandle, false);
707 return true;
708 }
709
710 long identity = Binder.clearCallingIdentity();
711 try {
712 // otherwise, we show a profile challenge to trigger decryption of the user
713 final KeyguardManager km = (KeyguardManager) mContext.getSystemService(
714 Context.KEYGUARD_SERVICE);
715 final Intent unlockIntent = km.createConfirmDeviceCredentialIntent(null, null,
716 userHandle);
717 if (unlockIntent == null) {
718 return false;
719 }
720 if (target != null) {
721 unlockIntent.putExtra(Intent.EXTRA_INTENT, target);
722 }
723 unlockIntent.setFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
724 mContext.startActivity(unlockIntent);
725 } finally {
726 Binder.restoreCallingIdentity(identity);
727 }
728 return false;
729 }
730
731 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100732 public void setUserEnabled(int userId) {
733 checkManageUsersPermission("enable user");
734 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700735 UserInfo info;
736 synchronized (mUsersLock) {
737 info = getUserInfoLU(userId);
738 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100739 if (info != null && !info.isEnabled()) {
740 info.flags ^= UserInfo.FLAG_DISABLED;
Amith Yamasani12747872015-12-07 14:19:49 -0800741 writeUserLP(getUserDataLU(info.id));
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100742 }
743 }
744 }
745
746 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700747 public UserInfo getUserInfo(int userId) {
Tony Mak8673b282016-03-21 21:10:59 +0000748 checkManageUsersPermission("query user");
749 synchronized (mUsersLock) {
Amith Yamasani6f48d6e2016-03-23 14:28:25 -0700750 return userWithName(getUserInfoLU(userId));
751 }
752 }
753
754 /**
755 * Returns a UserInfo object with the name filled in, for Owner, or the original
756 * if the name is already set.
757 */
758 private UserInfo userWithName(UserInfo orig) {
759 if (orig != null && orig.name == null && orig.id == UserHandle.USER_SYSTEM) {
760 UserInfo withName = new UserInfo(orig);
761 withName.name = getOwnerName();
762 return withName;
763 } else {
764 return orig;
Tony Mak8673b282016-03-21 21:10:59 +0000765 }
766 }
767
768 @Override
769 public boolean isManagedProfile(int userId) {
Tony Makb531d082016-03-16 14:49:52 +0000770 int callingUserId = UserHandle.getCallingUserId();
771 if (callingUserId != userId && !hasManageUsersPermission()) {
772 synchronized (mPackagesLock) {
773 if (!isSameProfileGroupLP(callingUserId, userId)) {
774 throw new SecurityException(
Tony Mak8673b282016-03-21 21:10:59 +0000775 "You need MANAGE_USERS permission to: check if specified user a " +
776 "managed profile outside your profile group");
Tony Makb531d082016-03-16 14:49:52 +0000777 }
778 }
Tony Mak4dc008c2016-03-16 10:46:49 +0000779 }
Fyodor Kupolov82402752015-10-28 14:54:51 -0700780 synchronized (mUsersLock) {
Tony Mak8673b282016-03-21 21:10:59 +0000781 UserInfo userInfo = getUserInfoLU(userId);
782 return userInfo != null && userInfo.isManagedProfile();
Amith Yamasani13593602012-03-22 16:16:17 -0700783 }
784 }
785
Amith Yamasani71e6c692013-03-24 17:39:28 -0700786 @Override
787 public boolean isRestricted() {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700788 synchronized (mUsersLock) {
789 return getUserInfoLU(UserHandle.getCallingUserId()).isRestricted();
Amith Yamasani71e6c692013-03-24 17:39:28 -0700790 }
791 }
792
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700793 @Override
794 public boolean canHaveRestrictedProfile(int userId) {
795 checkManageUsersPermission("canHaveRestrictedProfile");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700796 synchronized (mUsersLock) {
797 final UserInfo userInfo = getUserInfoLU(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700798 if (userInfo == null || !userInfo.canHaveProfile()) {
799 return false;
800 }
801 if (!userInfo.isAdmin()) {
802 return false;
803 }
Makoto Onukie7927da2015-11-25 10:05:17 -0800804 // restricted profile can be created if there is no DO set and the admin user has no PO;
805 return !mIsDeviceManaged && !mIsUserManaged.get(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700806 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700807 }
808
Amith Yamasani195263742012-08-21 15:40:12 -0700809 /*
810 * Should be locked on mUsers before calling this.
811 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700812 private UserInfo getUserInfoLU(int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -0800813 final UserData userData = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -0700814 // If it is partial and not in the process of being removed, return as unknown user.
Amith Yamasani12747872015-12-07 14:19:49 -0800815 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700816 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
817 return null;
818 }
Amith Yamasani12747872015-12-07 14:19:49 -0800819 return userData != null ? userData.info : null;
820 }
821
822 private UserData getUserDataLU(int userId) {
823 final UserData userData = mUsers.get(userId);
824 // If it is partial and not in the process of being removed, return as unknown user.
825 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
826 return null;
827 }
828 return userData;
Amith Yamasani195263742012-08-21 15:40:12 -0700829 }
830
Fyodor Kupolov82402752015-10-28 14:54:51 -0700831 /**
832 * Obtains {@link #mUsersLock} and return UserInfo from mUsers.
833 * <p>No permissions checking or any addition checks are made</p>
834 */
835 private UserInfo getUserInfoNoChecks(int userId) {
836 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800837 final UserData userData = mUsers.get(userId);
838 return userData != null ? userData.info : null;
839 }
840 }
841
842 /**
843 * Obtains {@link #mUsersLock} and return UserData from mUsers.
844 * <p>No permissions checking or any addition checks are made</p>
845 */
846 private UserData getUserDataNoChecks(int userId) {
847 synchronized (mUsersLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700848 return mUsers.get(userId);
849 }
850 }
851
Amith Yamasani236b2b52015-08-18 14:32:14 -0700852 /** Called by PackageManagerService */
Amith Yamasani13593602012-03-22 16:16:17 -0700853 public boolean exists(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700854 return getUserInfoNoChecks(userId) != null;
Amith Yamasani13593602012-03-22 16:16:17 -0700855 }
856
Amith Yamasani258848d2012-08-10 17:06:33 -0700857 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700858 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700859 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700860 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700861 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800862 UserData userData = getUserDataNoChecks(userId);
863 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700864 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
865 return;
866 }
Amith Yamasani12747872015-12-07 14:19:49 -0800867 if (name != null && !name.equals(userData.info.name)) {
868 userData.info.name = name;
869 writeUserLP(userData);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700870 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -0700871 }
872 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700873 if (changed) {
874 sendUserInfoChangedBroadcast(userId);
875 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700876 }
877
Amith Yamasani258848d2012-08-10 17:06:33 -0700878 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700879 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700880 checkManageUsersPermission("update users");
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +0100881 if (hasUserRestriction(UserManager.DISALLOW_SET_USER_ICON, userId)) {
882 Log.w(LOG_TAG, "Cannot set user icon. DISALLOW_SET_USER_ICON is enabled.");
883 return;
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700884 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +0100885 mLocalService.setUserIcon(userId, bitmap);
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700886 }
887
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +0100888
889
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700890 private void sendUserInfoChangedBroadcast(int userId) {
891 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
892 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
893 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -0700894 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700895 }
896
Amith Yamasani258848d2012-08-10 17:06:33 -0700897 @Override
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +0100898 public ParcelFileDescriptor getUserIcon(int targetUserId) {
Adrian Roos1bdff912015-02-17 15:51:35 +0100899 String iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700900 synchronized (mPackagesLock) {
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +0100901 UserInfo targetUserInfo = getUserInfoNoChecks(targetUserId);
902 if (targetUserInfo == null || targetUserInfo.partial) {
903 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + targetUserId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700904 return null;
905 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +0100906
907 final int callingUserId = UserHandle.getCallingUserId();
908 final int callingGroupId = getUserInfoNoChecks(callingUserId).profileGroupId;
909 final int targetGroupId = targetUserInfo.profileGroupId;
910 final boolean sameGroup = (callingGroupId != UserInfo.NO_PROFILE_GROUP_ID
911 && callingGroupId == targetGroupId);
912 if ((callingUserId != targetUserId) && !sameGroup) {
Nicolas Prevot88cc3462014-05-14 14:51:48 +0100913 checkManageUsersPermission("get the icon of a user who is not related");
914 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +0100915
916 if (targetUserInfo.iconPath == null) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700917 return null;
918 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +0100919 iconPath = targetUserInfo.iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700920 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100921
922 try {
923 return ParcelFileDescriptor.open(
924 new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
925 } catch (FileNotFoundException e) {
926 Log.e(LOG_TAG, "Couldn't find icon file", e);
927 }
928 return null;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700929 }
930
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700931 public void makeInitialized(int userId) {
932 checkManageUsersPermission("makeInitialized");
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800933 boolean scheduleWriteUser = false;
Amith Yamasani12747872015-12-07 14:19:49 -0800934 UserData userData;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800935 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800936 userData = mUsers.get(userId);
937 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700938 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800939 return;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700940 }
Amith Yamasani12747872015-12-07 14:19:49 -0800941 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
942 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800943 scheduleWriteUser = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700944 }
945 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800946 if (scheduleWriteUser) {
Amith Yamasani12747872015-12-07 14:19:49 -0800947 scheduleWriteUser(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800948 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700949 }
950
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700951 /**
952 * If default guest restrictions haven't been initialized yet, add the basic
953 * restrictions.
954 */
955 private void initDefaultGuestRestrictions() {
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800956 synchronized (mGuestRestrictions) {
957 if (mGuestRestrictions.isEmpty()) {
Samuel Tand9453b82016-03-14 15:57:02 -0700958 mGuestRestrictions.putBoolean(UserManager.DISALLOW_CONFIG_WIFI, true);
Fyodor Kupolove04462c2015-11-30 15:02:53 -0800959 mGuestRestrictions.putBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, true);
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800960 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
961 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
962 }
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700963 }
964 }
965
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800966 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530967 public Bundle getDefaultGuestRestrictions() {
968 checkManageUsersPermission("getDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800969 synchronized (mGuestRestrictions) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530970 return new Bundle(mGuestRestrictions);
971 }
972 }
973
974 @Override
975 public void setDefaultGuestRestrictions(Bundle restrictions) {
976 checkManageUsersPermission("setDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800977 synchronized (mGuestRestrictions) {
978 mGuestRestrictions.clear();
979 mGuestRestrictions.putAll(restrictions);
980 }
981 synchronized (mPackagesLock) {
982 writeUserListLP();
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530983 }
984 }
985
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800986 /**
987 * See {@link UserManagerInternal#setDevicePolicyUserRestrictions(int, Bundle, Bundle)}
988 */
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800989 void setDevicePolicyUserRestrictionsInner(int userId, @NonNull Bundle local,
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800990 @Nullable Bundle global) {
991 Preconditions.checkNotNull(local);
992 boolean globalChanged = false;
993 boolean localChanged;
994 synchronized (mRestrictionsLock) {
995 if (global != null) {
996 // Update global.
997 globalChanged = !UserRestrictionsUtils.areEqual(
998 mDevicePolicyGlobalUserRestrictions, global);
999 if (globalChanged) {
1000 mDevicePolicyGlobalUserRestrictions = global;
1001 }
1002 }
1003 {
1004 // Update local.
1005 final Bundle prev = mDevicePolicyLocalUserRestrictions.get(userId);
1006 localChanged = !UserRestrictionsUtils.areEqual(prev, local);
1007 if (localChanged) {
1008 mDevicePolicyLocalUserRestrictions.put(userId, local);
1009 }
1010 }
1011 }
1012 if (DBG) {
1013 Log.d(LOG_TAG, "setDevicePolicyUserRestrictions: userId=" + userId
1014 + " global=" + global + (globalChanged ? " (changed)" : "")
1015 + " local=" + local + (localChanged ? " (changed)" : "")
1016 );
1017 }
1018 // Don't call them within the mRestrictionsLock.
1019 synchronized (mPackagesLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001020 if (localChanged) {
Amith Yamasani12747872015-12-07 14:19:49 -08001021 writeUserLP(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001022 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06001023 if (globalChanged) {
1024 writeUserListLP();
1025 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001026 }
1027
1028 synchronized (mRestrictionsLock) {
1029 if (globalChanged) {
1030 applyUserRestrictionsForAllUsersLR();
1031 } else if (localChanged) {
1032 applyUserRestrictionsLR(userId);
1033 }
1034 }
1035 }
1036
Makoto Onuki068c54a2015-10-13 14:34:03 -07001037 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001038 private Bundle computeEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001039 final Bundle baseRestrictions =
1040 UserRestrictionsUtils.nonNull(mBaseUserRestrictions.get(userId));
1041 final Bundle global = mDevicePolicyGlobalUserRestrictions;
1042 final Bundle local = mDevicePolicyLocalUserRestrictions.get(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001043
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001044 if (UserRestrictionsUtils.isEmpty(global) && UserRestrictionsUtils.isEmpty(local)) {
1045 // Common case first.
1046 return baseRestrictions;
Makoto Onuki068c54a2015-10-13 14:34:03 -07001047 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001048 final Bundle effective = UserRestrictionsUtils.clone(baseRestrictions);
1049 UserRestrictionsUtils.merge(effective, global);
1050 UserRestrictionsUtils.merge(effective, local);
1051
Makoto Onuki068c54a2015-10-13 14:34:03 -07001052 return effective;
1053 }
1054
1055 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001056 private void invalidateEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki068c54a2015-10-13 14:34:03 -07001057 if (DBG) {
1058 Log.d(LOG_TAG, "invalidateEffectiveUserRestrictions userId=" + userId);
1059 }
1060 mCachedEffectiveUserRestrictions.remove(userId);
1061 }
1062
1063 private Bundle getEffectiveUserRestrictions(int userId) {
1064 synchronized (mRestrictionsLock) {
1065 Bundle restrictions = mCachedEffectiveUserRestrictions.get(userId);
1066 if (restrictions == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001067 restrictions = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001068 mCachedEffectiveUserRestrictions.put(userId, restrictions);
1069 }
1070 return restrictions;
Amith Yamasani8cd28b52014-06-08 17:54:27 -07001071 }
1072 }
1073
Makoto Onuki068c54a2015-10-13 14:34:03 -07001074 /** @return a specific user restriction that's in effect currently. */
1075 @Override
1076 public boolean hasUserRestriction(String restrictionKey, int userId) {
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001077 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1078 return false;
1079 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001080 Bundle restrictions = getEffectiveUserRestrictions(userId);
1081 return restrictions != null && restrictions.getBoolean(restrictionKey);
1082 }
1083
1084 /**
1085 * @return UserRestrictions that are in effect currently. This always returns a new
1086 * {@link Bundle}.
1087 */
Amith Yamasani8cd28b52014-06-08 17:54:27 -07001088 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001089 public Bundle getUserRestrictions(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001090 return UserRestrictionsUtils.clone(getEffectiveUserRestrictions(userId));
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001091 }
1092
1093 @Override
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +00001094 public boolean hasBaseUserRestriction(String restrictionKey, int userId) {
1095 checkManageUsersPermission("hasBaseUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001096 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1097 return false;
1098 }
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +00001099 synchronized (mRestrictionsLock) {
1100 Bundle bundle = mBaseUserRestrictions.get(userId);
1101 return (bundle != null && bundle.getBoolean(restrictionKey, false));
1102 }
1103 }
1104
1105 @Override
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001106 public void setUserRestriction(String key, boolean value, int userId) {
Fyodor Kupolovd4b26042015-07-27 14:30:59 -07001107 checkManageUsersPermission("setUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001108 if (!UserRestrictionsUtils.isValidRestriction(key)) {
1109 return;
1110 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001111 synchronized (mRestrictionsLock) {
1112 // Note we can't modify Bundles stored in mBaseUserRestrictions directly, so create
1113 // a copy.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001114 final Bundle newRestrictions = UserRestrictionsUtils.clone(
1115 mBaseUserRestrictions.get(userId));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001116 newRestrictions.putBoolean(key, value);
1117
Fyodor Kupolov82402752015-10-28 14:54:51 -07001118 updateUserRestrictionsInternalLR(newRestrictions, userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001119 }
1120 }
1121
Makoto Onuki068c54a2015-10-13 14:34:03 -07001122 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001123 * Optionally updating user restrictions, calculate the effective user restrictions and also
1124 * propagate to other services and system settings.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001125 *
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001126 * @param newRestrictions User restrictions to set.
1127 * If null, will not update user restrictions and only does the propagation.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001128 * @param userId target user ID.
1129 */
1130 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001131 private void updateUserRestrictionsInternalLR(
Makoto Onuki068c54a2015-10-13 14:34:03 -07001132 @Nullable Bundle newRestrictions, int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001133
1134 final Bundle prevAppliedRestrictions = UserRestrictionsUtils.nonNull(
1135 mAppliedUserRestrictions.get(userId));
1136
1137 // Update base restrictions.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001138 if (newRestrictions != null) {
1139 // If newRestrictions == the current one, it's probably a bug.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001140 final Bundle prevBaseRestrictions = mBaseUserRestrictions.get(userId);
1141
1142 Preconditions.checkState(prevBaseRestrictions != newRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001143 Preconditions.checkState(mCachedEffectiveUserRestrictions.get(userId)
1144 != newRestrictions);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001145
1146 if (!UserRestrictionsUtils.areEqual(prevBaseRestrictions, newRestrictions)) {
1147 mBaseUserRestrictions.put(userId, newRestrictions);
Amith Yamasani12747872015-12-07 14:19:49 -08001148 scheduleWriteUser(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001149 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001150 }
1151
Fyodor Kupolov82402752015-10-28 14:54:51 -07001152 final Bundle effective = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001153
Makoto Onuki759a7632015-10-28 16:43:10 -07001154 mCachedEffectiveUserRestrictions.put(userId, effective);
1155
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001156 // Apply the new restrictions.
Makoto Onuki4f160732015-10-27 17:15:38 -07001157 if (DBG) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001158 debug("Applying user restrictions: userId=" + userId
1159 + " new=" + effective + " prev=" + prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001160 }
1161
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001162 if (mAppOpsService != null) { // We skip it until system-ready.
1163 final long token = Binder.clearCallingIdentity();
1164 try {
Svet Ganov9cea80cd2016-02-16 11:47:00 -08001165 mAppOpsService.setUserRestrictions(effective, mUserRestriconToken, userId);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001166 } catch (RemoteException e) {
1167 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
1168 } finally {
1169 Binder.restoreCallingIdentity(token);
1170 }
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001171 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001172
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001173 propagateUserRestrictionsLR(userId, effective, prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001174
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001175 mAppliedUserRestrictions.put(userId, new Bundle(effective));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001176 }
1177
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001178 private void propagateUserRestrictionsLR(final int userId,
Makoto Onukid45a4a22015-11-02 17:17:38 -08001179 Bundle newRestrictions, Bundle prevRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001180 // Note this method doesn't touch any state, meaning it doesn't require mRestrictionsLock
1181 // actually, but we still need some kind of synchronization otherwise we might end up
1182 // calling listeners out-of-order, thus "LR".
1183
1184 if (UserRestrictionsUtils.areEqual(newRestrictions, prevRestrictions)) {
1185 return;
1186 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08001187
1188 final Bundle newRestrictionsFinal = new Bundle(newRestrictions);
1189 final Bundle prevRestrictionsFinal = new Bundle(prevRestrictions);
1190
1191 mHandler.post(new Runnable() {
1192 @Override
1193 public void run() {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07001194 UserRestrictionsUtils.applyUserRestrictions(
1195 mContext, userId, newRestrictionsFinal, prevRestrictionsFinal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001196
Makoto Onukid45a4a22015-11-02 17:17:38 -08001197 final UserRestrictionsListener[] listeners;
1198 synchronized (mUserRestrictionsListeners) {
1199 listeners = new UserRestrictionsListener[mUserRestrictionsListeners.size()];
1200 mUserRestrictionsListeners.toArray(listeners);
1201 }
1202 for (int i = 0; i < listeners.length; i++) {
1203 listeners[i].onUserRestrictionsChanged(userId,
1204 newRestrictionsFinal, prevRestrictionsFinal);
1205 }
1206 }
1207 });
1208 }
1209
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001210 // Package private for the inner class.
1211 void applyUserRestrictionsLR(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001212 updateUserRestrictionsInternalLR(null, userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001213 }
1214
1215 @GuardedBy("mRestrictionsLock")
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001216 // Package private for the inner class.
1217 void applyUserRestrictionsForAllUsersLR() {
1218 if (DBG) {
1219 debug("applyUserRestrictionsForAllUsersLR");
1220 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001221 // First, invalidate all cached values.
Makoto Onuki4f160732015-10-27 17:15:38 -07001222 mCachedEffectiveUserRestrictions.clear();
1223
Makoto Onuki068c54a2015-10-13 14:34:03 -07001224 // We don't want to call into ActivityManagerNative while taking a lock, so we'll call
1225 // it on a handler.
1226 final Runnable r = new Runnable() {
1227 @Override
1228 public void run() {
1229 // Then get the list of running users.
1230 final int[] runningUsers;
1231 try {
1232 runningUsers = ActivityManagerNative.getDefault().getRunningUserIds();
1233 } catch (RemoteException e) {
1234 Log.w(LOG_TAG, "Unable to access ActivityManagerNative");
1235 return;
1236 }
1237 // Then re-calculate the effective restrictions and apply, only for running users.
1238 // It's okay if a new user has started after the getRunningUserIds() call,
1239 // because we'll do the same thing (re-calculate the restrictions and apply)
1240 // when we start a user.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001241 synchronized (mRestrictionsLock) {
1242 for (int i = 0; i < runningUsers.length; i++) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001243 applyUserRestrictionsLR(runningUsers[i]);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001244 }
1245 }
1246 }
1247 };
1248 mHandler.post(r);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001249 }
1250
Amith Yamasani258848d2012-08-10 17:06:33 -07001251 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001252 * Check if we've hit the limit of how many users can be created.
1253 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001254 private boolean isUserLimitReached() {
1255 int count;
1256 synchronized (mUsersLock) {
1257 count = getAliveUsersExcludingGuestsCountLU();
1258 }
1259 return count >= UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001260 }
1261
1262 @Override
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001263 public boolean canAddMoreManagedProfiles(int userId, boolean allowedToRemoveOne) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001264 checkManageUsersPermission("check if more managed profiles can be added.");
1265 if (ActivityManager.isLowRamDeviceStatic()) {
1266 return false;
1267 }
Fyodor Kupolovb6157992015-06-05 15:32:28 -07001268 if (!mContext.getPackageManager().hasSystemFeature(
1269 PackageManager.FEATURE_MANAGED_USERS)) {
1270 return false;
1271 }
Nicolas Prevotb8186812015-08-06 15:00:03 +01001272 // Limit number of managed profiles that can be created
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001273 final int managedProfilesCount = getProfiles(userId, true).size() - 1;
1274 final int profilesRemovedCount = managedProfilesCount > 0 && allowedToRemoveOne ? 1 : 0;
1275 if (managedProfilesCount - profilesRemovedCount >= MAX_MANAGED_PROFILES) {
Nicolas Prevotb8186812015-08-06 15:00:03 +01001276 return false;
1277 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001278 synchronized(mUsersLock) {
1279 UserInfo userInfo = getUserInfoLU(userId);
Nicolas Prevotb8186812015-08-06 15:00:03 +01001280 if (!userInfo.canHaveProfile()) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001281 return false;
1282 }
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001283 int usersCountAfterRemoving = getAliveUsersExcludingGuestsCountLU()
1284 - profilesRemovedCount;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001285 // We allow creating a managed profile in the special case where there is only one user.
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001286 return usersCountAfterRemoving == 1
1287 || usersCountAfterRemoving < UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001288 }
1289 }
1290
Fyodor Kupolov82402752015-10-28 14:54:51 -07001291 private int getAliveUsersExcludingGuestsCountLU() {
Amith Yamasanif584f012014-05-19 17:57:25 -07001292 int aliveUserCount = 0;
1293 final int totalUserCount = mUsers.size();
1294 // Skip over users being removed
1295 for (int i = 0; i < totalUserCount; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001296 UserInfo user = mUsers.valueAt(i).info;
Amith Yamasani95ab7842014-08-11 17:09:26 -07001297 if (!mRemovingUserIds.get(user.id)
Amith Yamasani1df14732014-08-29 21:37:27 -07001298 && !user.isGuest() && !user.partial) {
Amith Yamasanif584f012014-05-19 17:57:25 -07001299 aliveUserCount++;
1300 }
1301 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001302 return aliveUserCount;
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001303 }
1304
1305 /**
Amith Yamasani195263742012-08-21 15:40:12 -07001306 * Enforces that only the system UID or root's UID or apps that have the
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001307 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} and
1308 * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL INTERACT_ACROSS_USERS_FULL}
1309 * permissions can make certain calls to the UserManager.
1310 *
1311 * @param message used as message if SecurityException is thrown
1312 * @throws SecurityException if the caller does not have enough privilege.
1313 */
1314 private static final void checkManageUserAndAcrossUsersFullPermission(String message) {
1315 final int uid = Binder.getCallingUid();
1316 if (uid != Process.SYSTEM_UID && uid != 0
1317 && ActivityManager.checkComponentPermission(
1318 Manifest.permission.MANAGE_USERS,
1319 uid, -1, true) != PackageManager.PERMISSION_GRANTED
1320 && ActivityManager.checkComponentPermission(
1321 Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1322 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
1323 throw new SecurityException(
1324 "You need MANAGE_USERS and INTERACT_ACROSS_USERS_FULL permission to: "
1325 + message);
1326 }
1327 }
1328
1329 /**
1330 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001331 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -07001332 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -07001333 *
1334 * @param message used as message if SecurityException is thrown
1335 * @throws SecurityException if the caller is not system or root
Tony Mak4dc008c2016-03-16 10:46:49 +00001336 * @see #hasManageUsersPermission()
Amith Yamasani258848d2012-08-10 17:06:33 -07001337 */
Amith Yamasanibe465322014-04-24 13:45:17 -07001338 private static final void checkManageUsersPermission(String message) {
Tony Mak4dc008c2016-03-16 10:46:49 +00001339 if (!hasManageUsersPermission()) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001340 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
1341 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -04001342 }
1343
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001344 /**
Tony Mak4dc008c2016-03-16 10:46:49 +00001345 * @return whether the calling UID is system UID or root's UID or the calling app has the
1346 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}.
1347 */
1348 private static final boolean hasManageUsersPermission() {
1349 final int callingUid = Binder.getCallingUid();
1350 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
1351 || callingUid == Process.ROOT_UID
1352 || ActivityManager.checkComponentPermission(
1353 android.Manifest.permission.MANAGE_USERS,
1354 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED;
1355 }
1356
1357 /**
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001358 * Enforces that only the system UID or root's UID (on any user) can make certain calls to the
1359 * UserManager.
1360 *
1361 * @param message used as message if SecurityException is thrown
1362 * @throws SecurityException if the caller is not system or root
1363 */
1364 private static void checkSystemOrRoot(String message) {
1365 final int uid = Binder.getCallingUid();
1366 if (!UserHandle.isSameApp(uid, Process.SYSTEM_UID) && uid != Process.ROOT_UID) {
1367 throw new SecurityException("Only system may: " + message);
1368 }
1369 }
1370
Fyodor Kupolov82402752015-10-28 14:54:51 -07001371 private void writeBitmapLP(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001372 try {
1373 File dir = new File(mUsersDir, Integer.toString(info.id));
1374 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +01001375 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001376 if (!dir.exists()) {
1377 dir.mkdir();
1378 FileUtils.setPermissions(
1379 dir.getPath(),
1380 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
1381 -1, -1);
1382 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001383 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +01001384 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001385 && tmp.renameTo(file) && SELinux.restorecon(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -07001386 info.iconPath = file.getAbsolutePath();
1387 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001388 try {
1389 os.close();
1390 } catch (IOException ioe) {
1391 // What the ... !
1392 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001393 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001394 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001395 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001396 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001397 }
1398
Amith Yamasani0b285492011-04-14 17:35:23 -07001399 /**
1400 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
1401 * cache it elsewhere.
1402 * @return the array of user ids.
1403 */
Dianne Hackborn1676c852012-09-10 14:52:30 -07001404 public int[] getUserIds() {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001405 synchronized (mUsersLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001406 return mUserIds;
1407 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001408 }
1409
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001410 private void readUserListLP() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001411 if (!mUserListFile.exists()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001412 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001413 return;
1414 }
1415 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001416 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001417 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001418 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001419 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001420 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001421 int type;
1422 while ((type = parser.next()) != XmlPullParser.START_TAG
1423 && type != XmlPullParser.END_DOCUMENT) {
Amith Yamasani12747872015-12-07 14:19:49 -08001424 // Skip
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001425 }
1426
1427 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001428 Slog.e(LOG_TAG, "Unable to read user list");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001429 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001430 return;
1431 }
1432
Amith Yamasani2a003292012-08-14 18:25:45 -07001433 mNextSerialNumber = -1;
1434 if (parser.getName().equals(TAG_USERS)) {
1435 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
1436 if (lastSerialNumber != null) {
1437 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
1438 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001439 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
1440 if (versionNumber != null) {
1441 mUserVersion = Integer.parseInt(versionNumber);
1442 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001443 }
1444
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001445 final Bundle newDevicePolicyGlobalUserRestrictions = new Bundle();
1446
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001447 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301448 if (type == XmlPullParser.START_TAG) {
1449 final String name = parser.getName();
1450 if (name.equals(TAG_USER)) {
1451 String id = parser.getAttributeValue(null, ATTR_ID);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001452
Amith Yamasani12747872015-12-07 14:19:49 -08001453 UserData userData = readUserLP(Integer.parseInt(id));
1454
1455 if (userData != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001456 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001457 mUsers.put(userData.info.id, userData);
1458 if (mNextSerialNumber < 0
1459 || mNextSerialNumber <= userData.info.id) {
1460 mNextSerialNumber = userData.info.id + 1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001461 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301462 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001463 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301464 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -08001465 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1466 && type != XmlPullParser.END_TAG) {
1467 if (type == XmlPullParser.START_TAG) {
1468 if (parser.getName().equals(TAG_RESTRICTIONS)) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001469 synchronized (mGuestRestrictions) {
1470 UserRestrictionsUtils
1471 .readRestrictions(parser, mGuestRestrictions);
1472 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001473 } else if (parser.getName().equals(TAG_DEVICE_POLICY_RESTRICTIONS)
1474 ) {
1475 UserRestrictionsUtils.readRestrictions(parser,
1476 newDevicePolicyGlobalUserRestrictions);
Amith Yamasanida0b1682014-11-21 12:58:17 -08001477 }
1478 break;
1479 }
1480 }
Amith Yamasani258848d2012-08-10 17:06:33 -07001481 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001482 }
1483 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001484 synchronized (mRestrictionsLock) {
1485 mDevicePolicyGlobalUserRestrictions = newDevicePolicyGlobalUserRestrictions;
1486 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001487 updateUserIds();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001488 upgradeIfNecessaryLP();
1489 } catch (IOException | XmlPullParserException e) {
1490 fallbackToSingleUserLP();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001491 } finally {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001492 IoUtils.closeQuietly(fis);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001493 }
1494 }
1495
Amith Yamasani6f34b412012-10-22 18:19:27 -07001496 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -08001497 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -07001498 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001499 private void upgradeIfNecessaryLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001500 final int originalVersion = mUserVersion;
Amith Yamasani6f34b412012-10-22 18:19:27 -07001501 int userVersion = mUserVersion;
1502 if (userVersion < 1) {
1503 // Assign a proper name for the owner, if not initialized correctly before
Amith Yamasani12747872015-12-07 14:19:49 -08001504 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
1505 if ("Primary".equals(userData.info.name)) {
1506 userData.info.name =
1507 mContext.getResources().getString(com.android.internal.R.string.owner_name);
1508 scheduleWriteUser(userData);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001509 }
1510 userVersion = 1;
1511 }
1512
Amith Yamasanibc9625052012-11-15 14:39:18 -08001513 if (userVersion < 2) {
1514 // Owner should be marked as initialized
Amith Yamasani12747872015-12-07 14:19:49 -08001515 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
1516 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1517 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
1518 scheduleWriteUser(userData);
Amith Yamasanibc9625052012-11-15 14:39:18 -08001519 }
1520 userVersion = 2;
1521 }
1522
Amith Yamasani350962c2013-08-06 11:18:53 -07001523
Amith Yamasani5e486f52013-08-07 11:06:44 -07001524 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -07001525 userVersion = 4;
1526 }
1527
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001528 if (userVersion < 5) {
1529 initDefaultGuestRestrictions();
1530 userVersion = 5;
1531 }
1532
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001533 if (userVersion < 6) {
1534 final boolean splitSystemUser = UserManager.isSplitSystemUser();
Fyodor Kupolov82402752015-10-28 14:54:51 -07001535 synchronized (mUsersLock) {
1536 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001537 UserData userData = mUsers.valueAt(i);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001538 // In non-split mode, only user 0 can have restricted profiles
Amith Yamasani12747872015-12-07 14:19:49 -08001539 if (!splitSystemUser && userData.info.isRestricted()
1540 && (userData.info.restrictedProfileParentId
1541 == UserInfo.NO_PROFILE_GROUP_ID)) {
1542 userData.info.restrictedProfileParentId = UserHandle.USER_SYSTEM;
1543 scheduleWriteUser(userData);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001544 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001545 }
1546 }
1547 userVersion = 6;
1548 }
1549
Amith Yamasani6f34b412012-10-22 18:19:27 -07001550 if (userVersion < USER_VERSION) {
1551 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
1552 + USER_VERSION);
1553 } else {
1554 mUserVersion = userVersion;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001555
1556 if (originalVersion < mUserVersion) {
1557 writeUserListLP();
1558 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001559 }
1560 }
1561
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001562 private void fallbackToSingleUserLP() {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001563 int flags = UserInfo.FLAG_INITIALIZED;
1564 // In split system user mode, the admin and primary flags are assigned to the first human
1565 // user.
1566 if (!UserManager.isSplitSystemUser()) {
1567 flags |= UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY;
1568 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001569 // Create the system user
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001570 UserInfo system = new UserInfo(UserHandle.USER_SYSTEM, null, null, flags);
Amith Yamasani12747872015-12-07 14:19:49 -08001571 UserData userData = new UserData();
1572 userData.info = system;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001573 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001574 mUsers.put(system.id, userData);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001575 }
Amith Yamasani634cf312012-10-04 17:34:21 -07001576 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -04001577 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -08001578
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001579 Bundle restrictions = new Bundle();
Makoto Onuki068c54a2015-10-13 14:34:03 -07001580 synchronized (mRestrictionsLock) {
1581 mBaseUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions);
1582 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001583
Fyodor Kupolov82402752015-10-28 14:54:51 -07001584 updateUserIds();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001585 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001586
Amith Yamasani12747872015-12-07 14:19:49 -08001587 writeUserLP(userData);
Jeff Sharkeycd575992016-03-29 14:12:49 -06001588 writeUserListLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001589 }
1590
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001591 private String getOwnerName() {
1592 return mContext.getResources().getString(com.android.internal.R.string.owner_name);
1593 }
1594
Amith Yamasani12747872015-12-07 14:19:49 -08001595 private void scheduleWriteUser(UserData UserData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001596 if (DBG) {
1597 debug("scheduleWriteUser");
1598 }
Makoto Onuki9e935a32015-11-06 14:24:24 -08001599 // No need to wrap it within a lock -- worst case, we'll just post the same message
1600 // twice.
Amith Yamasani12747872015-12-07 14:19:49 -08001601 if (!mHandler.hasMessages(WRITE_USER_MSG, UserData)) {
1602 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, UserData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001603 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
1604 }
1605 }
1606
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001607 /*
1608 * Writes the user file in this format:
1609 *
1610 * <user flags="20039023" id="0">
1611 * <name>Primary</name>
1612 * </user>
1613 */
Amith Yamasani12747872015-12-07 14:19:49 -08001614 private void writeUserLP(UserData userData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001615 if (DBG) {
Amith Yamasani12747872015-12-07 14:19:49 -08001616 debug("writeUserLP " + userData);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001617 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001618 FileOutputStream fos = null;
Amith Yamasani12747872015-12-07 14:19:49 -08001619 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userData.info.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001620 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001621 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001622 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1623
1624 // XmlSerializer serializer = XmlUtils.serializerInstance();
1625 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001626 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001627 serializer.startDocument(null, true);
1628 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1629
Amith Yamasani12747872015-12-07 14:19:49 -08001630 final UserInfo userInfo = userData.info;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001631 serializer.startTag(null, TAG_USER);
1632 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
Amith Yamasani2a003292012-08-14 18:25:45 -07001633 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001634 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Amith Yamasani920ace02012-09-20 22:15:37 -07001635 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
1636 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
1637 Long.toString(userInfo.lastLoggedInTime));
Jeff Sharkeycd575992016-03-29 14:12:49 -06001638 if (userInfo.lastLoggedInFingerprint != null) {
1639 serializer.attribute(null, ATTR_LAST_LOGGED_IN_FINGERPRINT,
1640 userInfo.lastLoggedInFingerprint);
1641 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001642 if (userInfo.iconPath != null) {
1643 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
1644 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001645 if (userInfo.partial) {
1646 serializer.attribute(null, ATTR_PARTIAL, "true");
1647 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001648 if (userInfo.guestToRemove) {
1649 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
1650 }
Kenny Guy2a764942014-04-02 13:29:20 +01001651 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
1652 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
1653 Integer.toString(userInfo.profileGroupId));
Kenny Guya52dc3e2014-02-11 15:33:14 +00001654 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001655 if (userInfo.restrictedProfileParentId != UserInfo.NO_PROFILE_GROUP_ID) {
1656 serializer.attribute(null, ATTR_RESTRICTED_PROFILE_PARENT_ID,
1657 Integer.toString(userInfo.restrictedProfileParentId));
1658 }
Amith Yamasani12747872015-12-07 14:19:49 -08001659 // Write seed data
1660 if (userData.persistSeedData) {
1661 if (userData.seedAccountName != null) {
1662 serializer.attribute(null, ATTR_SEED_ACCOUNT_NAME, userData.seedAccountName);
1663 }
1664 if (userData.seedAccountType != null) {
1665 serializer.attribute(null, ATTR_SEED_ACCOUNT_TYPE, userData.seedAccountType);
1666 }
1667 }
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001668 if (userInfo.name != null) {
1669 serializer.startTag(null, TAG_NAME);
1670 serializer.text(userInfo.name);
1671 serializer.endTag(null, TAG_NAME);
1672 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001673 synchronized (mRestrictionsLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001674 UserRestrictionsUtils.writeRestrictions(serializer,
1675 mBaseUserRestrictions.get(userInfo.id), TAG_RESTRICTIONS);
1676 UserRestrictionsUtils.writeRestrictions(serializer,
1677 mDevicePolicyLocalUserRestrictions.get(userInfo.id),
1678 TAG_DEVICE_POLICY_RESTRICTIONS);
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001679 }
Amith Yamasani12747872015-12-07 14:19:49 -08001680
1681 if (userData.account != null) {
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001682 serializer.startTag(null, TAG_ACCOUNT);
Amith Yamasani12747872015-12-07 14:19:49 -08001683 serializer.text(userData.account);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001684 serializer.endTag(null, TAG_ACCOUNT);
1685 }
1686
Amith Yamasani12747872015-12-07 14:19:49 -08001687 if (userData.persistSeedData && userData.seedAccountOptions != null) {
1688 serializer.startTag(null, TAG_SEED_ACCOUNT_OPTIONS);
1689 userData.seedAccountOptions.saveToXml(serializer);
1690 serializer.endTag(null, TAG_SEED_ACCOUNT_OPTIONS);
1691 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001692 serializer.endTag(null, TAG_USER);
1693
1694 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001695 userFile.finishWrite(fos);
1696 } catch (Exception ioe) {
Jeff Sharkeycd575992016-03-29 14:12:49 -06001697 Slog.e(LOG_TAG, "Error writing user info " + userData.info.id, ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -07001698 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001699 }
1700 }
1701
1702 /*
1703 * Writes the user list file in this format:
1704 *
Amith Yamasani2a003292012-08-14 18:25:45 -07001705 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001706 * <user id="0"></user>
1707 * <user id="2"></user>
1708 * </users>
1709 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001710 private void writeUserListLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001711 if (DBG) {
1712 debug("writeUserList");
1713 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001714 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001715 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001716 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001717 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001718 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1719
1720 // XmlSerializer serializer = XmlUtils.serializerInstance();
1721 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001722 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001723 serializer.startDocument(null, true);
1724 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1725
1726 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -07001727 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -07001728 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001729
Adam Lesinskieddeb492014-09-08 17:50:03 -07001730 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001731 synchronized (mGuestRestrictions) {
1732 UserRestrictionsUtils
1733 .writeRestrictions(serializer, mGuestRestrictions, TAG_RESTRICTIONS);
1734 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301735 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001736 synchronized (mRestrictionsLock) {
1737 UserRestrictionsUtils.writeRestrictions(serializer,
1738 mDevicePolicyGlobalUserRestrictions, TAG_DEVICE_POLICY_RESTRICTIONS);
1739 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001740 int[] userIdsToWrite;
1741 synchronized (mUsersLock) {
1742 userIdsToWrite = new int[mUsers.size()];
1743 for (int i = 0; i < userIdsToWrite.length; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001744 UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001745 userIdsToWrite[i] = user.id;
1746 }
1747 }
1748 for (int id : userIdsToWrite) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001749 serializer.startTag(null, TAG_USER);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001750 serializer.attribute(null, ATTR_ID, Integer.toString(id));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001751 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001752 }
1753
1754 serializer.endTag(null, TAG_USERS);
1755
1756 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001757 userListFile.finishWrite(fos);
1758 } catch (Exception e) {
1759 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -07001760 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001761 }
1762 }
1763
Amith Yamasani12747872015-12-07 14:19:49 -08001764 private UserData readUserLP(int id) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001765 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -07001766 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001767 String name = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001768 String account = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001769 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -07001770 long creationTime = 0L;
1771 long lastLoggedInTime = 0L;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06001772 String lastLoggedInFingerprint = null;
Kenny Guy2a764942014-04-02 13:29:20 +01001773 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001774 int restrictedProfileParentId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001775 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001776 boolean guestToRemove = false;
Amith Yamasani12747872015-12-07 14:19:49 -08001777 boolean persistSeedData = false;
1778 String seedAccountName = null;
1779 String seedAccountType = null;
1780 PersistableBundle seedAccountOptions = null;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001781 Bundle baseRestrictions = new Bundle();
1782 Bundle localRestrictions = new Bundle();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001783
1784 FileInputStream fis = null;
1785 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001786 AtomicFile userFile =
Amith Yamasanifc95e702013-09-26 13:20:17 -07001787 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
Amith Yamasani2a003292012-08-14 18:25:45 -07001788 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001789 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001790 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001791 int type;
1792 while ((type = parser.next()) != XmlPullParser.START_TAG
1793 && type != XmlPullParser.END_DOCUMENT) {
Amith Yamasani12747872015-12-07 14:19:49 -08001794 // Skip
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001795 }
1796
1797 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001798 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001799 return null;
1800 }
1801
1802 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001803 int storedId = readIntAttribute(parser, ATTR_ID, -1);
1804 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001805 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001806 return null;
1807 }
Amith Yamasani920ace02012-09-20 22:15:37 -07001808 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
1809 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001810 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -07001811 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
1812 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06001813 lastLoggedInFingerprint = parser.getAttributeValue(null,
1814 ATTR_LAST_LOGGED_IN_FINGERPRINT);
Kenny Guy2a764942014-04-02 13:29:20 +01001815 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
1816 UserInfo.NO_PROFILE_GROUP_ID);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001817 restrictedProfileParentId = readIntAttribute(parser,
1818 ATTR_RESTRICTED_PROFILE_PARENT_ID, UserInfo.NO_PROFILE_GROUP_ID);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001819 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
1820 if ("true".equals(valueString)) {
1821 partial = true;
1822 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001823 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
1824 if ("true".equals(valueString)) {
1825 guestToRemove = true;
1826 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001827
Amith Yamasani12747872015-12-07 14:19:49 -08001828 seedAccountName = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_NAME);
1829 seedAccountType = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_TYPE);
1830 if (seedAccountName != null || seedAccountType != null) {
1831 persistSeedData = true;
1832 }
1833
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001834 int outerDepth = parser.getDepth();
1835 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1836 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1837 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1838 continue;
1839 }
1840 String tag = parser.getName();
1841 if (TAG_NAME.equals(tag)) {
1842 type = parser.next();
1843 if (type == XmlPullParser.TEXT) {
1844 name = parser.getText();
1845 }
1846 } else if (TAG_RESTRICTIONS.equals(tag)) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001847 UserRestrictionsUtils.readRestrictions(parser, baseRestrictions);
1848 } else if (TAG_DEVICE_POLICY_RESTRICTIONS.equals(tag)) {
1849 UserRestrictionsUtils.readRestrictions(parser, localRestrictions);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001850 } else if (TAG_ACCOUNT.equals(tag)) {
1851 type = parser.next();
1852 if (type == XmlPullParser.TEXT) {
1853 account = parser.getText();
1854 }
Amith Yamasani12747872015-12-07 14:19:49 -08001855 } else if (TAG_SEED_ACCOUNT_OPTIONS.equals(tag)) {
1856 seedAccountOptions = PersistableBundle.restoreFromXml(parser);
1857 persistSeedData = true;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001858 }
1859 }
1860 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001861
Amith Yamasani12747872015-12-07 14:19:49 -08001862 // Create the UserInfo object that gets passed around
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001863 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -07001864 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -07001865 userInfo.creationTime = creationTime;
1866 userInfo.lastLoggedInTime = lastLoggedInTime;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06001867 userInfo.lastLoggedInFingerprint = lastLoggedInFingerprint;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001868 userInfo.partial = partial;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001869 userInfo.guestToRemove = guestToRemove;
Kenny Guy2a764942014-04-02 13:29:20 +01001870 userInfo.profileGroupId = profileGroupId;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001871 userInfo.restrictedProfileParentId = restrictedProfileParentId;
Amith Yamasani12747872015-12-07 14:19:49 -08001872
1873 // Create the UserData object that's internal to this class
1874 UserData userData = new UserData();
1875 userData.info = userInfo;
1876 userData.account = account;
1877 userData.seedAccountName = seedAccountName;
1878 userData.seedAccountType = seedAccountType;
1879 userData.persistSeedData = persistSeedData;
1880 userData.seedAccountOptions = seedAccountOptions;
1881
Makoto Onuki068c54a2015-10-13 14:34:03 -07001882 synchronized (mRestrictionsLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001883 mBaseUserRestrictions.put(id, baseRestrictions);
1884 mDevicePolicyLocalUserRestrictions.put(id, localRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001885 }
Amith Yamasani12747872015-12-07 14:19:49 -08001886 return userData;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001887 } catch (IOException ioe) {
1888 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001889 } finally {
1890 if (fis != null) {
1891 try {
1892 fis.close();
1893 } catch (IOException e) {
1894 }
1895 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001896 }
1897 return null;
1898 }
1899
Amith Yamasani920ace02012-09-20 22:15:37 -07001900 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
1901 String valueString = parser.getAttributeValue(null, attr);
1902 if (valueString == null) return defaultValue;
1903 try {
1904 return Integer.parseInt(valueString);
1905 } catch (NumberFormatException nfe) {
1906 return defaultValue;
1907 }
1908 }
1909
1910 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
1911 String valueString = parser.getAttributeValue(null, attr);
1912 if (valueString == null) return defaultValue;
1913 try {
1914 return Long.parseLong(valueString);
1915 } catch (NumberFormatException nfe) {
1916 return defaultValue;
1917 }
1918 }
1919
Amith Yamasanib82add22013-07-09 11:24:44 -07001920 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001921 * Removes the app restrictions file for a specific package and user id, if it exists.
1922 */
1923 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
1924 synchronized (mPackagesLock) {
1925 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07001926 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001927 if (resFile.exists()) {
1928 resFile.delete();
1929 }
1930 }
1931 }
1932
Kenny Guya52dc3e2014-02-11 15:33:14 +00001933 @Override
Kenny Guy2a764942014-04-02 13:29:20 +01001934 public UserInfo createProfileForUser(String name, int flags, int userId) {
Kenny Guya52dc3e2014-02-11 15:33:14 +00001935 checkManageUsersPermission("Only the system can create users");
Kenny Guy2a764942014-04-02 13:29:20 +01001936 return createUserInternal(name, flags, userId);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001937 }
1938
Amith Yamasani258848d2012-08-10 17:06:33 -07001939 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07001940 public UserInfo createUser(String name, int flags) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001941 checkManageUsersPermission("Only the system can create users");
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001942 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001943 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001944
Jessica Hummelbe81c802014-04-22 15:49:22 +01001945 private UserInfo createUserInternal(String name, int flags, int parentId) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001946 if (hasUserRestriction(UserManager.DISALLOW_ADD_USER, UserHandle.getCallingUserId())) {
Julia Reynolds75175022014-06-26 16:35:00 -04001947 Log.w(LOG_TAG, "Cannot add user. DISALLOW_ADD_USER is enabled.");
1948 return null;
1949 }
phweisse9c44062016-02-10 12:57:38 +01001950 return createUserInternalUnchecked(name, flags, parentId);
1951 }
1952
1953 private UserInfo createUserInternalUnchecked(String name, int flags, int parentId) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001954 if (ActivityManager.isLowRamDeviceStatic()) {
1955 return null;
1956 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07001957 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001958 final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001959 final boolean isRestricted = (flags & UserInfo.FLAG_RESTRICTED) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001960 final long ident = Binder.clearCallingIdentity();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001961 UserInfo userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08001962 UserData userData;
Amith Yamasanibb054c92015-07-09 14:16:27 -07001963 final int userId;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001964 try {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001965 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001966 UserData parent = null;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001967 if (parentId != UserHandle.USER_NULL) {
1968 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001969 parent = getUserDataLU(parentId);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001970 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001971 if (parent == null) return null;
1972 }
1973 if (isManagedProfile && !canAddMoreManagedProfiles(parentId, false)) {
1974 Log.e(LOG_TAG, "Cannot add more managed profiles for user " + parentId);
1975 return null;
1976 }
1977 if (!isGuest && !isManagedProfile && isUserLimitReached()) {
1978 // If we're not adding a guest user or a managed profile and the limit has
1979 // been reached, cannot add a user.
1980 return null;
1981 }
1982 // If we're adding a guest and there already exists one, bail.
1983 if (isGuest && findCurrentGuestUser() != null) {
1984 return null;
1985 }
1986 // In legacy mode, restricted profile's parent can only be the owner user
1987 if (isRestricted && !UserManager.isSplitSystemUser()
1988 && (parentId != UserHandle.USER_SYSTEM)) {
1989 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
1990 return null;
1991 }
1992 if (isRestricted && UserManager.isSplitSystemUser()) {
1993 if (parent == null) {
1994 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be "
1995 + "specified");
Nicolas Prevot12678a92015-05-13 12:15:03 -07001996 return null;
1997 }
Amith Yamasani12747872015-12-07 14:19:49 -08001998 if (!parent.info.canHaveProfile()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001999 Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be "
2000 + "created for the specified parent user id " + parentId);
Amith Yamasani95ab7842014-08-11 17:09:26 -07002001 return null;
2002 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002003 }
Lenka Trochtova024f9792016-02-17 13:55:17 +01002004 if (!UserManager.isSplitSystemUser() && (flags & UserInfo.FLAG_EPHEMERAL) != 0) {
2005 Log.e(LOG_TAG,
2006 "Ephemeral users are supported on split-system-user systems only.");
2007 return null;
2008 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002009 // In split system user mode, we assign the first human user the primary flag.
2010 // And if there is no device owner, we also assign the admin flag to primary user.
2011 if (UserManager.isSplitSystemUser()
2012 && !isGuest && !isManagedProfile && getPrimaryUser() == null) {
2013 flags |= UserInfo.FLAG_PRIMARY;
Makoto Onukie7927da2015-11-25 10:05:17 -08002014 synchronized (mUsersLock) {
2015 if (!mIsDeviceManaged) {
2016 flags |= UserInfo.FLAG_ADMIN;
2017 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07002018 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002019 }
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002020
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002021 userId = getNextAvailableId();
2022 Environment.getUserSystemDirectory(userId).mkdirs();
Lenka Trochtova02fee152015-12-22 14:26:18 +01002023 boolean ephemeralGuests = Resources.getSystem()
2024 .getBoolean(com.android.internal.R.bool.config_guestUserEphemeral);
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002025
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002026 synchronized (mUsersLock) {
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002027 // Add ephemeral flag to guests/users if required. Also inherit it from parent.
2028 if ((isGuest && ephemeralGuests) || mForceEphemeralUsers
2029 || (parent != null && parent.info.isEphemeral())) {
2030 flags |= UserInfo.FLAG_EPHEMERAL;
2031 }
2032
2033 userInfo = new UserInfo(userId, name, null, flags);
2034 userInfo.serialNumber = mNextSerialNumber++;
2035 long now = System.currentTimeMillis();
2036 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
2037 userInfo.partial = true;
Fyodor Kupolov83c24242016-03-31 13:30:42 -07002038 userInfo.lastLoggedInFingerprint = Build.FINGERPRINT;
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002039 userData = new UserData();
2040 userData.info = userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08002041 mUsers.put(userId, userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002042 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06002043 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002044 writeUserListLP();
2045 if (parent != null) {
2046 if (isManagedProfile) {
Amith Yamasani12747872015-12-07 14:19:49 -08002047 if (parent.info.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
2048 parent.info.profileGroupId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002049 writeUserLP(parent);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002050 }
Amith Yamasani12747872015-12-07 14:19:49 -08002051 userInfo.profileGroupId = parent.info.profileGroupId;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002052 } else if (isRestricted) {
Amith Yamasani12747872015-12-07 14:19:49 -08002053 if (parent.info.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) {
2054 parent.info.restrictedProfileParentId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002055 writeUserLP(parent);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002056 }
Amith Yamasani12747872015-12-07 14:19:49 -08002057 userInfo.restrictedProfileParentId = parent.info.restrictedProfileParentId;
Makoto Onuki068c54a2015-10-13 14:34:03 -07002058 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002059 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07002060 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002061 final StorageManager storage = mContext.getSystemService(StorageManager.class);
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002062 storage.createUserKey(userId, userInfo.serialNumber, userInfo.isEphemeral());
Jeff Sharkey47f71082016-02-01 17:03:54 -07002063 prepareUserStorage(userId, userInfo.serialNumber,
2064 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002065 mPm.createNewUser(userId);
2066 userInfo.partial = false;
2067 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002068 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002069 }
2070 updateUserIds();
2071 Bundle restrictions = new Bundle();
Fyodor Kupolove04462c2015-11-30 15:02:53 -08002072 if (isGuest) {
2073 synchronized (mGuestRestrictions) {
2074 restrictions.putAll(mGuestRestrictions);
2075 }
2076 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002077 synchronized (mRestrictionsLock) {
2078 mBaseUserRestrictions.append(userId, restrictions);
2079 }
2080 mPm.newUserCreated(userId);
2081 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
2082 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
2083 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
2084 android.Manifest.permission.MANAGE_USERS);
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -08002085 MetricsLogger.count(mContext, isGuest ? TRON_GUEST_CREATED : TRON_USER_CREATED, 1);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002086 } finally {
2087 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07002088 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002089 return userInfo;
2090 }
2091
Amith Yamasani0b285492011-04-14 17:35:23 -07002092 /**
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002093 * @hide
2094 */
Amith Yamasani12747872015-12-07 14:19:49 -08002095 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002096 public UserInfo createRestrictedProfile(String name, int parentUserId) {
2097 checkManageUsersPermission("setupRestrictedProfile");
2098 final UserInfo user = createProfileForUser(name, UserInfo.FLAG_RESTRICTED, parentUserId);
2099 if (user == null) {
2100 return null;
2101 }
Fyodor Kupolov9e912ba2016-02-09 18:29:43 -08002102 long identity = Binder.clearCallingIdentity();
2103 try {
2104 setUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, true, user.id);
2105 // Change the setting before applying the DISALLOW_SHARE_LOCATION restriction, otherwise
2106 // the putIntForUser() will fail.
2107 android.provider.Settings.Secure.putIntForUser(mContext.getContentResolver(),
2108 android.provider.Settings.Secure.LOCATION_MODE,
2109 android.provider.Settings.Secure.LOCATION_MODE_OFF, user.id);
2110 setUserRestriction(UserManager.DISALLOW_SHARE_LOCATION, true, user.id);
2111 } finally {
2112 Binder.restoreCallingIdentity(identity);
2113 }
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002114 return user;
2115 }
2116
2117 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07002118 * Find the current guest user. If the Guest user is partial,
2119 * then do not include it in the results as it is about to die.
Adam Lesinskieddeb492014-09-08 17:50:03 -07002120 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002121 private UserInfo findCurrentGuestUser() {
2122 synchronized (mUsersLock) {
2123 final int size = mUsers.size();
2124 for (int i = 0; i < size; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002125 final UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002126 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
2127 return user;
2128 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002129 }
2130 }
2131 return null;
2132 }
2133
2134 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07002135 * Mark this guest user for deletion to allow us to create another guest
2136 * and switch to that user before actually removing this guest.
2137 * @param userHandle the userid of the current guest
2138 * @return whether the user could be marked for deletion
2139 */
Amith Yamasani12747872015-12-07 14:19:49 -08002140 @Override
Amith Yamasani1df14732014-08-29 21:37:27 -07002141 public boolean markGuestForDeletion(int userHandle) {
2142 checkManageUsersPermission("Only the system can remove users");
2143 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
2144 UserManager.DISALLOW_REMOVE_USER, false)) {
2145 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
2146 return false;
2147 }
2148
2149 long ident = Binder.clearCallingIdentity();
2150 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002151 final UserData userData;
Amith Yamasani1df14732014-08-29 21:37:27 -07002152 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002153 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002154 userData = mUsers.get(userHandle);
2155 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002156 return false;
2157 }
Amith Yamasani1df14732014-08-29 21:37:27 -07002158 }
Amith Yamasani12747872015-12-07 14:19:49 -08002159 if (!userData.info.isGuest()) {
Amith Yamasani1df14732014-08-29 21:37:27 -07002160 return false;
2161 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002162 // We set this to a guest user that is to be removed. This is a temporary state
2163 // where we are allowed to add new Guest users, even if this one is still not
2164 // removed. This user will still show up in getUserInfo() calls.
2165 // If we don't get around to removing this Guest user, it will be purged on next
2166 // startup.
Amith Yamasani12747872015-12-07 14:19:49 -08002167 userData.info.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07002168 // Mark it as disabled, so that it isn't returned any more when
2169 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002170 userData.info.flags |= UserInfo.FLAG_DISABLED;
2171 writeUserLP(userData);
Amith Yamasani1df14732014-08-29 21:37:27 -07002172 }
2173 } finally {
2174 Binder.restoreCallingIdentity(ident);
2175 }
2176 return true;
2177 }
2178
2179 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002180 * Removes a user and all data directories created for that user. This method should be called
2181 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07002182 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07002183 */
Amith Yamasani12747872015-12-07 14:19:49 -08002184 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -07002185 public boolean removeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002186 checkManageUsersPermission("Only the system can remove users");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04002187 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
2188 UserManager.DISALLOW_REMOVE_USER, false)) {
2189 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
2190 return false;
2191 }
2192
Kenny Guyee58b4f2014-05-23 15:19:53 +01002193 long ident = Binder.clearCallingIdentity();
2194 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002195 final UserData userData;
Fyodor Kupolov0df68cd2015-10-01 13:54:22 -07002196 int currentUser = ActivityManager.getCurrentUser();
2197 if (currentUser == userHandle) {
2198 Log.w(LOG_TAG, "Current user cannot be removed");
2199 return false;
2200 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002201 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002202 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002203 userData = mUsers.get(userHandle);
2204 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002205 return false;
2206 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002207
Fyodor Kupolov82402752015-10-28 14:54:51 -07002208 // We remember deleted user IDs to prevent them from being
2209 // reused during the current boot; they can still be reused
2210 // after a reboot.
2211 mRemovingUserIds.put(userHandle, true);
2212 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002213
Kenny Guyee58b4f2014-05-23 15:19:53 +01002214 try {
2215 mAppOpsService.removeUser(userHandle);
2216 } catch (RemoteException e) {
2217 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
2218 }
2219 // Set this to a partially created user, so that the user will be purged
2220 // on next startup, in case the runtime stops now before stopping and
2221 // removing the user completely.
Amith Yamasani12747872015-12-07 14:19:49 -08002222 userData.info.partial = true;
Kenny Guyee58b4f2014-05-23 15:19:53 +01002223 // Mark it as disabled, so that it isn't returned any more when
2224 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002225 userData.info.flags |= UserInfo.FLAG_DISABLED;
2226 writeUserLP(userData);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002227 }
2228
Amith Yamasani12747872015-12-07 14:19:49 -08002229 if (userData.info.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
2230 && userData.info.isManagedProfile()) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002231 // Send broadcast to notify system that the user removed was a
2232 // managed user.
Amith Yamasani12747872015-12-07 14:19:49 -08002233 sendProfileRemovedBroadcast(userData.info.profileGroupId, userData.info.id);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002234 }
2235
2236 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
2237 int res;
2238 try {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07002239 res = ActivityManagerNative.getDefault().stopUser(userHandle, /* force= */ true,
2240 new IStopUserCallback.Stub() {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002241 @Override
2242 public void userStopped(int userId) {
2243 finishRemoveUser(userId);
2244 }
2245 @Override
2246 public void userStopAborted(int userId) {
2247 }
2248 });
2249 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002250 return false;
2251 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002252 return res == ActivityManager.USER_OP_SUCCESS;
2253 } finally {
2254 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002255 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002256 }
2257
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002258 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07002259 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002260 // Let other services shutdown any activity and clean up their state before completely
2261 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002262 long ident = Binder.clearCallingIdentity();
2263 try {
2264 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
2265 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002266 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
2267 android.Manifest.permission.MANAGE_USERS,
2268
2269 new BroadcastReceiver() {
2270 @Override
2271 public void onReceive(Context context, Intent intent) {
2272 if (DBG) {
2273 Slog.i(LOG_TAG,
2274 "USER_REMOVED broadcast sent, cleaning up user data "
2275 + userHandle);
2276 }
2277 new Thread() {
Amith Yamasani12747872015-12-07 14:19:49 -08002278 @Override
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002279 public void run() {
Amith Yamasani515d4062015-09-28 11:30:06 -07002280 // Clean up any ActivityManager state
2281 LocalServices.getService(ActivityManagerInternal.class)
2282 .onUserRemoved(userHandle);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002283 removeUserState(userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002284 }
2285 }.start();
2286 }
2287 },
2288
2289 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002290 } finally {
2291 Binder.restoreCallingIdentity(ident);
2292 }
Amith Yamasani2a003292012-08-14 18:25:45 -07002293 }
2294
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002295 private void removeUserState(final int userHandle) {
Paul Crowley91293792016-03-25 15:23:07 -07002296 try {
2297 mContext.getSystemService(StorageManager.class).destroyUserKey(userHandle);
2298 } catch (IllegalStateException e) {
2299 // This may be simply because the user was partially created.
2300 Slog.i(LOG_TAG,
2301 "Destroying key for user " + userHandle + " failed, continuing anyway", e);
2302 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002303 // Cleanup package manager settings
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002304 mPm.cleanUpUser(this, userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002305
2306 // Remove this user from the list
Fyodor Kupolov82402752015-10-28 14:54:51 -07002307 synchronized (mUsersLock) {
2308 mUsers.remove(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08002309 mIsUserManaged.delete(userHandle);
2310 }
2311 synchronized (mRestrictionsLock) {
2312 mBaseUserRestrictions.remove(userHandle);
2313 mAppliedUserRestrictions.remove(userHandle);
2314 mCachedEffectiveUserRestrictions.remove(userHandle);
2315 mDevicePolicyLocalUserRestrictions.remove(userHandle);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002316 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002317 // Update the user list
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002318 synchronized (mPackagesLock) {
2319 writeUserListLP();
2320 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06002321 // Remove user file
2322 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
2323 userFile.delete();
Fyodor Kupolov82402752015-10-28 14:54:51 -07002324 updateUserIds();
Amith Yamasani12747872015-12-07 14:19:49 -08002325 File userDir = Environment.getUserSystemDirectory(userHandle);
2326 File renamedUserDir = Environment.getUserSystemDirectory(UserHandle.USER_NULL - userHandle);
2327 if (userDir.renameTo(renamedUserDir)) {
2328 removeDirectoryRecursive(renamedUserDir);
2329 } else {
2330 removeDirectoryRecursive(userDir);
2331 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002332 }
2333
Amith Yamasani61f57372012-08-31 12:12:28 -07002334 private void removeDirectoryRecursive(File parent) {
2335 if (parent.isDirectory()) {
2336 String[] files = parent.list();
2337 for (String filename : files) {
2338 File child = new File(parent, filename);
2339 removeDirectoryRecursive(child);
2340 }
2341 }
2342 parent.delete();
2343 }
2344
Kenny Guyf8d3a232014-05-15 16:09:52 +01002345 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01002346 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01002347 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
2348 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002349 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
Jeff Sharkeyaf6ec292015-12-17 11:19:00 -07002350 managedProfileIntent.putExtra(Intent.EXTRA_USER_HANDLE, removedUserId);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002351 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01002352 }
2353
Amith Yamasani2a003292012-08-14 18:25:45 -07002354 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002355 public Bundle getApplicationRestrictions(String packageName) {
2356 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
2357 }
2358
2359 @Override
2360 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002361 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07002362 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00002363 checkSystemOrRoot("get application restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002364 }
2365 synchronized (mPackagesLock) {
2366 // Read the restrictions from XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07002367 return readApplicationRestrictionsLP(packageName, userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002368 }
2369 }
2370
2371 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002372 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002373 int userId) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00002374 checkSystemOrRoot("set application restrictions");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002375 synchronized (mPackagesLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01002376 if (restrictions == null || restrictions.isEmpty()) {
2377 cleanAppRestrictionsForPackage(packageName, userId);
2378 } else {
Amith Yamasani23879322016-03-30 16:51:26 -07002379 restrictions.setDefusable(true);
Kenny Guyd21b2182014-07-17 16:38:55 +01002380 // Write the restrictions to XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07002381 writeApplicationRestrictionsLP(packageName, restrictions, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01002382 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002383 }
Robin Lee66e5d962014-04-09 16:44:21 +01002384
Fyodor Kupolovd2846122016-02-11 18:06:34 -08002385 // Notify package of changes via an intent - only sent to explicitly registered receivers.
2386 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
2387 changeIntent.setPackage(packageName);
2388 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
2389 mContext.sendBroadcastAsUser(changeIntent, UserHandle.of(userId));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002390 }
2391
2392 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07002393 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002394 try {
2395 return mContext.getPackageManager().getApplicationInfo(packageName,
Fyodor Kupolovd2846122016-02-11 18:06:34 -08002396 PackageManager.MATCH_UNINSTALLED_PACKAGES).uid;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002397 } catch (NameNotFoundException nnfe) {
2398 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07002399 } finally {
2400 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002401 }
2402 }
2403
Fyodor Kupolov82402752015-10-28 14:54:51 -07002404 private Bundle readApplicationRestrictionsLP(String packageName, int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002405 AtomicFile restrictionsFile =
2406 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
2407 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002408 return readApplicationRestrictionsLP(restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002409 }
2410
2411 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002412 static Bundle readApplicationRestrictionsLP(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002413 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002414 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002415 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07002416 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002417 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002418
2419 FileInputStream fis = null;
2420 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002421 fis = restrictionsFile.openRead();
2422 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002423 parser.setInput(fis, StandardCharsets.UTF_8.name());
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002424 XmlUtils.nextElement(parser);
2425 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002426 Slog.e(LOG_TAG, "Unable to read restrictions file "
2427 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002428 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002429 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002430 while (parser.next() != XmlPullParser.END_DOCUMENT) {
2431 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002432 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002433 } catch (IOException|XmlPullParserException e) {
2434 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002435 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002436 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002437 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002438 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002439 }
2440
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002441 private static void readEntry(Bundle restrictions, ArrayList<String> values,
2442 XmlPullParser parser) throws XmlPullParserException, IOException {
2443 int type = parser.getEventType();
2444 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
2445 String key = parser.getAttributeValue(null, ATTR_KEY);
2446 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
2447 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
2448 if (multiple != null) {
2449 values.clear();
2450 int count = Integer.parseInt(multiple);
2451 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
2452 if (type == XmlPullParser.START_TAG
2453 && parser.getName().equals(TAG_VALUE)) {
2454 values.add(parser.nextText().trim());
2455 count--;
2456 }
2457 }
2458 String [] valueStrings = new String[values.size()];
2459 values.toArray(valueStrings);
2460 restrictions.putStringArray(key, valueStrings);
2461 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
2462 restrictions.putBundle(key, readBundleEntry(parser, values));
2463 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
2464 final int outerDepth = parser.getDepth();
2465 ArrayList<Bundle> bundleList = new ArrayList<>();
2466 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2467 Bundle childBundle = readBundleEntry(parser, values);
2468 bundleList.add(childBundle);
2469 }
2470 restrictions.putParcelableArray(key,
2471 bundleList.toArray(new Bundle[bundleList.size()]));
2472 } else {
2473 String value = parser.nextText().trim();
2474 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
2475 restrictions.putBoolean(key, Boolean.parseBoolean(value));
2476 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
2477 restrictions.putInt(key, Integer.parseInt(value));
2478 } else {
2479 restrictions.putString(key, value);
2480 }
2481 }
2482 }
2483 }
2484
2485 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
2486 throws IOException, XmlPullParserException {
2487 Bundle childBundle = new Bundle();
2488 final int outerDepth = parser.getDepth();
2489 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2490 readEntry(childBundle, values, parser);
2491 }
2492 return childBundle;
2493 }
2494
Fyodor Kupolov82402752015-10-28 14:54:51 -07002495 private void writeApplicationRestrictionsLP(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002496 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002497 AtomicFile restrictionsFile = new AtomicFile(
2498 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07002499 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002500 writeApplicationRestrictionsLP(restrictions, restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002501 }
2502
2503 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002504 static void writeApplicationRestrictionsLP(Bundle restrictions, AtomicFile restrictionsFile) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002505 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002506 try {
2507 fos = restrictionsFile.startWrite();
2508 final BufferedOutputStream bos = new BufferedOutputStream(fos);
2509
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002510 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002511 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002512 serializer.startDocument(null, true);
2513 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2514
2515 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002516 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002517 serializer.endTag(null, TAG_RESTRICTIONS);
2518
2519 serializer.endDocument();
2520 restrictionsFile.finishWrite(fos);
2521 } catch (Exception e) {
2522 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002523 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
2524 }
2525 }
2526
2527 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
2528 throws IOException {
2529 for (String key : restrictions.keySet()) {
2530 Object value = restrictions.get(key);
2531 serializer.startTag(null, TAG_ENTRY);
2532 serializer.attribute(null, ATTR_KEY, key);
2533
2534 if (value instanceof Boolean) {
2535 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
2536 serializer.text(value.toString());
2537 } else if (value instanceof Integer) {
2538 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
2539 serializer.text(value.toString());
2540 } else if (value == null || value instanceof String) {
2541 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
2542 serializer.text(value != null ? (String) value : "");
2543 } else if (value instanceof Bundle) {
2544 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2545 writeBundle((Bundle) value, serializer);
2546 } else if (value instanceof Parcelable[]) {
2547 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
2548 Parcelable[] array = (Parcelable[]) value;
2549 for (Parcelable parcelable : array) {
2550 if (!(parcelable instanceof Bundle)) {
2551 throw new IllegalArgumentException("bundle-array can only hold Bundles");
2552 }
2553 serializer.startTag(null, TAG_ENTRY);
2554 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2555 writeBundle((Bundle) parcelable, serializer);
2556 serializer.endTag(null, TAG_ENTRY);
2557 }
2558 } else {
2559 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
2560 String[] values = (String[]) value;
2561 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
2562 for (String choice : values) {
2563 serializer.startTag(null, TAG_VALUE);
2564 serializer.text(choice != null ? choice : "");
2565 serializer.endTag(null, TAG_VALUE);
2566 }
2567 }
2568 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002569 }
2570 }
2571
2572 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07002573 public int getUserSerialNumber(int userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002574 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002575 if (!exists(userHandle)) return -1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002576 return getUserInfoLU(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07002577 }
2578 }
2579
2580 @Override
2581 public int getUserHandle(int userSerialNumber) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002582 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002583 for (int userId : mUserIds) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002584 UserInfo info = getUserInfoLU(userId);
Kenny Guy945f8832015-02-10 15:17:26 +00002585 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07002586 }
2587 // Not found
2588 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07002589 }
2590 }
2591
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002592 @Override
2593 public long getUserCreationTime(int userHandle) {
2594 int callingUserId = UserHandle.getCallingUserId();
2595 UserInfo userInfo = null;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002596 synchronized (mUsersLock) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002597 if (callingUserId == userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002598 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002599 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002600 UserInfo parent = getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002601 if (parent != null && parent.id == callingUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002602 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002603 }
2604 }
2605 }
2606 if (userInfo == null) {
2607 throw new SecurityException("userHandle can only be the calling user or a managed "
2608 + "profile associated with this user");
2609 }
2610 return userInfo.creationTime;
2611 }
2612
Amith Yamasani0b285492011-04-14 17:35:23 -07002613 /**
2614 * Caches the list of user ids in an array, adjusting the array size when necessary.
2615 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002616 private void updateUserIds() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002617 int num = 0;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002618 synchronized (mUsersLock) {
2619 final int userSize = mUsers.size();
2620 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002621 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002622 num++;
2623 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002624 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002625 final int[] newUsers = new int[num];
2626 int n = 0;
2627 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002628 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002629 newUsers[n++] = mUsers.keyAt(i);
2630 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002631 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002632 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07002633 }
2634 }
2635
2636 /**
Jeff Sharkey47f71082016-02-01 17:03:54 -07002637 * Prepare storage areas for given user on all mounted devices.
2638 */
2639 private void prepareUserStorage(int userId, int userSerial, int flags) {
2640 final StorageManager storage = mContext.getSystemService(StorageManager.class);
2641 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
2642 final String volumeUuid = vol.getFsUuid();
2643 storage.prepareUserStorage(volumeUuid, userId, userSerial, flags);
2644 }
2645 }
2646
2647 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002648 * Called right before a user is started. This gives us a chance to prepare
2649 * app storage and apply any user restrictions.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002650 */
2651 public void onBeforeStartUser(int userId) {
Jeff Sharkey47f71082016-02-01 17:03:54 -07002652 final int userSerial = getUserSerialNumber(userId);
2653 prepareUserStorage(userId, userSerial, StorageManager.FLAG_STORAGE_DE);
2654 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_DE);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002655
2656 if (userId != UserHandle.USER_SYSTEM) {
2657 synchronized (mRestrictionsLock) {
2658 applyUserRestrictionsLR(userId);
2659 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002660 }
2661 }
2662
2663 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002664 * Called right before a user is unlocked. This gives us a chance to prepare
2665 * app storage.
2666 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002667 public void onBeforeUnlockUser(@UserIdInt int userId) {
Jeff Sharkey47f71082016-02-01 17:03:54 -07002668 final int userSerial = getUserSerialNumber(userId);
2669 prepareUserStorage(userId, userSerial, StorageManager.FLAG_STORAGE_CE);
2670 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_CE);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002671 }
2672
2673 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002674 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasani920ace02012-09-20 22:15:37 -07002675 * @param userId the user that was just foregrounded
2676 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002677 public void onUserLoggedIn(@UserIdInt int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -08002678 UserData userData = getUserDataNoChecks(userId);
2679 if (userData == null || userData.info.partial) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002680 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
2681 return;
2682 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002683
2684 final long now = System.currentTimeMillis();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002685 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani12747872015-12-07 14:19:49 -08002686 userData.info.lastLoggedInTime = now;
Amith Yamasani920ace02012-09-20 22:15:37 -07002687 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002688 userData.info.lastLoggedInFingerprint = Build.FINGERPRINT;
2689 scheduleWriteUser(userData);
Amith Yamasani920ace02012-09-20 22:15:37 -07002690 }
2691
2692 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002693 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani742a6712011-05-04 14:49:28 -07002694 * TODO: May not be a good idea to recycle ids, in case it results in confusion
2695 * for data and battery stats collection, or unexpected cross-talk.
Amith Yamasani0b285492011-04-14 17:35:23 -07002696 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002697 private int getNextAvailableId() {
2698 synchronized (mUsersLock) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002699 int i = MIN_USER_ID;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002700 while (i < MAX_USER_ID) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002701 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002702 return i;
Amith Yamasani195263742012-08-21 15:40:12 -07002703 }
2704 i++;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002705 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002706 }
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002707 throw new IllegalStateException("No user id available!");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002708 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002709
Amith Yamasanifc95e702013-09-26 13:20:17 -07002710 private String packageToRestrictionsFileName(String packageName) {
2711 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
2712 }
2713
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002714 /**
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002715 * Enforce that serial number stored in user directory inode matches the
2716 * given expected value. Gracefully sets the serial number if currently
2717 * undefined.
2718 *
2719 * @throws IOException when problem extracting serial number, or serial
2720 * number is mismatched.
2721 */
2722 public static void enforceSerialNumber(File file, int serialNumber) throws IOException {
2723 final int foundSerial = getSerialNumber(file);
2724 Slog.v(LOG_TAG, "Found " + file + " with serial number " + foundSerial);
2725
2726 if (foundSerial == -1) {
2727 Slog.d(LOG_TAG, "Serial number missing on " + file + "; assuming current is valid");
2728 try {
2729 setSerialNumber(file, serialNumber);
2730 } catch (IOException e) {
2731 Slog.w(LOG_TAG, "Failed to set serial number on " + file, e);
2732 }
2733
2734 } else if (foundSerial != serialNumber) {
2735 throw new IOException("Found serial number " + foundSerial
2736 + " doesn't match expected " + serialNumber);
2737 }
2738 }
2739
2740 /**
2741 * Set serial number stored in user directory inode.
2742 *
2743 * @throws IOException if serial number was already set
2744 */
2745 private static void setSerialNumber(File file, int serialNumber)
2746 throws IOException {
2747 try {
2748 final byte[] buf = Integer.toString(serialNumber).getBytes(StandardCharsets.UTF_8);
2749 Os.setxattr(file.getAbsolutePath(), XATTR_SERIAL, buf, OsConstants.XATTR_CREATE);
2750 } catch (ErrnoException e) {
2751 throw e.rethrowAsIOException();
2752 }
2753 }
2754
2755 /**
2756 * Return serial number stored in user directory inode.
2757 *
2758 * @return parsed serial number, or -1 if not set
2759 */
2760 private static int getSerialNumber(File file) throws IOException {
2761 try {
2762 final byte[] buf = new byte[256];
2763 final int len = Os.getxattr(file.getAbsolutePath(), XATTR_SERIAL, buf);
2764 final String serial = new String(buf, 0, len);
2765 try {
2766 return Integer.parseInt(serial);
2767 } catch (NumberFormatException e) {
2768 throw new IOException("Bad serial number: " + serial);
2769 }
2770 } catch (ErrnoException e) {
2771 if (e.errno == OsConstants.ENODATA) {
2772 return -1;
2773 } else {
2774 throw e.rethrowAsIOException();
2775 }
2776 }
2777 }
2778
Amith Yamasani920ace02012-09-20 22:15:37 -07002779 @Override
Amith Yamasani12747872015-12-07 14:19:49 -08002780 public void setSeedAccountData(int userId, String accountName, String accountType,
2781 PersistableBundle accountOptions, boolean persist) {
2782 checkManageUsersPermission("Require MANAGE_USERS permission to set user seed data");
2783 synchronized (mPackagesLock) {
2784 final UserData userData;
2785 synchronized (mUsersLock) {
2786 userData = getUserDataLU(userId);
2787 if (userData == null) {
2788 Slog.e(LOG_TAG, "No such user for settings seed data u=" + userId);
2789 return;
2790 }
2791 userData.seedAccountName = accountName;
2792 userData.seedAccountType = accountType;
2793 userData.seedAccountOptions = accountOptions;
2794 userData.persistSeedData = persist;
2795 }
2796 if (persist) {
2797 writeUserLP(userData);
2798 }
2799 }
2800 }
2801
2802 @Override
2803 public String getSeedAccountName() throws RemoteException {
2804 checkManageUsersPermission("Cannot get seed account information");
2805 synchronized (mUsersLock) {
2806 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
2807 return userData.seedAccountName;
2808 }
2809 }
2810
2811 @Override
2812 public String getSeedAccountType() throws RemoteException {
2813 checkManageUsersPermission("Cannot get seed account information");
2814 synchronized (mUsersLock) {
2815 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
2816 return userData.seedAccountType;
2817 }
2818 }
2819
2820 @Override
2821 public PersistableBundle getSeedAccountOptions() throws RemoteException {
2822 checkManageUsersPermission("Cannot get seed account information");
2823 synchronized (mUsersLock) {
2824 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
2825 return userData.seedAccountOptions;
2826 }
2827 }
2828
2829 @Override
2830 public void clearSeedAccountData() throws RemoteException {
2831 checkManageUsersPermission("Cannot clear seed account information");
2832 synchronized (mPackagesLock) {
2833 UserData userData;
2834 synchronized (mUsersLock) {
2835 userData = getUserDataLU(UserHandle.getCallingUserId());
2836 if (userData == null) return;
2837 userData.clearSeedAccountData();
2838 }
2839 writeUserLP(userData);
2840 }
2841 }
2842
2843 @Override
2844 public boolean someUserHasSeedAccount(String accountName, String accountType)
2845 throws RemoteException {
2846 checkManageUsersPermission("Cannot check seed account information");
2847 synchronized (mUsersLock) {
2848 final int userSize = mUsers.size();
2849 for (int i = 0; i < userSize; i++) {
2850 final UserData data = mUsers.valueAt(i);
2851 if (data.info.isInitialized()) continue;
2852 if (data.seedAccountName == null || !data.seedAccountName.equals(accountName)) {
2853 continue;
2854 }
2855 if (data.seedAccountType == null || !data.seedAccountType.equals(accountType)) {
2856 continue;
2857 }
2858 return true;
2859 }
2860 }
2861 return false;
2862 }
2863
2864 @Override
Todd Kennedy60459ab2015-10-30 11:32:16 -07002865 public void onShellCommand(FileDescriptor in, FileDescriptor out,
2866 FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
2867 (new Shell()).exec(this, in, out, err, args, resultReceiver);
2868 }
2869
2870 int onShellCommand(Shell shell, String cmd) {
2871 if (cmd == null) {
2872 return shell.handleDefaultCommands(cmd);
2873 }
2874
2875 final PrintWriter pw = shell.getOutPrintWriter();
2876 try {
2877 switch(cmd) {
2878 case "list":
2879 return runList(pw);
2880 }
2881 } catch (RemoteException e) {
2882 pw.println("Remote exception: " + e);
2883 }
2884 return -1;
2885 }
2886
2887 private int runList(PrintWriter pw) throws RemoteException {
2888 final IActivityManager am = ActivityManagerNative.getDefault();
2889 final List<UserInfo> users = getUsers(false);
2890 if (users == null) {
2891 pw.println("Error: couldn't get users");
2892 return 1;
2893 } else {
2894 pw.println("Users:");
2895 for (int i = 0; i < users.size(); i++) {
Jeff Sharkeye17ac152015-11-06 22:40:29 -08002896 String running = am.isUserRunning(users.get(i).id, 0) ? " running" : "";
Todd Kennedy60459ab2015-10-30 11:32:16 -07002897 pw.println("\t" + users.get(i).toString() + running);
2898 }
2899 return 0;
2900 }
2901 }
2902
2903 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -07002904 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2905 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2906 != PackageManager.PERMISSION_GRANTED) {
2907 pw.println("Permission Denial: can't dump UserManager from from pid="
2908 + Binder.getCallingPid()
2909 + ", uid=" + Binder.getCallingUid()
2910 + " without permission "
2911 + android.Manifest.permission.DUMP);
2912 return;
2913 }
2914
2915 long now = System.currentTimeMillis();
2916 StringBuilder sb = new StringBuilder();
2917 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002918 synchronized (mUsersLock) {
2919 pw.println("Users:");
2920 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002921 UserData userData = mUsers.valueAt(i);
2922 if (userData == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002923 continue;
2924 }
Amith Yamasani12747872015-12-07 14:19:49 -08002925 UserInfo userInfo = userData.info;
2926 final int userId = userInfo.id;
2927 pw.print(" "); pw.print(userInfo);
2928 pw.print(" serialNo="); pw.print(userInfo.serialNumber);
Makoto Onukie7927da2015-11-25 10:05:17 -08002929 if (mRemovingUserIds.get(userId)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002930 pw.print(" <removing> ");
2931 }
Amith Yamasani12747872015-12-07 14:19:49 -08002932 if (userInfo.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002933 pw.print(" <partial>");
2934 }
2935 pw.println();
2936 pw.print(" Created: ");
Amith Yamasani12747872015-12-07 14:19:49 -08002937 if (userInfo.creationTime == 0) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002938 pw.println("<unknown>");
2939 } else {
2940 sb.setLength(0);
Amith Yamasani12747872015-12-07 14:19:49 -08002941 TimeUtils.formatDuration(now - userInfo.creationTime, sb);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002942 sb.append(" ago");
2943 pw.println(sb);
2944 }
2945 pw.print(" Last logged in: ");
Amith Yamasani12747872015-12-07 14:19:49 -08002946 if (userInfo.lastLoggedInTime == 0) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002947 pw.println("<unknown>");
2948 } else {
2949 sb.setLength(0);
Amith Yamasani12747872015-12-07 14:19:49 -08002950 TimeUtils.formatDuration(now - userInfo.lastLoggedInTime, sb);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002951 sb.append(" ago");
2952 pw.println(sb);
2953 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002954 pw.print(" Last logged in fingerprint: ");
2955 pw.println(userInfo.lastLoggedInFingerprint);
Makoto Onukie7927da2015-11-25 10:05:17 -08002956 pw.print(" Has profile owner: ");
2957 pw.println(mIsUserManaged.get(userId));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002958 pw.println(" Restrictions:");
2959 synchronized (mRestrictionsLock) {
2960 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08002961 pw, " ", mBaseUserRestrictions.get(userInfo.id));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002962 pw.println(" Device policy local restrictions:");
2963 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08002964 pw, " ", mDevicePolicyLocalUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002965 pw.println(" Effective restrictions:");
2966 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08002967 pw, " ", mCachedEffectiveUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002968 }
Amith Yamasani12747872015-12-07 14:19:49 -08002969
2970 if (userData.account != null) {
2971 pw.print(" Account name: " + userData.account);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08002972 pw.println();
2973 }
Amith Yamasani12747872015-12-07 14:19:49 -08002974
2975 if (userData.seedAccountName != null) {
2976 pw.print(" Seed account name: " + userData.seedAccountName);
2977 pw.println();
2978 if (userData.seedAccountType != null) {
2979 pw.print(" account type: " + userData.seedAccountType);
2980 pw.println();
2981 }
2982 if (userData.seedAccountOptions != null) {
2983 pw.print(" account options exist");
2984 pw.println();
2985 }
2986 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002987 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002988 }
Amith Yamasani12747872015-12-07 14:19:49 -08002989 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002990 pw.println(" Device policy global restrictions:");
2991 synchronized (mRestrictionsLock) {
2992 UserRestrictionsUtils
2993 .dumpRestrictions(pw, " ", mDevicePolicyGlobalUserRestrictions);
2994 }
Makoto Onukia4f11972015-10-01 13:19:58 -07002995 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002996 pw.println(" Guest restrictions:");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002997 synchronized (mGuestRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002998 UserRestrictionsUtils.dumpRestrictions(pw, " ", mGuestRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002999 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003000 synchronized (mUsersLock) {
3001 pw.println();
3002 pw.println(" Device managed: " + mIsDeviceManaged);
3003 }
Amith Yamasani12747872015-12-07 14:19:49 -08003004 // Dump some capabilities
3005 pw.println();
3006 pw.println(" Max users: " + UserManager.getMaxSupportedUsers());
3007 pw.println(" Supports switchable users: " + UserManager.supportsMultipleUsers());
Lenka Trochtova02fee152015-12-22 14:26:18 +01003008 pw.println(" All guests ephemeral: " + Resources.getSystem().getBoolean(
3009 com.android.internal.R.bool.config_guestUserEphemeral));
Amith Yamasani920ace02012-09-20 22:15:37 -07003010 }
3011 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08003012
3013 final class MainHandler extends Handler {
3014
3015 @Override
3016 public void handleMessage(Message msg) {
3017 switch (msg.what) {
3018 case WRITE_USER_MSG:
3019 removeMessages(WRITE_USER_MSG, msg.obj);
3020 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08003021 int userId = ((UserData) msg.obj).info.id;
3022 UserData userData = getUserDataNoChecks(userId);
3023 if (userData != null) {
3024 writeUserLP(userData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08003025 }
3026 }
3027 }
3028 }
3029 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07003030
3031 /**
3032 * @param userId
3033 * @return whether the user has been initialized yet
3034 */
3035 boolean isInitialized(int userId) {
3036 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
3037 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003038
3039 private class LocalService extends UserManagerInternal {
Makoto Onuki068c54a2015-10-13 14:34:03 -07003040 @Override
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003041 public void setDevicePolicyUserRestrictions(int userId, @NonNull Bundle localRestrictions,
3042 @Nullable Bundle globalRestrictions) {
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08003043 UserManagerService.this.setDevicePolicyUserRestrictionsInner(userId, localRestrictions,
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003044 globalRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003045 }
3046
3047 @Override
3048 public Bundle getBaseUserRestrictions(int userId) {
3049 synchronized (mRestrictionsLock) {
3050 return mBaseUserRestrictions.get(userId);
3051 }
3052 }
3053
3054 @Override
3055 public void setBaseUserRestrictionsByDpmsForMigration(
3056 int userId, Bundle baseRestrictions) {
3057 synchronized (mRestrictionsLock) {
3058 mBaseUserRestrictions.put(userId, new Bundle(baseRestrictions));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003059 invalidateEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003060 }
3061
Amith Yamasani12747872015-12-07 14:19:49 -08003062 final UserData userData = getUserDataNoChecks(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003063 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08003064 if (userData != null) {
3065 writeUserLP(userData);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003066 } else {
3067 Slog.w(LOG_TAG, "UserInfo not found for " + userId);
3068 }
3069 }
3070 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08003071
3072 @Override
3073 public boolean getUserRestriction(int userId, String key) {
3074 return getUserRestrictions(userId).getBoolean(key);
3075 }
3076
3077 @Override
3078 public void addUserRestrictionsListener(UserRestrictionsListener listener) {
3079 synchronized (mUserRestrictionsListeners) {
3080 mUserRestrictionsListeners.add(listener);
3081 }
3082 }
3083
3084 @Override
3085 public void removeUserRestrictionsListener(UserRestrictionsListener listener) {
3086 synchronized (mUserRestrictionsListeners) {
3087 mUserRestrictionsListeners.remove(listener);
3088 }
3089 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003090
3091 @Override
3092 public void setDeviceManaged(boolean isManaged) {
3093 synchronized (mUsersLock) {
3094 mIsDeviceManaged = isManaged;
3095 }
3096 }
3097
3098 @Override
3099 public void setUserManaged(int userId, boolean isManaged) {
3100 synchronized (mUsersLock) {
3101 mIsUserManaged.put(userId, isManaged);
3102 }
3103 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01003104
3105 @Override
3106 public void setUserIcon(int userId, Bitmap bitmap) {
3107 long ident = Binder.clearCallingIdentity();
3108 try {
3109 synchronized (mPackagesLock) {
3110 UserData userData = getUserDataNoChecks(userId);
3111 if (userData == null || userData.info.partial) {
3112 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
3113 return;
3114 }
3115 writeBitmapLP(userData.info, bitmap);
3116 writeUserLP(userData);
3117 }
3118 sendUserInfoChangedBroadcast(userId);
3119 } finally {
3120 Binder.restoreCallingIdentity(ident);
3121 }
3122 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01003123
3124 @Override
3125 public void setForceEphemeralUsers(boolean forceEphemeralUsers) {
3126 synchronized (mUsersLock) {
3127 mForceEphemeralUsers = forceEphemeralUsers;
3128 }
3129 }
3130
3131 @Override
3132 public void removeAllUsers() {
3133 if (UserHandle.USER_SYSTEM == ActivityManager.getCurrentUser()) {
3134 // Remove the non-system users straight away.
3135 removeNonSystemUsers();
3136 } else {
3137 // Switch to the system user first and then remove the other users.
3138 BroadcastReceiver userSwitchedReceiver = new BroadcastReceiver() {
3139 @Override
3140 public void onReceive(Context context, Intent intent) {
3141 int userId =
3142 intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3143 if (userId != UserHandle.USER_SYSTEM) {
3144 return;
3145 }
3146 mContext.unregisterReceiver(this);
3147 removeNonSystemUsers();
3148 }
3149 };
3150 IntentFilter userSwitchedFilter = new IntentFilter();
3151 userSwitchedFilter.addAction(Intent.ACTION_USER_SWITCHED);
3152 mContext.registerReceiver(
3153 userSwitchedReceiver, userSwitchedFilter, null, mHandler);
3154
3155 // Switch to the system user.
3156 ActivityManager am =
3157 (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
3158 am.switchUser(UserHandle.USER_SYSTEM);
3159 }
3160 }
phweisse9c44062016-02-10 12:57:38 +01003161
3162 @Override
Lenka Trochtova1ddda472016-02-12 10:42:12 +01003163 public void onEphemeralUserStop(int userId) {
3164 synchronized (mUsersLock) {
3165 UserInfo userInfo = getUserInfoLU(userId);
3166 if (userInfo != null && userInfo.isEphemeral()) {
3167 // Do not allow switching back to the ephemeral user again as the user is going
3168 // to be deleted.
3169 userInfo.flags |= UserInfo.FLAG_DISABLED;
3170 if (userInfo.isGuest()) {
3171 // Indicate that the guest will be deleted after it stops.
3172 userInfo.guestToRemove = true;
3173 }
3174 }
3175 }
3176 }
3177
3178 @Override
phweisse9c44062016-02-10 12:57:38 +01003179 public UserInfo createUserEvenWhenDisallowed(String name, int flags) {
3180 UserInfo user = createUserInternalUnchecked(name, flags, UserHandle.USER_NULL);
3181 // Keep this in sync with UserManager.createUser
3182 if (user != null && !user.isAdmin()) {
3183 setUserRestriction(UserManager.DISALLOW_SMS, true, user.id);
3184 setUserRestriction(UserManager.DISALLOW_OUTGOING_CALLS, true, user.id);
3185 }
3186 return user;
3187 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01003188 }
3189
3190 /* Remove all the users except of the system one. */
3191 private void removeNonSystemUsers() {
3192 ArrayList<UserInfo> usersToRemove = new ArrayList<>();
3193 synchronized (mUsersLock) {
3194 final int userSize = mUsers.size();
3195 for (int i = 0; i < userSize; i++) {
3196 UserInfo ui = mUsers.valueAt(i).info;
3197 if (ui.id != UserHandle.USER_SYSTEM) {
3198 usersToRemove.add(ui);
3199 }
3200 }
3201 }
3202 for (UserInfo ui: usersToRemove) {
3203 removeUser(ui.id);
3204 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003205 }
Todd Kennedy60459ab2015-10-30 11:32:16 -07003206
3207 private class Shell extends ShellCommand {
3208 @Override
3209 public int onCommand(String cmd) {
3210 return onShellCommand(this, cmd);
3211 }
3212
3213 @Override
3214 public void onHelp() {
3215 final PrintWriter pw = getOutPrintWriter();
3216 pw.println("User manager (user) commands:");
3217 pw.println(" help");
3218 pw.println(" Print this help text.");
3219 pw.println("");
3220 pw.println(" list");
3221 pw.println(" Prints all users on the system.");
3222 }
3223 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003224
3225 private static void debug(String message) {
3226 Log.d(LOG_TAG, message +
3227 (DBG_WITH_STACKTRACE ? " called at\n" + Debug.getCallers(10, " ") : ""));
3228 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003229}