blob: 04f3ce3f233b4a870c5a0b0adbca73c2c55b07e8 [file] [log] [blame]
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
Benjamin Franzf02420c2016-04-04 18:52:21 +010019import static android.content.Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS;
20import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
21
Xiaohui Chenb3b92582015-12-07 11:22:13 -080022import android.Manifest;
Xiaohui Chen594f2082015-08-18 11:04:20 -070023import android.annotation.NonNull;
Makoto Onuki068c54a2015-10-13 14:34:03 -070024import android.annotation.Nullable;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -060025import android.annotation.UserIdInt;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070026import android.app.Activity;
Amith Yamasani2a003292012-08-14 18:25:45 -070027import android.app.ActivityManager;
Amith Yamasani515d4062015-09-28 11:30:06 -070028import android.app.ActivityManagerInternal;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070029import android.app.ActivityManagerNative;
Amith Yamasanieb437d42016-04-29 09:31:25 -070030import android.app.AppGlobals;
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;
Ricky Waib1dd80b2016-06-07 18:00:55 +010034import android.app.PendingIntent;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070035import android.content.BroadcastReceiver;
Bart Searsc51e7252016-05-27 04:12:51 +000036import android.content.ComponentName;
Amith Yamasani258848d2012-08-10 17:06:33 -070037import android.content.Context;
38import android.content.Intent;
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +010039import android.content.IntentFilter;
Benjamin Franzf02420c2016-04-04 18:52:21 +010040import android.content.IntentSender;
Sudheer Shanka194e4152016-07-06 17:49:37 -070041import android.content.pm.IPackageManager;
Amith Yamasani0b285492011-04-14 17:35:23 -070042import android.content.pm.PackageManager;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -080043import android.content.pm.PackageManager.NameNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070044import android.content.pm.UserInfo;
Lenka Trochtova02fee152015-12-22 14:26:18 +010045import android.content.res.Resources;
Amith Yamasanie928d7d2012-09-17 21:46:51 -070046import android.graphics.Bitmap;
Amith Yamasani258848d2012-08-10 17:06:33 -070047import android.os.Binder;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -060048import android.os.Build;
Amith Yamasanie4cf7342012-12-17 11:12:09 -080049import android.os.Bundle;
Makoto Onuki1a2cd742015-11-16 13:51:27 -080050import android.os.Debug;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070051import android.os.Environment;
52import android.os.FileUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080053import android.os.Handler;
Svet Ganov9cea80cd2016-02-16 11:47:00 -080054import android.os.IBinder;
Amith Yamasani258848d2012-08-10 17:06:33 -070055import android.os.IUserManager;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -080056import android.os.Message;
Adrian Roos1bdff912015-02-17 15:51:35 +010057import android.os.ParcelFileDescriptor;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070058import android.os.Parcelable;
Amith Yamasani12747872015-12-07 14:19:49 -080059import android.os.PersistableBundle;
Amith Yamasani258848d2012-08-10 17:06:33 -070060import android.os.Process;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070061import android.os.RemoteException;
Todd Kennedy60459ab2015-10-30 11:32:16 -070062import android.os.ResultReceiver;
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +010063import android.os.SELinux;
Jason Monk62062992014-05-06 09:55:28 -040064import android.os.ServiceManager;
Todd Kennedy60459ab2015-10-30 11:32:16 -070065import android.os.ShellCommand;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070066import android.os.UserHandle;
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070067import android.os.UserManager;
Makoto Onuki068c54a2015-10-13 14:34:03 -070068import android.os.UserManagerInternal;
Makoto Onukid45a4a22015-11-02 17:17:38 -080069import android.os.UserManagerInternal.UserRestrictionsListener;
Paul Crowley85e4e812015-05-19 12:42:00 +010070import android.os.storage.StorageManager;
Amith Yamasanid04aaa32016-06-13 12:09:36 -070071import android.security.GateKeeper;
72import android.service.gatekeeper.IGateKeeperService;
Jeff Sharkey6dce4962015-07-03 18:08:41 -070073import android.system.ErrnoException;
74import android.system.Os;
75import android.system.OsConstants;
Amith Yamasanieb437d42016-04-29 09:31:25 -070076import android.text.TextUtils;
Amith Yamasani2a003292012-08-14 18:25:45 -070077import android.util.AtomicFile;
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -070078import android.util.IntArray;
Amith Yamasani655d0e22013-06-12 14:19:10 -070079import android.util.Log;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070080import android.util.Slog;
81import android.util.SparseArray;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080082import android.util.SparseBooleanArray;
Amith Yamasaniea1b9d72016-05-27 15:57:38 +000083import android.util.SparseIntArray;
Amith Yamasani920ace02012-09-20 22:15:37 -070084import android.util.TimeUtils;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070085import android.util.Xml;
86
Makoto Onuki068c54a2015-10-13 14:34:03 -070087import com.android.internal.annotations.GuardedBy;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070088import com.android.internal.annotations.VisibleForTesting;
Jason Monk62062992014-05-06 09:55:28 -040089import com.android.internal.app.IAppOpsService;
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -080090import com.android.internal.logging.MetricsLogger;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080091import com.android.internal.util.FastXmlSerializer;
Makoto Onuki068c54a2015-10-13 14:34:03 -070092import com.android.internal.util.Preconditions;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070093import com.android.internal.util.XmlUtils;
Clara Bayarri10ad84a2015-12-01 17:38:05 +000094import com.android.internal.widget.LockPatternUtils;
Amith Yamasani515d4062015-09-28 11:30:06 -070095import com.android.server.LocalServices;
Amith Yamasanid04aaa32016-06-13 12:09:36 -070096import com.android.server.SystemService;
Amith Yamasaniea1b9d72016-05-27 15:57:38 +000097import com.android.server.am.UserState;
Jeff Sharkey47f71082016-02-01 17:03:54 -070098
99import libcore.io.IoUtils;
100import libcore.util.Objects;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800101
102import org.xmlpull.v1.XmlPullParser;
103import org.xmlpull.v1.XmlPullParserException;
104import org.xmlpull.v1.XmlSerializer;
105
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700106import java.io.BufferedOutputStream;
107import java.io.File;
Amith Yamasani920ace02012-09-20 22:15:37 -0700108import java.io.FileDescriptor;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700109import java.io.FileInputStream;
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700110import java.io.FileNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700111import java.io.FileOutputStream;
112import java.io.IOException;
Amith Yamasani920ace02012-09-20 22:15:37 -0700113import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100114import java.nio.charset.StandardCharsets;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700115import java.util.ArrayList;
116import java.util.List;
117
Makoto Onuki068c54a2015-10-13 14:34:03 -0700118/**
119 * Service for {@link UserManager}.
120 *
121 * Method naming convention:
Fyodor Kupolov82402752015-10-28 14:54:51 -0700122 * <ul>
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800123 * <li> Methods suffixed with "LP" should be called within the {@link #mPackagesLock} lock.
Fyodor Kupolov82402752015-10-28 14:54:51 -0700124 * <li> Methods suffixed with "LR" should be called within the {@link #mRestrictionsLock} lock.
125 * <li> Methods suffixed with "LU" should be called within the {@link #mUsersLock} lock.
126 * </ul>
Makoto Onuki068c54a2015-10-13 14:34:03 -0700127 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700128public class UserManagerService extends IUserManager.Stub {
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700129
Amith Yamasani2a003292012-08-14 18:25:45 -0700130 private static final String LOG_TAG = "UserManagerService";
Makoto Onuki81c61ea2016-01-22 11:22:26 -0800131 static final boolean DBG = false; // DO NOT SUBMIT WITH TRUE
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800132 private static final boolean DBG_WITH_STACKTRACE = false; // DO NOT SUBMIT WITH TRUE
Amith Yamasani16389312012-10-17 21:20:14 -0700133
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700134 private static final String TAG_NAME = "name";
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800135 private static final String TAG_ACCOUNT = "account";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700136 private static final String ATTR_FLAGS = "flags";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700137 private static final String ATTR_ICON_PATH = "icon";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700138 private static final String ATTR_ID = "id";
Amith Yamasani920ace02012-09-20 22:15:37 -0700139 private static final String ATTR_CREATION_TIME = "created";
140 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -0600141 private static final String ATTR_LAST_LOGGED_IN_FINGERPRINT = "lastLoggedInFingerprint";
Amith Yamasani2a003292012-08-14 18:25:45 -0700142 private static final String ATTR_SERIAL_NO = "serialNumber";
143 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700144 private static final String ATTR_PARTIAL = "partial";
Adam Lesinskieddeb492014-09-08 17:50:03 -0700145 private static final String ATTR_GUEST_TO_REMOVE = "guestToRemove";
Amith Yamasani6f34b412012-10-22 18:19:27 -0700146 private static final String ATTR_USER_VERSION = "version";
Kenny Guy2a764942014-04-02 13:29:20 +0100147 private static final String ATTR_PROFILE_GROUP_ID = "profileGroupId";
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700148 private static final String ATTR_RESTRICTED_PROFILE_PARENT_ID = "restrictedProfileParentId";
Amith Yamasani12747872015-12-07 14:19:49 -0800149 private static final String ATTR_SEED_ACCOUNT_NAME = "seedAccountName";
150 private static final String ATTR_SEED_ACCOUNT_TYPE = "seedAccountType";
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530151 private static final String TAG_GUEST_RESTRICTIONS = "guestRestrictions";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700152 private static final String TAG_USERS = "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700153 private static final String TAG_USER = "user";
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800154 private static final String TAG_RESTRICTIONS = "restrictions";
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800155 private static final String TAG_DEVICE_POLICY_RESTRICTIONS = "device_policy_restrictions";
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +0100156 private static final String TAG_GLOBAL_RESTRICTION_OWNER_ID = "globalRestrictionOwnerUserId";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800157 private static final String TAG_ENTRY = "entry";
158 private static final String TAG_VALUE = "value";
Amith Yamasani12747872015-12-07 14:19:49 -0800159 private static final String TAG_SEED_ACCOUNT_OPTIONS = "seedAccountOptions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800160 private static final String ATTR_KEY = "key";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700161 private static final String ATTR_VALUE_TYPE = "type";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800162 private static final String ATTR_MULTIPLE = "m";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700163
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700164 private static final String ATTR_TYPE_STRING_ARRAY = "sa";
165 private static final String ATTR_TYPE_STRING = "s";
166 private static final String ATTR_TYPE_BOOLEAN = "b";
Amith Yamasani5b5aa402014-06-01 20:10:14 -0700167 private static final String ATTR_TYPE_INTEGER = "i";
Fyodor Kupolov262f9952015-03-23 18:55:11 -0700168 private static final String ATTR_TYPE_BUNDLE = "B";
169 private static final String ATTR_TYPE_BUNDLE_ARRAY = "BA";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700170
Amith Yamasani0b285492011-04-14 17:35:23 -0700171 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700172 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700173 private static final String USER_PHOTO_FILENAME = "photo.png";
Adrian Roos1bdff912015-02-17 15:51:35 +0100174 private static final String USER_PHOTO_FILENAME_TMP = USER_PHOTO_FILENAME + ".tmp";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700175
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800176 private static final String RESTRICTIONS_FILE_PREFIX = "res_";
Amith Yamasanifc95e702013-09-26 13:20:17 -0700177 private static final String XML_SUFFIX = ".xml";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800178
Sudheer Shankaf5cea032016-06-08 17:13:24 -0700179 private static final int ALLOWED_FLAGS_FOR_CREATE_USERS_PERMISSION =
180 UserInfo.FLAG_MANAGED_PROFILE
181 | UserInfo.FLAG_EPHEMERAL
182 | UserInfo.FLAG_RESTRICTED
183 | UserInfo.FLAG_GUEST;
184
Amith Yamasani634cf312012-10-04 17:34:21 -0700185 private static final int MIN_USER_ID = 10;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700186 // We need to keep process uid within Integer.MAX_VALUE.
187 private static final int MAX_USER_ID = Integer.MAX_VALUE / UserHandle.PER_USER_RANGE;
Amith Yamasani634cf312012-10-04 17:34:21 -0700188
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700189 private static final int USER_VERSION = 6;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700190
Amith Yamasani920ace02012-09-20 22:15:37 -0700191 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
192
Nicolas Prevotb8186812015-08-06 15:00:03 +0100193 // Maximum number of managed profiles permitted per user is 1. This cannot be increased
Amith Yamasani95ab7842014-08-11 17:09:26 -0700194 // without first making sure that the rest of the framework is prepared for it.
195 private static final int MAX_MANAGED_PROFILES = 1;
196
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800197 static final int WRITE_USER_MSG = 1;
198 static final int WRITE_USER_DELAY = 2*1000; // 2 seconds
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530199
Jeff Sharkey6dce4962015-07-03 18:08:41 -0700200 private static final String XATTR_SERIAL = "user.serial";
201
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -0800202 // Tron counters
203 private static final String TRON_GUEST_CREATED = "users_guest_created";
204 private static final String TRON_USER_CREATED = "users_user_created";
205
Dianne Hackborn4428e172012-08-24 17:43:05 -0700206 private final Context mContext;
207 private final PackageManagerService mPm;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700208 private final Object mPackagesLock;
Fyodor Kupolov82402752015-10-28 14:54:51 -0700209 // Short-term lock for internal state, when interaction/sync with PM is not required
210 private final Object mUsersLock = new Object();
211 private final Object mRestrictionsLock = new Object();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700212
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800213 private final Handler mHandler;
214
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700215 private final File mUsersDir;
216 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700217
Svet Ganov9cea80cd2016-02-16 11:47:00 -0800218 private static final IBinder mUserRestriconToken = new Binder();
219
Makoto Onuki068c54a2015-10-13 14:34:03 -0700220 /**
Amith Yamasani12747872015-12-07 14:19:49 -0800221 * User-related information that is used for persisting to flash. Only UserInfo is
222 * directly exposed to other system apps.
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800223 */
Amith Yamasani12747872015-12-07 14:19:49 -0800224 private static class UserData {
225 // Basic user information and properties
226 UserInfo info;
227 // Account name used when there is a strong association between a user and an account
228 String account;
229 // Account information for seeding into a newly created user. This could also be
230 // used for login validation for an existing user, for updating their credentials.
231 // In the latter case, data may not need to be persisted as it is only valid for the
232 // current login session.
233 String seedAccountName;
234 String seedAccountType;
235 PersistableBundle seedAccountOptions;
236 // Whether to perist the seed account information to be available after a boot
237 boolean persistSeedData;
238
239 void clearSeedAccountData() {
240 seedAccountName = null;
241 seedAccountType = null;
242 seedAccountOptions = null;
243 persistSeedData = false;
244 }
245 }
246
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800247 @GuardedBy("mUsersLock")
Amith Yamasani12747872015-12-07 14:19:49 -0800248 private final SparseArray<UserData> mUsers = new SparseArray<>();
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800249
250 /**
Makoto Onuki068c54a2015-10-13 14:34:03 -0700251 * User restrictions set via UserManager. This doesn't include restrictions set by
252 * device owner / profile owners.
253 *
254 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
255 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
256 * maybe shared between {@link #mBaseUserRestrictions} and
257 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
258 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700259 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700260 */
261 @GuardedBy("mRestrictionsLock")
262 private final SparseArray<Bundle> mBaseUserRestrictions = new SparseArray<>();
263
264 /**
265 * Cached user restrictions that are in effect -- i.e. {@link #mBaseUserRestrictions} combined
266 * with device / profile owner restrictions. We'll initialize it lazily; use
267 * {@link #getEffectiveUserRestrictions} to access it.
268 *
269 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
270 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
271 * maybe shared between {@link #mBaseUserRestrictions} and
272 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
273 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700274 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700275 */
276 @GuardedBy("mRestrictionsLock")
277 private final SparseArray<Bundle> mCachedEffectiveUserRestrictions = new SparseArray<>();
278
Makoto Onuki4f160732015-10-27 17:15:38 -0700279 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800280 * User restrictions that have already been applied in
281 * {@link #updateUserRestrictionsInternalLR(Bundle, int)}. We use it to detect restrictions
282 * that have changed since the last
283 * {@link #updateUserRestrictionsInternalLR(Bundle, int)} call.
Makoto Onuki4f160732015-10-27 17:15:38 -0700284 */
285 @GuardedBy("mRestrictionsLock")
286 private final SparseArray<Bundle> mAppliedUserRestrictions = new SparseArray<>();
287
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800288 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800289 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
290 * that should be applied to all users, including guests.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800291 */
292 @GuardedBy("mRestrictionsLock")
293 private Bundle mDevicePolicyGlobalUserRestrictions;
294
295 /**
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +0100296 * Id of the user that set global restrictions.
297 */
298 @GuardedBy("mRestrictionsLock")
299 private int mGlobalRestrictionOwnerUserId = UserHandle.USER_NULL;
300
301 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800302 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
303 * for each user.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800304 */
305 @GuardedBy("mRestrictionsLock")
306 private final SparseArray<Bundle> mDevicePolicyLocalUserRestrictions = new SparseArray<>();
307
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800308 @GuardedBy("mGuestRestrictions")
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530309 private final Bundle mGuestRestrictions = new Bundle();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800310
311 /**
312 * Set of user IDs being actively removed. Removed IDs linger in this set
313 * for several seconds to work around a VFS caching issue.
314 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700315 @GuardedBy("mUsersLock")
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800316 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700317
Fyodor Kupolov82402752015-10-28 14:54:51 -0700318 @GuardedBy("mUsersLock")
Amith Yamasani0b285492011-04-14 17:35:23 -0700319 private int[] mUserIds;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800320 @GuardedBy("mPackagesLock")
Amith Yamasani2a003292012-08-14 18:25:45 -0700321 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700322 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700323
Jason Monk62062992014-05-06 09:55:28 -0400324 private IAppOpsService mAppOpsService;
325
Makoto Onuki068c54a2015-10-13 14:34:03 -0700326 private final LocalService mLocalService;
327
Makoto Onukie7927da2015-11-25 10:05:17 -0800328 @GuardedBy("mUsersLock")
329 private boolean mIsDeviceManaged;
330
331 @GuardedBy("mUsersLock")
332 private final SparseBooleanArray mIsUserManaged = new SparseBooleanArray();
333
Makoto Onukid45a4a22015-11-02 17:17:38 -0800334 @GuardedBy("mUserRestrictionsListeners")
335 private final ArrayList<UserRestrictionsListener> mUserRestrictionsListeners =
336 new ArrayList<>();
337
Clara Bayarria1771112015-12-18 16:29:18 +0000338 private final LockPatternUtils mLockPatternUtils;
339
Ricky Waib1dd80b2016-06-07 18:00:55 +0100340 private final String ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK =
341 "com.android.server.pm.DISABLE_QUIET_MODE_AFTER_UNLOCK";
342
343 private final BroadcastReceiver mDisableQuietModeCallback = new BroadcastReceiver() {
344 @Override
345 public void onReceive(Context context, Intent intent) {
346 if (ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK.equals(intent.getAction())) {
347 final IntentSender target = intent.getParcelableExtra(Intent.EXTRA_INTENT);
348 final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_ID, 0);
349 setQuietModeEnabled(userHandle, false);
350 if (target != null) {
351 try {
352 mContext.startIntentSender(target, null, 0, 0, 0);
353 } catch (IntentSender.SendIntentException e) {
354 /* ignore */
355 }
356 }
357 }
358 }
359 };
360
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +0100361 /**
362 * Whether all users should be created ephemeral.
363 */
364 @GuardedBy("mUsersLock")
365 private boolean mForceEphemeralUsers;
366
Amith Yamasaniea1b9d72016-05-27 15:57:38 +0000367 @GuardedBy("mUserStates")
368 private final SparseIntArray mUserStates = new SparseIntArray();
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -0700369
Amith Yamasani258848d2012-08-10 17:06:33 -0700370 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700371
Dianne Hackborn4428e172012-08-24 17:43:05 -0700372 public static UserManagerService getInstance() {
373 synchronized (UserManagerService.class) {
374 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700375 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700376 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700377
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700378 public static class LifeCycle extends SystemService {
379
380 private UserManagerService mUms;
381
382 /**
383 * @param context
384 */
385 public LifeCycle(Context context) {
386 super(context);
387 }
388
389 @Override
390 public void onStart() {
391 mUms = UserManagerService.getInstance();
392 publishBinderService(Context.USER_SERVICE, mUms);
393 }
394
395 @Override
396 public void onBootPhase(int phase) {
397 if (phase == SystemService.PHASE_ACTIVITY_MANAGER_READY) {
398 mUms.cleanupPartialUsers();
399 }
400 }
401 }
402
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800403 @VisibleForTesting
404 UserManagerService(File dataDir) {
405 this(null, null, new Object(), dataDir);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700406 }
407
Dianne Hackborn4428e172012-08-24 17:43:05 -0700408 /**
409 * Called by package manager to create the service. This is closely
410 * associated with the package manager, and the given lock is the
411 * package manager's own lock.
412 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800413 UserManagerService(Context context, PackageManagerService pm, Object packagesLock) {
414 this(context, pm, packagesLock, Environment.getDataDirectory());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700415 }
416
Dianne Hackborn4428e172012-08-24 17:43:05 -0700417 private UserManagerService(Context context, PackageManagerService pm,
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800418 Object packagesLock, File dataDir) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700419 mContext = context;
420 mPm = pm;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700421 mPackagesLock = packagesLock;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800422 mHandler = new MainHandler();
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800423 synchronized (mPackagesLock) {
424 mUsersDir = new File(dataDir, USER_INFO_DIR);
425 mUsersDir.mkdirs();
426 // Make zeroth user directory, for services to migrate their files to that location
427 File userZeroDir = new File(mUsersDir, String.valueOf(UserHandle.USER_SYSTEM));
428 userZeroDir.mkdirs();
429 FileUtils.setPermissions(mUsersDir.toString(),
430 FileUtils.S_IRWXU | FileUtils.S_IRWXG | FileUtils.S_IROTH | FileUtils.S_IXOTH,
431 -1, -1);
432 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
433 initDefaultGuestRestrictions();
434 readUserListLP();
435 sInstance = this;
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700436 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700437 mLocalService = new LocalService();
438 LocalServices.addService(UserManagerInternal.class, mLocalService);
Clara Bayarria1771112015-12-18 16:29:18 +0000439 mLockPatternUtils = new LockPatternUtils(mContext);
Amith Yamasaniea1b9d72016-05-27 15:57:38 +0000440 mUserStates.put(UserHandle.USER_SYSTEM, UserState.STATE_BOOTING);
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700441 }
442
443 void systemReady() {
Jason Monk62062992014-05-06 09:55:28 -0400444 mAppOpsService = IAppOpsService.Stub.asInterface(
445 ServiceManager.getService(Context.APP_OPS_SERVICE));
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800446
447 synchronized (mRestrictionsLock) {
448 applyUserRestrictionsLR(UserHandle.USER_SYSTEM);
Jason Monk62062992014-05-06 09:55:28 -0400449 }
Samuel Tand9453b82016-03-14 15:57:02 -0700450
451 UserInfo currentGuestUser = findCurrentGuestUser();
452 if (currentGuestUser != null && !hasUserRestriction(
453 UserManager.DISALLOW_CONFIG_WIFI, currentGuestUser.id)) {
454 // If a guest user currently exists, apply the DISALLOW_CONFIG_WIFI option
455 // to it, in case this guest was created in a previous version where this
456 // user restriction was not a default guest restriction.
457 setUserRestriction(UserManager.DISALLOW_CONFIG_WIFI, true, currentGuestUser.id);
458 }
Amith Yamasanieb437d42016-04-29 09:31:25 -0700459
Ricky Waib1dd80b2016-06-07 18:00:55 +0100460 mContext.registerReceiver(mDisableQuietModeCallback,
461 new IntentFilter(ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK),
462 null, mHandler);
Amith Yamasani258848d2012-08-10 17:06:33 -0700463 }
464
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700465 void cleanupPartialUsers() {
466 // Prune out any partially created, partially removed and ephemeral users.
467 ArrayList<UserInfo> partials = new ArrayList<>();
468 synchronized (mUsersLock) {
469 final int userSize = mUsers.size();
470 for (int i = 0; i < userSize; i++) {
471 UserInfo ui = mUsers.valueAt(i).info;
472 if ((ui.partial || ui.guestToRemove || ui.isEphemeral()) && i != 0) {
473 partials.add(ui);
Amith Yamasaniae261892016-06-27 10:40:09 -0700474 mRemovingUserIds.append(ui.id, true);
475 ui.partial = true;
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700476 }
477 }
478 }
479 final int partialsSize = partials.size();
480 for (int i = 0; i < partialsSize; i++) {
481 UserInfo ui = partials.get(i);
482 Slog.w(LOG_TAG, "Removing partially created user " + ui.id
483 + " (name=" + ui.name + ")");
484 removeUserState(ui.id);
485 }
486 }
487
Amith Yamasani258848d2012-08-10 17:06:33 -0700488 @Override
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800489 public String getUserAccount(int userId) {
490 checkManageUserAndAcrossUsersFullPermission("get user account");
491 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800492 return mUsers.get(userId).account;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800493 }
494 }
495
496 @Override
497 public void setUserAccount(int userId, String accountName) {
498 checkManageUserAndAcrossUsersFullPermission("set user account");
Amith Yamasani12747872015-12-07 14:19:49 -0800499 UserData userToUpdate = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800500 synchronized (mPackagesLock) {
501 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800502 final UserData userData = mUsers.get(userId);
503 if (userData == null) {
504 Slog.e(LOG_TAG, "User not found for setting user account: u" + userId);
505 return;
506 }
507 String currentAccount = userData.account;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800508 if (!Objects.equal(currentAccount, accountName)) {
Amith Yamasani12747872015-12-07 14:19:49 -0800509 userData.account = accountName;
510 userToUpdate = userData;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800511 }
512 }
513
514 if (userToUpdate != null) {
515 writeUserLP(userToUpdate);
516 }
517 }
518 }
519
520 @Override
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700521 public UserInfo getPrimaryUser() {
522 checkManageUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700523 synchronized (mUsersLock) {
Amith Yamasani515d4062015-09-28 11:30:06 -0700524 final int userSize = mUsers.size();
525 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800526 UserInfo ui = mUsers.valueAt(i).info;
Xiaohui Chend3e9e182015-11-18 13:37:32 -0800527 if (ui.isPrimary() && !mRemovingUserIds.get(ui.id)) {
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700528 return ui;
529 }
530 }
531 }
532 return null;
533 }
534
535 @Override
Xiaohui Chen594f2082015-08-18 11:04:20 -0700536 public @NonNull List<UserInfo> getUsers(boolean excludeDying) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -0700537 checkManageOrCreateUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700538 synchronized (mUsersLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700539 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasani515d4062015-09-28 11:30:06 -0700540 final int userSize = mUsers.size();
541 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800542 UserInfo ui = mUsers.valueAt(i).info;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700543 if (ui.partial) {
544 continue;
545 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800546 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Amith Yamasani6f48d6e2016-03-23 14:28:25 -0700547 users.add(userWithName(ui));
Amith Yamasani920ace02012-09-20 22:15:37 -0700548 }
Amith Yamasani13593602012-03-22 16:16:17 -0700549 }
550 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700551 }
Amith Yamasani13593602012-03-22 16:16:17 -0700552 }
553
Amith Yamasani258848d2012-08-10 17:06:33 -0700554 @Override
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100555 public List<UserInfo> getProfiles(int userId, boolean enabledOnly) {
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700556 boolean returnFullInfo = true;
Amith Yamasani4f582632014-02-19 14:31:52 -0800557 if (userId != UserHandle.getCallingUserId()) {
558 checkManageUsersPermission("getting profiles related to user " + userId);
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700559 } else {
560 returnFullInfo = hasManageUsersPermission();
Amith Yamasani4f582632014-02-19 14:31:52 -0800561 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700562 final long ident = Binder.clearCallingIdentity();
563 try {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700564 synchronized (mUsersLock) {
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700565 return getProfilesLU(userId, enabledOnly, returnFullInfo);
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100566 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700567 } finally {
568 Binder.restoreCallingIdentity(ident);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000569 }
570 }
571
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700572 @Override
573 public int[] getProfileIds(int userId, boolean enabledOnly) {
574 if (userId != UserHandle.getCallingUserId()) {
575 checkManageUsersPermission("getting profiles related to user " + userId);
576 }
577 final long ident = Binder.clearCallingIdentity();
578 try {
579 synchronized (mUsersLock) {
580 return getProfileIdsLU(userId, enabledOnly).toArray();
581 }
582 } finally {
583 Binder.restoreCallingIdentity(ident);
584 }
585 }
586
Amith Yamasanibe465322014-04-24 13:45:17 -0700587 /** Assume permissions already checked and caller's identity cleared */
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700588 private List<UserInfo> getProfilesLU(int userId, boolean enabledOnly, boolean fullInfo) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700589 IntArray profileIds = getProfileIdsLU(userId, enabledOnly);
590 ArrayList<UserInfo> users = new ArrayList<>(profileIds.size());
591 for (int i = 0; i < profileIds.size(); i++) {
592 int profileId = profileIds.get(i);
593 UserInfo userInfo = mUsers.get(profileId).info;
594 // If full info is not required - clear PII data to prevent 3P apps from reading it
595 if (!fullInfo) {
596 userInfo = new UserInfo(userInfo);
597 userInfo.name = null;
598 userInfo.iconPath = null;
599 } else {
600 userInfo = userWithName(userInfo);
601 }
602 users.add(userInfo);
603 }
604 return users;
605 }
606
607 /**
608 * Assume permissions already checked and caller's identity cleared
609 */
610 private IntArray getProfileIdsLU(int userId, boolean enabledOnly) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700611 UserInfo user = getUserInfoLU(userId);
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700612 IntArray result = new IntArray(mUsers.size());
Amith Yamasanidda003f2014-08-28 18:06:51 -0700613 if (user == null) {
614 // Probably a dying user
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700615 return result;
Amith Yamasanidda003f2014-08-28 18:06:51 -0700616 }
Amith Yamasani515d4062015-09-28 11:30:06 -0700617 final int userSize = mUsers.size();
618 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800619 UserInfo profile = mUsers.valueAt(i).info;
Amith Yamasanibe465322014-04-24 13:45:17 -0700620 if (!isProfileOf(user, profile)) {
621 continue;
622 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100623 if (enabledOnly && !profile.isEnabled()) {
624 continue;
Amith Yamasanibe465322014-04-24 13:45:17 -0700625 }
Amith Yamasani70fcf0c2014-07-11 08:40:19 -0700626 if (mRemovingUserIds.get(profile.id)) {
627 continue;
628 }
Tony Mak80189cd2016-04-05 17:21:42 +0100629 if (profile.partial) {
630 continue;
631 }
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700632 result.add(profile.id);
Amith Yamasanibe465322014-04-24 13:45:17 -0700633 }
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700634 return result;
Amith Yamasanibe465322014-04-24 13:45:17 -0700635 }
636
Jessica Hummelbe81c802014-04-22 15:49:22 +0100637 @Override
Andres Moralesc5548c02015-08-05 10:23:12 -0700638 public int getCredentialOwnerProfile(int userHandle) {
639 checkManageUsersPermission("get the credential owner");
Clara Bayarria1771112015-12-18 16:29:18 +0000640 if (!mLockPatternUtils.isSeparateProfileChallengeEnabled(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700641 synchronized (mUsersLock) {
642 UserInfo profileParent = getProfileParentLU(userHandle);
Andres Moralesc5548c02015-08-05 10:23:12 -0700643 if (profileParent != null) {
644 return profileParent.id;
645 }
646 }
647 }
648
649 return userHandle;
650 }
651
652 @Override
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700653 public boolean isSameProfileGroup(int userId, int otherUserId) {
654 if (userId == otherUserId) return true;
655 checkManageUsersPermission("check if in the same profile group");
656 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700657 return isSameProfileGroupLP(userId, otherUserId);
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700658 }
659 }
660
Fyodor Kupolov82402752015-10-28 14:54:51 -0700661 private boolean isSameProfileGroupLP(int userId, int otherUserId) {
662 synchronized (mUsersLock) {
663 UserInfo userInfo = getUserInfoLU(userId);
664 if (userInfo == null || userInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
665 return false;
666 }
667 UserInfo otherUserInfo = getUserInfoLU(otherUserId);
668 if (otherUserInfo == null
669 || otherUserInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
670 return false;
671 }
672 return userInfo.profileGroupId == otherUserInfo.profileGroupId;
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700673 }
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700674 }
675
676 @Override
Jessica Hummelbe81c802014-04-22 15:49:22 +0100677 public UserInfo getProfileParent(int userHandle) {
678 checkManageUsersPermission("get the profile parent");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700679 synchronized (mUsersLock) {
680 return getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700681 }
682 }
683
Fyodor Kupolov82402752015-10-28 14:54:51 -0700684 private UserInfo getProfileParentLU(int userHandle) {
685 UserInfo profile = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700686 if (profile == null) {
687 return null;
688 }
689 int parentUserId = profile.profileGroupId;
690 if (parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
691 return null;
692 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700693 return getUserInfoLU(parentUserId);
Jessica Hummelbe81c802014-04-22 15:49:22 +0100694 }
695 }
696
Fyodor Kupolov82402752015-10-28 14:54:51 -0700697 private static boolean isProfileOf(UserInfo user, UserInfo profile) {
Kenny Guy2a764942014-04-02 13:29:20 +0100698 return user.id == profile.id ||
699 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
700 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000701 }
702
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000703 private void broadcastProfileAvailabilityChanges(UserHandle profileHandle,
Rubin Xuf13c9802016-01-21 18:06:00 +0000704 UserHandle parentHandle, boolean inQuietMode) {
Rubin Xue95057a2016-04-01 16:49:25 +0100705 Intent intent = new Intent();
706 if (inQuietMode) {
707 intent.setAction(Intent.ACTION_MANAGED_PROFILE_UNAVAILABLE);
708 } else {
709 intent.setAction(Intent.ACTION_MANAGED_PROFILE_AVAILABLE);
710 }
Rubin Xuf13c9802016-01-21 18:06:00 +0000711 intent.putExtra(Intent.EXTRA_QUIET_MODE, inQuietMode);
712 intent.putExtra(Intent.EXTRA_USER, profileHandle);
713 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileHandle.getIdentifier());
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000714 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Rubin Xuf13c9802016-01-21 18:06:00 +0000715 mContext.sendBroadcastAsUser(intent, parentHandle);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000716 }
717
718 @Override
719 public void setQuietModeEnabled(int userHandle, boolean enableQuietMode) {
720 checkManageUsersPermission("silence profile");
721 boolean changed = false;
722 UserInfo profile, parent;
723 synchronized (mPackagesLock) {
724 synchronized (mUsersLock) {
725 profile = getUserInfoLU(userHandle);
726 parent = getProfileParentLU(userHandle);
727
728 }
729 if (profile == null || !profile.isManagedProfile()) {
730 throw new IllegalArgumentException("User " + userHandle + " is not a profile");
731 }
732 if (profile.isQuietModeEnabled() != enableQuietMode) {
733 profile.flags ^= UserInfo.FLAG_QUIET_MODE;
Amith Yamasani12747872015-12-07 14:19:49 -0800734 writeUserLP(getUserDataLU(profile.id));
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000735 changed = true;
736 }
737 }
738 if (changed) {
Rubin Xuf13c9802016-01-21 18:06:00 +0000739 long identity = Binder.clearCallingIdentity();
740 try {
741 if (enableQuietMode) {
Nicolas Prevot1219c922016-06-20 17:25:12 +0100742 ActivityManagerNative.getDefault().stopUser(userHandle, /* force */true, null);
Rubin Xuf8451b92016-04-01 15:50:58 +0100743 LocalServices.getService(ActivityManagerInternal.class)
744 .killForegroundAppsForUser(userHandle);
Rubin Xuf13c9802016-01-21 18:06:00 +0000745 } else {
746 ActivityManagerNative.getDefault().startUserInBackground(userHandle);
747 }
748 } catch (RemoteException e) {
749 Slog.e(LOG_TAG, "fail to start/stop user for quiet mode", e);
750 } finally {
751 Binder.restoreCallingIdentity(identity);
752 }
753
754 broadcastProfileAvailabilityChanges(profile.getUserHandle(), parent.getUserHandle(),
755 enableQuietMode);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000756 }
757 }
758
759 @Override
760 public boolean isQuietModeEnabled(int userHandle) {
761 synchronized (mPackagesLock) {
762 UserInfo info;
763 synchronized (mUsersLock) {
764 info = getUserInfoLU(userHandle);
765 }
766 if (info == null || !info.isManagedProfile()) {
Rubin Xuf13c9802016-01-21 18:06:00 +0000767 return false;
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000768 }
769 return info.isQuietModeEnabled();
770 }
771 }
772
Kenny Guya52dc3e2014-02-11 15:33:14 +0000773 @Override
Benjamin Franzf02420c2016-04-04 18:52:21 +0100774 public boolean trySetQuietModeDisabled(int userHandle, IntentSender target) {
Ricky Waib1dd80b2016-06-07 18:00:55 +0100775 checkManageUsersPermission("silence profile");
Jeff Sharkeyce18c812016-04-27 16:00:41 -0600776 if (StorageManager.isUserKeyUnlocked(userHandle)
Ricky Wai9cc7ad62016-05-11 18:00:20 +0100777 || !mLockPatternUtils.isSecure(userHandle)) {
Benjamin Franzf02420c2016-04-04 18:52:21 +0100778 // if the user is already unlocked, no need to show a profile challenge
779 setQuietModeEnabled(userHandle, false);
780 return true;
781 }
782
783 long identity = Binder.clearCallingIdentity();
784 try {
785 // otherwise, we show a profile challenge to trigger decryption of the user
786 final KeyguardManager km = (KeyguardManager) mContext.getSystemService(
787 Context.KEYGUARD_SERVICE);
Ricky Wai7881cf82016-04-15 17:20:12 +0100788 // We should use userHandle not credentialOwnerUserId here, as even if it is unified
789 // lock, confirm screenlock page will know and show personal challenge, and unlock
790 // work profile when personal challenge is correct
Benjamin Franzf02420c2016-04-04 18:52:21 +0100791 final Intent unlockIntent = km.createConfirmDeviceCredentialIntent(null, null,
792 userHandle);
793 if (unlockIntent == null) {
794 return false;
795 }
Ricky Waib1dd80b2016-06-07 18:00:55 +0100796 final Intent callBackIntent = new Intent(
797 ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK);
Benjamin Franzf02420c2016-04-04 18:52:21 +0100798 if (target != null) {
Ricky Waib1dd80b2016-06-07 18:00:55 +0100799 callBackIntent.putExtra(Intent.EXTRA_INTENT, target);
Benjamin Franzf02420c2016-04-04 18:52:21 +0100800 }
Ricky Waib1dd80b2016-06-07 18:00:55 +0100801 callBackIntent.putExtra(Intent.EXTRA_USER_ID, userHandle);
802 callBackIntent.setPackage(mContext.getPackageName());
803 callBackIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
804 final PendingIntent pendingIntent = PendingIntent.getBroadcast(
805 mContext,
806 0,
807 callBackIntent,
808 PendingIntent.FLAG_CANCEL_CURRENT |
809 PendingIntent.FLAG_ONE_SHOT |
810 PendingIntent.FLAG_IMMUTABLE);
811 // After unlocking the challenge, it will disable quiet mode and run the original
812 // intentSender
813 unlockIntent.putExtra(Intent.EXTRA_INTENT, pendingIntent.getIntentSender());
Benjamin Franzf02420c2016-04-04 18:52:21 +0100814 unlockIntent.setFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
815 mContext.startActivity(unlockIntent);
816 } finally {
817 Binder.restoreCallingIdentity(identity);
818 }
819 return false;
820 }
821
822 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100823 public void setUserEnabled(int userId) {
824 checkManageUsersPermission("enable user");
825 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700826 UserInfo info;
827 synchronized (mUsersLock) {
828 info = getUserInfoLU(userId);
829 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100830 if (info != null && !info.isEnabled()) {
831 info.flags ^= UserInfo.FLAG_DISABLED;
Amith Yamasani12747872015-12-07 14:19:49 -0800832 writeUserLP(getUserDataLU(info.id));
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100833 }
834 }
835 }
836
837 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700838 public UserInfo getUserInfo(int userId) {
Sudheer Shankaaccaa082016-06-14 16:22:57 -0700839 checkManageOrCreateUsersPermission("query user");
Tony Mak8673b282016-03-21 21:10:59 +0000840 synchronized (mUsersLock) {
Amith Yamasani6f48d6e2016-03-23 14:28:25 -0700841 return userWithName(getUserInfoLU(userId));
842 }
843 }
844
845 /**
846 * Returns a UserInfo object with the name filled in, for Owner, or the original
847 * if the name is already set.
848 */
849 private UserInfo userWithName(UserInfo orig) {
850 if (orig != null && orig.name == null && orig.id == UserHandle.USER_SYSTEM) {
851 UserInfo withName = new UserInfo(orig);
852 withName.name = getOwnerName();
853 return withName;
854 } else {
855 return orig;
Tony Mak8673b282016-03-21 21:10:59 +0000856 }
857 }
858
859 @Override
860 public boolean isManagedProfile(int userId) {
Tony Makb531d082016-03-16 14:49:52 +0000861 int callingUserId = UserHandle.getCallingUserId();
862 if (callingUserId != userId && !hasManageUsersPermission()) {
863 synchronized (mPackagesLock) {
864 if (!isSameProfileGroupLP(callingUserId, userId)) {
865 throw new SecurityException(
Tony Mak8673b282016-03-21 21:10:59 +0000866 "You need MANAGE_USERS permission to: check if specified user a " +
867 "managed profile outside your profile group");
Tony Makb531d082016-03-16 14:49:52 +0000868 }
869 }
Tony Mak4dc008c2016-03-16 10:46:49 +0000870 }
Fyodor Kupolov82402752015-10-28 14:54:51 -0700871 synchronized (mUsersLock) {
Amith Yamasani1c41dc82016-06-28 16:13:15 -0700872 UserInfo userInfo = getUserInfoLU(userId);
Tony Mak8673b282016-03-21 21:10:59 +0000873 return userInfo != null && userInfo.isManagedProfile();
Amith Yamasani13593602012-03-22 16:16:17 -0700874 }
875 }
876
Amith Yamasani71e6c692013-03-24 17:39:28 -0700877 @Override
Amith Yamasani1c41dc82016-06-28 16:13:15 -0700878 public boolean isDemoUser(int userId) {
879 int callingUserId = UserHandle.getCallingUserId();
880 if (callingUserId != userId && !hasManageUsersPermission()) {
881 throw new SecurityException("You need MANAGE_USERS permission to query if u=" + userId
882 + " is a demo user");
883 }
884 synchronized (mUsersLock) {
885 UserInfo userInfo = getUserInfoLU(userId);
886 return userInfo != null && userInfo.isDemo();
887 }
888 }
889
890 @Override
Amith Yamasani71e6c692013-03-24 17:39:28 -0700891 public boolean isRestricted() {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700892 synchronized (mUsersLock) {
893 return getUserInfoLU(UserHandle.getCallingUserId()).isRestricted();
Amith Yamasani71e6c692013-03-24 17:39:28 -0700894 }
895 }
896
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700897 @Override
898 public boolean canHaveRestrictedProfile(int userId) {
899 checkManageUsersPermission("canHaveRestrictedProfile");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700900 synchronized (mUsersLock) {
901 final UserInfo userInfo = getUserInfoLU(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700902 if (userInfo == null || !userInfo.canHaveProfile()) {
903 return false;
904 }
905 if (!userInfo.isAdmin()) {
906 return false;
907 }
Makoto Onukie7927da2015-11-25 10:05:17 -0800908 // restricted profile can be created if there is no DO set and the admin user has no PO;
909 return !mIsDeviceManaged && !mIsUserManaged.get(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700910 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700911 }
912
Amith Yamasani195263742012-08-21 15:40:12 -0700913 /*
914 * Should be locked on mUsers before calling this.
915 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700916 private UserInfo getUserInfoLU(int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -0800917 final UserData userData = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -0700918 // If it is partial and not in the process of being removed, return as unknown user.
Amith Yamasani12747872015-12-07 14:19:49 -0800919 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700920 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
921 return null;
922 }
Amith Yamasani12747872015-12-07 14:19:49 -0800923 return userData != null ? userData.info : null;
924 }
925
926 private UserData getUserDataLU(int userId) {
927 final UserData userData = mUsers.get(userId);
928 // If it is partial and not in the process of being removed, return as unknown user.
929 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
930 return null;
931 }
932 return userData;
Amith Yamasani195263742012-08-21 15:40:12 -0700933 }
934
Fyodor Kupolov82402752015-10-28 14:54:51 -0700935 /**
936 * Obtains {@link #mUsersLock} and return UserInfo from mUsers.
937 * <p>No permissions checking or any addition checks are made</p>
938 */
939 private UserInfo getUserInfoNoChecks(int userId) {
940 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800941 final UserData userData = mUsers.get(userId);
942 return userData != null ? userData.info : null;
943 }
944 }
945
946 /**
947 * Obtains {@link #mUsersLock} and return UserData from mUsers.
948 * <p>No permissions checking or any addition checks are made</p>
949 */
950 private UserData getUserDataNoChecks(int userId) {
951 synchronized (mUsersLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700952 return mUsers.get(userId);
953 }
954 }
955
Amith Yamasani236b2b52015-08-18 14:32:14 -0700956 /** Called by PackageManagerService */
Amith Yamasani13593602012-03-22 16:16:17 -0700957 public boolean exists(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700958 return getUserInfoNoChecks(userId) != null;
Amith Yamasani13593602012-03-22 16:16:17 -0700959 }
960
Amith Yamasani258848d2012-08-10 17:06:33 -0700961 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700962 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700963 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700964 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700965 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800966 UserData userData = getUserDataNoChecks(userId);
967 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700968 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
969 return;
970 }
Amith Yamasani12747872015-12-07 14:19:49 -0800971 if (name != null && !name.equals(userData.info.name)) {
972 userData.info.name = name;
973 writeUserLP(userData);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700974 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -0700975 }
976 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700977 if (changed) {
978 sendUserInfoChangedBroadcast(userId);
979 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700980 }
981
Amith Yamasani258848d2012-08-10 17:06:33 -0700982 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700983 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700984 checkManageUsersPermission("update users");
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +0100985 if (hasUserRestriction(UserManager.DISALLOW_SET_USER_ICON, userId)) {
986 Log.w(LOG_TAG, "Cannot set user icon. DISALLOW_SET_USER_ICON is enabled.");
987 return;
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700988 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +0100989 mLocalService.setUserIcon(userId, bitmap);
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700990 }
991
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +0100992
993
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700994 private void sendUserInfoChangedBroadcast(int userId) {
995 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
996 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
997 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -0700998 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700999 }
1000
Amith Yamasani258848d2012-08-10 17:06:33 -07001001 @Override
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001002 public ParcelFileDescriptor getUserIcon(int targetUserId) {
Adrian Roos1bdff912015-02-17 15:51:35 +01001003 String iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001004 synchronized (mPackagesLock) {
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001005 UserInfo targetUserInfo = getUserInfoNoChecks(targetUserId);
1006 if (targetUserInfo == null || targetUserInfo.partial) {
1007 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + targetUserId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001008 return null;
1009 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001010
1011 final int callingUserId = UserHandle.getCallingUserId();
1012 final int callingGroupId = getUserInfoNoChecks(callingUserId).profileGroupId;
1013 final int targetGroupId = targetUserInfo.profileGroupId;
1014 final boolean sameGroup = (callingGroupId != UserInfo.NO_PROFILE_GROUP_ID
1015 && callingGroupId == targetGroupId);
1016 if ((callingUserId != targetUserId) && !sameGroup) {
Nicolas Prevot88cc3462014-05-14 14:51:48 +01001017 checkManageUsersPermission("get the icon of a user who is not related");
1018 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001019
1020 if (targetUserInfo.iconPath == null) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001021 return null;
1022 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001023 iconPath = targetUserInfo.iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001024 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001025
1026 try {
1027 return ParcelFileDescriptor.open(
1028 new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
1029 } catch (FileNotFoundException e) {
1030 Log.e(LOG_TAG, "Couldn't find icon file", e);
1031 }
1032 return null;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001033 }
1034
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001035 public void makeInitialized(int userId) {
1036 checkManageUsersPermission("makeInitialized");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001037 boolean scheduleWriteUser = false;
Amith Yamasani12747872015-12-07 14:19:49 -08001038 UserData userData;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001039 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001040 userData = mUsers.get(userId);
1041 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001042 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001043 return;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001044 }
Amith Yamasani12747872015-12-07 14:19:49 -08001045 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1046 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001047 scheduleWriteUser = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001048 }
1049 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001050 if (scheduleWriteUser) {
Amith Yamasani12747872015-12-07 14:19:49 -08001051 scheduleWriteUser(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001052 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001053 }
1054
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001055 /**
1056 * If default guest restrictions haven't been initialized yet, add the basic
1057 * restrictions.
1058 */
1059 private void initDefaultGuestRestrictions() {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001060 synchronized (mGuestRestrictions) {
1061 if (mGuestRestrictions.isEmpty()) {
Samuel Tand9453b82016-03-14 15:57:02 -07001062 mGuestRestrictions.putBoolean(UserManager.DISALLOW_CONFIG_WIFI, true);
Fyodor Kupolove04462c2015-11-30 15:02:53 -08001063 mGuestRestrictions.putBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, true);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001064 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
1065 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
1066 }
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001067 }
1068 }
1069
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001070 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301071 public Bundle getDefaultGuestRestrictions() {
1072 checkManageUsersPermission("getDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001073 synchronized (mGuestRestrictions) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301074 return new Bundle(mGuestRestrictions);
1075 }
1076 }
1077
1078 @Override
1079 public void setDefaultGuestRestrictions(Bundle restrictions) {
1080 checkManageUsersPermission("setDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001081 synchronized (mGuestRestrictions) {
1082 mGuestRestrictions.clear();
1083 mGuestRestrictions.putAll(restrictions);
1084 }
1085 synchronized (mPackagesLock) {
1086 writeUserListLP();
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301087 }
1088 }
1089
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001090 /**
1091 * See {@link UserManagerInternal#setDevicePolicyUserRestrictions(int, Bundle, Bundle)}
1092 */
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08001093 void setDevicePolicyUserRestrictionsInner(int userId, @NonNull Bundle local,
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001094 @Nullable Bundle global) {
1095 Preconditions.checkNotNull(local);
1096 boolean globalChanged = false;
1097 boolean localChanged;
1098 synchronized (mRestrictionsLock) {
1099 if (global != null) {
1100 // Update global.
1101 globalChanged = !UserRestrictionsUtils.areEqual(
1102 mDevicePolicyGlobalUserRestrictions, global);
1103 if (globalChanged) {
1104 mDevicePolicyGlobalUserRestrictions = global;
1105 }
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001106 // Remember the global restriction owner userId to be able to make a distinction
1107 // in getUserRestrictionSource on who set local policies.
1108 mGlobalRestrictionOwnerUserId = userId;
1109 } else {
Zoltan Szatmary-Ban8a5536d2016-05-27 17:56:44 +01001110 if (mGlobalRestrictionOwnerUserId == userId) {
1111 // When profile owner sets restrictions it passes null global bundle and we
1112 // reset global restriction owner userId.
1113 // This means this user used to have DO, but now the DO is gone and the user
1114 // instead has PO.
1115 mGlobalRestrictionOwnerUserId = UserHandle.USER_NULL;
1116 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001117 }
1118 {
1119 // Update local.
1120 final Bundle prev = mDevicePolicyLocalUserRestrictions.get(userId);
1121 localChanged = !UserRestrictionsUtils.areEqual(prev, local);
1122 if (localChanged) {
1123 mDevicePolicyLocalUserRestrictions.put(userId, local);
1124 }
1125 }
1126 }
1127 if (DBG) {
1128 Log.d(LOG_TAG, "setDevicePolicyUserRestrictions: userId=" + userId
1129 + " global=" + global + (globalChanged ? " (changed)" : "")
1130 + " local=" + local + (localChanged ? " (changed)" : "")
1131 );
1132 }
1133 // Don't call them within the mRestrictionsLock.
1134 synchronized (mPackagesLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001135 if (localChanged) {
Amith Yamasani12747872015-12-07 14:19:49 -08001136 writeUserLP(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001137 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06001138 if (globalChanged) {
1139 writeUserListLP();
1140 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001141 }
1142
1143 synchronized (mRestrictionsLock) {
1144 if (globalChanged) {
1145 applyUserRestrictionsForAllUsersLR();
1146 } else if (localChanged) {
1147 applyUserRestrictionsLR(userId);
1148 }
1149 }
1150 }
1151
Makoto Onuki068c54a2015-10-13 14:34:03 -07001152 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001153 private Bundle computeEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001154 final Bundle baseRestrictions =
1155 UserRestrictionsUtils.nonNull(mBaseUserRestrictions.get(userId));
1156 final Bundle global = mDevicePolicyGlobalUserRestrictions;
1157 final Bundle local = mDevicePolicyLocalUserRestrictions.get(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001158
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001159 if (UserRestrictionsUtils.isEmpty(global) && UserRestrictionsUtils.isEmpty(local)) {
1160 // Common case first.
1161 return baseRestrictions;
Makoto Onuki068c54a2015-10-13 14:34:03 -07001162 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001163 final Bundle effective = UserRestrictionsUtils.clone(baseRestrictions);
1164 UserRestrictionsUtils.merge(effective, global);
1165 UserRestrictionsUtils.merge(effective, local);
1166
Makoto Onuki068c54a2015-10-13 14:34:03 -07001167 return effective;
1168 }
1169
1170 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001171 private void invalidateEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki068c54a2015-10-13 14:34:03 -07001172 if (DBG) {
1173 Log.d(LOG_TAG, "invalidateEffectiveUserRestrictions userId=" + userId);
1174 }
1175 mCachedEffectiveUserRestrictions.remove(userId);
1176 }
1177
1178 private Bundle getEffectiveUserRestrictions(int userId) {
1179 synchronized (mRestrictionsLock) {
1180 Bundle restrictions = mCachedEffectiveUserRestrictions.get(userId);
1181 if (restrictions == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001182 restrictions = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001183 mCachedEffectiveUserRestrictions.put(userId, restrictions);
1184 }
1185 return restrictions;
Amith Yamasani8cd28b52014-06-08 17:54:27 -07001186 }
1187 }
1188
Makoto Onuki068c54a2015-10-13 14:34:03 -07001189 /** @return a specific user restriction that's in effect currently. */
1190 @Override
1191 public boolean hasUserRestriction(String restrictionKey, int userId) {
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001192 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1193 return false;
1194 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001195 Bundle restrictions = getEffectiveUserRestrictions(userId);
1196 return restrictions != null && restrictions.getBoolean(restrictionKey);
1197 }
1198
1199 /**
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001200 * @hide
1201 *
1202 * Returns who set a user restriction on a user.
1203 * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
1204 * @param restrictionKey the string key representing the restriction
1205 * @param userId the id of the user for whom to retrieve the restrictions.
1206 * @return The source of user restriction. Any combination of
1207 * {@link UserManager#RESTRICTION_NOT_SET},
1208 * {@link UserManager#RESTRICTION_SOURCE_SYSTEM},
1209 * {@link UserManager#RESTRICTION_SOURCE_DEVICE_OWNER}
1210 * and {@link UserManager#RESTRICTION_SOURCE_PROFILE_OWNER}
1211 */
1212 @Override
1213 public int getUserRestrictionSource(String restrictionKey, int userId) {
1214 checkManageUsersPermission("getUserRestrictionSource");
1215 int result = UserManager.RESTRICTION_NOT_SET;
1216
1217 // Shortcut for the most common case
1218 if (!hasUserRestriction(restrictionKey, userId)) {
1219 return result;
1220 }
1221
1222 if (hasBaseUserRestriction(restrictionKey, userId)) {
1223 result |= UserManager.RESTRICTION_SOURCE_SYSTEM;
1224 }
1225
1226 synchronized(mRestrictionsLock) {
1227 Bundle localRestrictions = mDevicePolicyLocalUserRestrictions.get(userId);
1228 if (!UserRestrictionsUtils.isEmpty(localRestrictions)
1229 && localRestrictions.getBoolean(restrictionKey)) {
1230 // Local restrictions may have been set by device owner the userId of which is
1231 // stored in mGlobalRestrictionOwnerUserId.
1232 if (mGlobalRestrictionOwnerUserId == userId) {
1233 result |= UserManager.RESTRICTION_SOURCE_DEVICE_OWNER;
1234 } else {
1235 result |= UserManager.RESTRICTION_SOURCE_PROFILE_OWNER;
1236 }
1237 }
1238 if (!UserRestrictionsUtils.isEmpty(mDevicePolicyGlobalUserRestrictions)
1239 && mDevicePolicyGlobalUserRestrictions.getBoolean(restrictionKey)) {
1240 result |= UserManager.RESTRICTION_SOURCE_DEVICE_OWNER;
1241 }
1242 }
1243
1244 return result;
1245 }
1246
1247 /**
Makoto Onuki068c54a2015-10-13 14:34:03 -07001248 * @return UserRestrictions that are in effect currently. This always returns a new
1249 * {@link Bundle}.
1250 */
Amith Yamasani8cd28b52014-06-08 17:54:27 -07001251 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001252 public Bundle getUserRestrictions(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001253 return UserRestrictionsUtils.clone(getEffectiveUserRestrictions(userId));
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001254 }
1255
1256 @Override
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +00001257 public boolean hasBaseUserRestriction(String restrictionKey, int userId) {
1258 checkManageUsersPermission("hasBaseUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001259 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1260 return false;
1261 }
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +00001262 synchronized (mRestrictionsLock) {
1263 Bundle bundle = mBaseUserRestrictions.get(userId);
1264 return (bundle != null && bundle.getBoolean(restrictionKey, false));
1265 }
1266 }
1267
1268 @Override
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001269 public void setUserRestriction(String key, boolean value, int userId) {
Fyodor Kupolovd4b26042015-07-27 14:30:59 -07001270 checkManageUsersPermission("setUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001271 if (!UserRestrictionsUtils.isValidRestriction(key)) {
1272 return;
1273 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001274 synchronized (mRestrictionsLock) {
1275 // Note we can't modify Bundles stored in mBaseUserRestrictions directly, so create
1276 // a copy.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001277 final Bundle newRestrictions = UserRestrictionsUtils.clone(
1278 mBaseUserRestrictions.get(userId));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001279 newRestrictions.putBoolean(key, value);
1280
Fyodor Kupolov82402752015-10-28 14:54:51 -07001281 updateUserRestrictionsInternalLR(newRestrictions, userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001282 }
1283 }
1284
Makoto Onuki068c54a2015-10-13 14:34:03 -07001285 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001286 * Optionally updating user restrictions, calculate the effective user restrictions and also
1287 * propagate to other services and system settings.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001288 *
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001289 * @param newRestrictions User restrictions to set.
1290 * If null, will not update user restrictions and only does the propagation.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001291 * @param userId target user ID.
1292 */
1293 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001294 private void updateUserRestrictionsInternalLR(
Makoto Onuki068c54a2015-10-13 14:34:03 -07001295 @Nullable Bundle newRestrictions, int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001296
1297 final Bundle prevAppliedRestrictions = UserRestrictionsUtils.nonNull(
1298 mAppliedUserRestrictions.get(userId));
1299
1300 // Update base restrictions.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001301 if (newRestrictions != null) {
1302 // If newRestrictions == the current one, it's probably a bug.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001303 final Bundle prevBaseRestrictions = mBaseUserRestrictions.get(userId);
1304
1305 Preconditions.checkState(prevBaseRestrictions != newRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001306 Preconditions.checkState(mCachedEffectiveUserRestrictions.get(userId)
1307 != newRestrictions);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001308
1309 if (!UserRestrictionsUtils.areEqual(prevBaseRestrictions, newRestrictions)) {
1310 mBaseUserRestrictions.put(userId, newRestrictions);
Amith Yamasani12747872015-12-07 14:19:49 -08001311 scheduleWriteUser(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001312 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001313 }
1314
Fyodor Kupolov82402752015-10-28 14:54:51 -07001315 final Bundle effective = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001316
Makoto Onuki759a7632015-10-28 16:43:10 -07001317 mCachedEffectiveUserRestrictions.put(userId, effective);
1318
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001319 // Apply the new restrictions.
Makoto Onuki4f160732015-10-27 17:15:38 -07001320 if (DBG) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001321 debug("Applying user restrictions: userId=" + userId
1322 + " new=" + effective + " prev=" + prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001323 }
1324
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001325 if (mAppOpsService != null) { // We skip it until system-ready.
Fyodor Kupolovec30ca32016-06-16 15:09:29 -07001326 mHandler.post(new Runnable() {
1327 @Override
1328 public void run() {
1329 try {
1330 mAppOpsService.setUserRestrictions(effective, mUserRestriconToken, userId);
1331 } catch (RemoteException e) {
1332 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
1333 }
1334 }
1335 });
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001336 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001337
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001338 propagateUserRestrictionsLR(userId, effective, prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001339
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001340 mAppliedUserRestrictions.put(userId, new Bundle(effective));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001341 }
1342
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001343 private void propagateUserRestrictionsLR(final int userId,
Makoto Onukid45a4a22015-11-02 17:17:38 -08001344 Bundle newRestrictions, Bundle prevRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001345 // Note this method doesn't touch any state, meaning it doesn't require mRestrictionsLock
1346 // actually, but we still need some kind of synchronization otherwise we might end up
1347 // calling listeners out-of-order, thus "LR".
1348
1349 if (UserRestrictionsUtils.areEqual(newRestrictions, prevRestrictions)) {
1350 return;
1351 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08001352
1353 final Bundle newRestrictionsFinal = new Bundle(newRestrictions);
1354 final Bundle prevRestrictionsFinal = new Bundle(prevRestrictions);
1355
1356 mHandler.post(new Runnable() {
1357 @Override
1358 public void run() {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07001359 UserRestrictionsUtils.applyUserRestrictions(
1360 mContext, userId, newRestrictionsFinal, prevRestrictionsFinal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001361
Makoto Onukid45a4a22015-11-02 17:17:38 -08001362 final UserRestrictionsListener[] listeners;
1363 synchronized (mUserRestrictionsListeners) {
1364 listeners = new UserRestrictionsListener[mUserRestrictionsListeners.size()];
1365 mUserRestrictionsListeners.toArray(listeners);
1366 }
1367 for (int i = 0; i < listeners.length; i++) {
1368 listeners[i].onUserRestrictionsChanged(userId,
1369 newRestrictionsFinal, prevRestrictionsFinal);
1370 }
1371 }
1372 });
1373 }
1374
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001375 // Package private for the inner class.
1376 void applyUserRestrictionsLR(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001377 updateUserRestrictionsInternalLR(null, userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001378 }
1379
1380 @GuardedBy("mRestrictionsLock")
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001381 // Package private for the inner class.
1382 void applyUserRestrictionsForAllUsersLR() {
1383 if (DBG) {
1384 debug("applyUserRestrictionsForAllUsersLR");
1385 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001386 // First, invalidate all cached values.
Makoto Onuki4f160732015-10-27 17:15:38 -07001387 mCachedEffectiveUserRestrictions.clear();
1388
Makoto Onuki068c54a2015-10-13 14:34:03 -07001389 // We don't want to call into ActivityManagerNative while taking a lock, so we'll call
1390 // it on a handler.
1391 final Runnable r = new Runnable() {
1392 @Override
1393 public void run() {
1394 // Then get the list of running users.
1395 final int[] runningUsers;
1396 try {
1397 runningUsers = ActivityManagerNative.getDefault().getRunningUserIds();
1398 } catch (RemoteException e) {
1399 Log.w(LOG_TAG, "Unable to access ActivityManagerNative");
1400 return;
1401 }
1402 // Then re-calculate the effective restrictions and apply, only for running users.
1403 // It's okay if a new user has started after the getRunningUserIds() call,
1404 // because we'll do the same thing (re-calculate the restrictions and apply)
1405 // when we start a user.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001406 synchronized (mRestrictionsLock) {
1407 for (int i = 0; i < runningUsers.length; i++) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001408 applyUserRestrictionsLR(runningUsers[i]);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001409 }
1410 }
1411 }
1412 };
1413 mHandler.post(r);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001414 }
1415
Amith Yamasani258848d2012-08-10 17:06:33 -07001416 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001417 * Check if we've hit the limit of how many users can be created.
1418 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001419 private boolean isUserLimitReached() {
1420 int count;
1421 synchronized (mUsersLock) {
1422 count = getAliveUsersExcludingGuestsCountLU();
1423 }
1424 return count >= UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001425 }
1426
1427 @Override
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001428 public boolean canAddMoreManagedProfiles(int userId, boolean allowedToRemoveOne) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001429 checkManageUsersPermission("check if more managed profiles can be added.");
1430 if (ActivityManager.isLowRamDeviceStatic()) {
1431 return false;
1432 }
Fyodor Kupolovb6157992015-06-05 15:32:28 -07001433 if (!mContext.getPackageManager().hasSystemFeature(
1434 PackageManager.FEATURE_MANAGED_USERS)) {
1435 return false;
1436 }
Nicolas Prevotb8186812015-08-06 15:00:03 +01001437 // Limit number of managed profiles that can be created
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001438 final int managedProfilesCount = getProfiles(userId, true).size() - 1;
1439 final int profilesRemovedCount = managedProfilesCount > 0 && allowedToRemoveOne ? 1 : 0;
1440 if (managedProfilesCount - profilesRemovedCount >= MAX_MANAGED_PROFILES) {
Nicolas Prevotb8186812015-08-06 15:00:03 +01001441 return false;
1442 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001443 synchronized(mUsersLock) {
1444 UserInfo userInfo = getUserInfoLU(userId);
Nicolas Prevotb8186812015-08-06 15:00:03 +01001445 if (!userInfo.canHaveProfile()) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001446 return false;
1447 }
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001448 int usersCountAfterRemoving = getAliveUsersExcludingGuestsCountLU()
1449 - profilesRemovedCount;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001450 // We allow creating a managed profile in the special case where there is only one user.
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001451 return usersCountAfterRemoving == 1
1452 || usersCountAfterRemoving < UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001453 }
1454 }
1455
Fyodor Kupolov82402752015-10-28 14:54:51 -07001456 private int getAliveUsersExcludingGuestsCountLU() {
Amith Yamasanif584f012014-05-19 17:57:25 -07001457 int aliveUserCount = 0;
1458 final int totalUserCount = mUsers.size();
1459 // Skip over users being removed
1460 for (int i = 0; i < totalUserCount; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001461 UserInfo user = mUsers.valueAt(i).info;
Amith Yamasani95ab7842014-08-11 17:09:26 -07001462 if (!mRemovingUserIds.get(user.id)
Amith Yamasani1df14732014-08-29 21:37:27 -07001463 && !user.isGuest() && !user.partial) {
Amith Yamasanif584f012014-05-19 17:57:25 -07001464 aliveUserCount++;
1465 }
1466 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001467 return aliveUserCount;
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001468 }
1469
1470 /**
Amith Yamasani195263742012-08-21 15:40:12 -07001471 * Enforces that only the system UID or root's UID or apps that have the
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001472 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} and
1473 * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL INTERACT_ACROSS_USERS_FULL}
1474 * permissions can make certain calls to the UserManager.
1475 *
1476 * @param message used as message if SecurityException is thrown
1477 * @throws SecurityException if the caller does not have enough privilege.
1478 */
1479 private static final void checkManageUserAndAcrossUsersFullPermission(String message) {
1480 final int uid = Binder.getCallingUid();
1481 if (uid != Process.SYSTEM_UID && uid != 0
1482 && ActivityManager.checkComponentPermission(
1483 Manifest.permission.MANAGE_USERS,
1484 uid, -1, true) != PackageManager.PERMISSION_GRANTED
1485 && ActivityManager.checkComponentPermission(
1486 Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1487 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
1488 throw new SecurityException(
1489 "You need MANAGE_USERS and INTERACT_ACROSS_USERS_FULL permission to: "
1490 + message);
1491 }
1492 }
1493
1494 /**
1495 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001496 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -07001497 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -07001498 *
1499 * @param message used as message if SecurityException is thrown
1500 * @throws SecurityException if the caller is not system or root
Tony Mak4dc008c2016-03-16 10:46:49 +00001501 * @see #hasManageUsersPermission()
Amith Yamasani258848d2012-08-10 17:06:33 -07001502 */
Amith Yamasanibe465322014-04-24 13:45:17 -07001503 private static final void checkManageUsersPermission(String message) {
Tony Mak4dc008c2016-03-16 10:46:49 +00001504 if (!hasManageUsersPermission()) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001505 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
1506 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -04001507 }
1508
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001509 /**
Sudheer Shankaf5cea032016-06-08 17:13:24 -07001510 * Enforces that only the system UID or root's UID or apps that have the
1511 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or
1512 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS}
1513 * can make certain calls to the UserManager.
1514 *
1515 * @param message used as message if SecurityException is thrown
1516 * @throws SecurityException if the caller is not system or root
1517 * @see #hasManageOrCreateUsersPermission()
1518 */
1519 private static final void checkManageOrCreateUsersPermission(String message) {
1520 if (!hasManageOrCreateUsersPermission()) {
1521 throw new SecurityException(
1522 "You either need MANAGE_USERS or CREATE_USERS permission to: " + message);
1523 }
1524 }
1525
1526 /**
1527 * Similar to {@link #checkManageOrCreateUsersPermission(String)} but when the caller is tries
1528 * to create user/profiles other than what is allowed for
1529 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS} permission, then it will only
1530 * allow callers with {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} permission.
1531 */
1532 private static final void checkManageOrCreateUsersPermission(int creationFlags) {
1533 if ((creationFlags & ~ALLOWED_FLAGS_FOR_CREATE_USERS_PERMISSION) == 0) {
1534 if (!hasManageOrCreateUsersPermission()) {
1535 throw new SecurityException("You either need MANAGE_USERS or CREATE_USERS "
1536 + "permission to create an user with flags: " + creationFlags);
1537 }
1538 } else if (!hasManageUsersPermission()) {
1539 throw new SecurityException("You need MANAGE_USERS permission to create an user "
1540 + " with flags: " + creationFlags);
1541 }
1542 }
1543
1544 /**
Tony Mak4dc008c2016-03-16 10:46:49 +00001545 * @return whether the calling UID is system UID or root's UID or the calling app has the
1546 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}.
1547 */
1548 private static final boolean hasManageUsersPermission() {
1549 final int callingUid = Binder.getCallingUid();
1550 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
1551 || callingUid == Process.ROOT_UID
1552 || ActivityManager.checkComponentPermission(
1553 android.Manifest.permission.MANAGE_USERS,
1554 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED;
1555 }
1556
1557 /**
Sudheer Shankaf5cea032016-06-08 17:13:24 -07001558 * @return whether the calling UID is system UID or root's UID or the calling app has the
1559 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or
1560 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS}.
1561 */
1562 private static final boolean hasManageOrCreateUsersPermission() {
1563 final int callingUid = Binder.getCallingUid();
1564 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
1565 || callingUid == Process.ROOT_UID
1566 || ActivityManager.checkComponentPermission(
1567 android.Manifest.permission.MANAGE_USERS,
1568 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED
1569 || ActivityManager.checkComponentPermission(
1570 android.Manifest.permission.CREATE_USERS,
1571 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED;
1572 }
1573
1574 /**
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001575 * Enforces that only the system UID or root's UID (on any user) can make certain calls to the
1576 * UserManager.
1577 *
1578 * @param message used as message if SecurityException is thrown
1579 * @throws SecurityException if the caller is not system or root
1580 */
1581 private static void checkSystemOrRoot(String message) {
1582 final int uid = Binder.getCallingUid();
1583 if (!UserHandle.isSameApp(uid, Process.SYSTEM_UID) && uid != Process.ROOT_UID) {
1584 throw new SecurityException("Only system may: " + message);
1585 }
1586 }
1587
Fyodor Kupolov82402752015-10-28 14:54:51 -07001588 private void writeBitmapLP(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001589 try {
1590 File dir = new File(mUsersDir, Integer.toString(info.id));
1591 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +01001592 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001593 if (!dir.exists()) {
1594 dir.mkdir();
1595 FileUtils.setPermissions(
1596 dir.getPath(),
1597 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
1598 -1, -1);
1599 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001600 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +01001601 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001602 && tmp.renameTo(file) && SELinux.restorecon(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -07001603 info.iconPath = file.getAbsolutePath();
1604 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001605 try {
1606 os.close();
1607 } catch (IOException ioe) {
1608 // What the ... !
1609 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001610 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001611 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001612 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001613 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001614 }
1615
Amith Yamasani0b285492011-04-14 17:35:23 -07001616 /**
1617 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
1618 * cache it elsewhere.
1619 * @return the array of user ids.
1620 */
Dianne Hackborn1676c852012-09-10 14:52:30 -07001621 public int[] getUserIds() {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001622 synchronized (mUsersLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001623 return mUserIds;
1624 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001625 }
1626
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001627 private void readUserListLP() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001628 if (!mUserListFile.exists()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001629 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001630 return;
1631 }
1632 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001633 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001634 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001635 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001636 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001637 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001638 int type;
1639 while ((type = parser.next()) != XmlPullParser.START_TAG
1640 && type != XmlPullParser.END_DOCUMENT) {
Amith Yamasani12747872015-12-07 14:19:49 -08001641 // Skip
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001642 }
1643
1644 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001645 Slog.e(LOG_TAG, "Unable to read user list");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001646 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001647 return;
1648 }
1649
Amith Yamasani2a003292012-08-14 18:25:45 -07001650 mNextSerialNumber = -1;
1651 if (parser.getName().equals(TAG_USERS)) {
1652 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
1653 if (lastSerialNumber != null) {
1654 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
1655 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001656 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
1657 if (versionNumber != null) {
1658 mUserVersion = Integer.parseInt(versionNumber);
1659 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001660 }
1661
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001662 final Bundle newDevicePolicyGlobalUserRestrictions = new Bundle();
1663
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001664 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301665 if (type == XmlPullParser.START_TAG) {
1666 final String name = parser.getName();
1667 if (name.equals(TAG_USER)) {
1668 String id = parser.getAttributeValue(null, ATTR_ID);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001669
Amith Yamasani12747872015-12-07 14:19:49 -08001670 UserData userData = readUserLP(Integer.parseInt(id));
1671
1672 if (userData != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001673 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001674 mUsers.put(userData.info.id, userData);
1675 if (mNextSerialNumber < 0
1676 || mNextSerialNumber <= userData.info.id) {
1677 mNextSerialNumber = userData.info.id + 1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001678 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301679 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001680 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301681 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -08001682 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1683 && type != XmlPullParser.END_TAG) {
1684 if (type == XmlPullParser.START_TAG) {
1685 if (parser.getName().equals(TAG_RESTRICTIONS)) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001686 synchronized (mGuestRestrictions) {
1687 UserRestrictionsUtils
1688 .readRestrictions(parser, mGuestRestrictions);
1689 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001690 } else if (parser.getName().equals(TAG_DEVICE_POLICY_RESTRICTIONS)
1691 ) {
1692 UserRestrictionsUtils.readRestrictions(parser,
1693 newDevicePolicyGlobalUserRestrictions);
Amith Yamasanida0b1682014-11-21 12:58:17 -08001694 }
1695 break;
1696 }
1697 }
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001698 } else if (name.equals(TAG_GLOBAL_RESTRICTION_OWNER_ID)) {
1699 String ownerUserId = parser.getAttributeValue(null, ATTR_ID);
1700 if (ownerUserId != null) {
1701 mGlobalRestrictionOwnerUserId = Integer.parseInt(ownerUserId);
1702 }
Amith Yamasani258848d2012-08-10 17:06:33 -07001703 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001704 }
1705 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001706 synchronized (mRestrictionsLock) {
1707 mDevicePolicyGlobalUserRestrictions = newDevicePolicyGlobalUserRestrictions;
1708 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001709 updateUserIds();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001710 upgradeIfNecessaryLP();
1711 } catch (IOException | XmlPullParserException e) {
1712 fallbackToSingleUserLP();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001713 } finally {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001714 IoUtils.closeQuietly(fis);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001715 }
1716 }
1717
Amith Yamasani6f34b412012-10-22 18:19:27 -07001718 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -08001719 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -07001720 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001721 private void upgradeIfNecessaryLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001722 final int originalVersion = mUserVersion;
Amith Yamasani6f34b412012-10-22 18:19:27 -07001723 int userVersion = mUserVersion;
1724 if (userVersion < 1) {
1725 // Assign a proper name for the owner, if not initialized correctly before
Amith Yamasani12747872015-12-07 14:19:49 -08001726 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
1727 if ("Primary".equals(userData.info.name)) {
1728 userData.info.name =
1729 mContext.getResources().getString(com.android.internal.R.string.owner_name);
1730 scheduleWriteUser(userData);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001731 }
1732 userVersion = 1;
1733 }
1734
Amith Yamasanibc9625052012-11-15 14:39:18 -08001735 if (userVersion < 2) {
1736 // Owner should be marked as initialized
Amith Yamasani12747872015-12-07 14:19:49 -08001737 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
1738 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1739 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
1740 scheduleWriteUser(userData);
Amith Yamasanibc9625052012-11-15 14:39:18 -08001741 }
1742 userVersion = 2;
1743 }
1744
Amith Yamasani350962c2013-08-06 11:18:53 -07001745
Amith Yamasani5e486f52013-08-07 11:06:44 -07001746 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -07001747 userVersion = 4;
1748 }
1749
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001750 if (userVersion < 5) {
1751 initDefaultGuestRestrictions();
1752 userVersion = 5;
1753 }
1754
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001755 if (userVersion < 6) {
1756 final boolean splitSystemUser = UserManager.isSplitSystemUser();
Fyodor Kupolov82402752015-10-28 14:54:51 -07001757 synchronized (mUsersLock) {
1758 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001759 UserData userData = mUsers.valueAt(i);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001760 // In non-split mode, only user 0 can have restricted profiles
Amith Yamasani12747872015-12-07 14:19:49 -08001761 if (!splitSystemUser && userData.info.isRestricted()
1762 && (userData.info.restrictedProfileParentId
1763 == UserInfo.NO_PROFILE_GROUP_ID)) {
1764 userData.info.restrictedProfileParentId = UserHandle.USER_SYSTEM;
1765 scheduleWriteUser(userData);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001766 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001767 }
1768 }
1769 userVersion = 6;
1770 }
1771
Amith Yamasani6f34b412012-10-22 18:19:27 -07001772 if (userVersion < USER_VERSION) {
1773 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
1774 + USER_VERSION);
1775 } else {
1776 mUserVersion = userVersion;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001777
1778 if (originalVersion < mUserVersion) {
1779 writeUserListLP();
1780 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001781 }
1782 }
1783
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001784 private void fallbackToSingleUserLP() {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001785 int flags = UserInfo.FLAG_INITIALIZED;
1786 // In split system user mode, the admin and primary flags are assigned to the first human
1787 // user.
1788 if (!UserManager.isSplitSystemUser()) {
1789 flags |= UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY;
1790 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001791 // Create the system user
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001792 UserInfo system = new UserInfo(UserHandle.USER_SYSTEM, null, null, flags);
Amith Yamasani12747872015-12-07 14:19:49 -08001793 UserData userData = new UserData();
1794 userData.info = system;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001795 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001796 mUsers.put(system.id, userData);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001797 }
Amith Yamasani634cf312012-10-04 17:34:21 -07001798 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -04001799 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -08001800
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001801 Bundle restrictions = new Bundle();
Mahaver Chopra3d9805d2016-07-07 16:25:05 +01001802 try {
1803 final String[] defaultFirstUserRestrictions = mContext.getResources().getStringArray(
1804 com.android.internal.R.array.config_defaultFirstUserRestrictions);
1805 for (String userRestriction : defaultFirstUserRestrictions) {
1806 if (UserRestrictionsUtils.isValidRestriction(userRestriction)) {
1807 restrictions.putBoolean(userRestriction, true);
1808 }
1809 }
1810 } catch (Resources.NotFoundException e) {
1811 Log.e(LOG_TAG, "Couldn't find resource: config_defaultFirstUserRestrictions", e);
1812 }
1813
Makoto Onuki068c54a2015-10-13 14:34:03 -07001814 synchronized (mRestrictionsLock) {
1815 mBaseUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions);
1816 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001817
Fyodor Kupolov82402752015-10-28 14:54:51 -07001818 updateUserIds();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001819 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001820
Amith Yamasani12747872015-12-07 14:19:49 -08001821 writeUserLP(userData);
Jeff Sharkeycd575992016-03-29 14:12:49 -06001822 writeUserListLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001823 }
1824
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001825 private String getOwnerName() {
1826 return mContext.getResources().getString(com.android.internal.R.string.owner_name);
1827 }
1828
Amith Yamasani12747872015-12-07 14:19:49 -08001829 private void scheduleWriteUser(UserData UserData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001830 if (DBG) {
1831 debug("scheduleWriteUser");
1832 }
Makoto Onuki9e935a32015-11-06 14:24:24 -08001833 // No need to wrap it within a lock -- worst case, we'll just post the same message
1834 // twice.
Amith Yamasani12747872015-12-07 14:19:49 -08001835 if (!mHandler.hasMessages(WRITE_USER_MSG, UserData)) {
1836 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, UserData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001837 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
1838 }
1839 }
1840
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001841 /*
1842 * Writes the user file in this format:
1843 *
1844 * <user flags="20039023" id="0">
1845 * <name>Primary</name>
1846 * </user>
1847 */
Amith Yamasani12747872015-12-07 14:19:49 -08001848 private void writeUserLP(UserData userData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001849 if (DBG) {
Amith Yamasani12747872015-12-07 14:19:49 -08001850 debug("writeUserLP " + userData);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001851 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001852 FileOutputStream fos = null;
Amith Yamasani12747872015-12-07 14:19:49 -08001853 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userData.info.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001854 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001855 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001856 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1857
1858 // XmlSerializer serializer = XmlUtils.serializerInstance();
1859 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001860 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001861 serializer.startDocument(null, true);
1862 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1863
Amith Yamasani12747872015-12-07 14:19:49 -08001864 final UserInfo userInfo = userData.info;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001865 serializer.startTag(null, TAG_USER);
1866 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
Amith Yamasani2a003292012-08-14 18:25:45 -07001867 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001868 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Amith Yamasani920ace02012-09-20 22:15:37 -07001869 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
1870 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
1871 Long.toString(userInfo.lastLoggedInTime));
Jeff Sharkeycd575992016-03-29 14:12:49 -06001872 if (userInfo.lastLoggedInFingerprint != null) {
1873 serializer.attribute(null, ATTR_LAST_LOGGED_IN_FINGERPRINT,
1874 userInfo.lastLoggedInFingerprint);
1875 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001876 if (userInfo.iconPath != null) {
1877 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
1878 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001879 if (userInfo.partial) {
1880 serializer.attribute(null, ATTR_PARTIAL, "true");
1881 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001882 if (userInfo.guestToRemove) {
1883 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
1884 }
Kenny Guy2a764942014-04-02 13:29:20 +01001885 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
1886 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
1887 Integer.toString(userInfo.profileGroupId));
Kenny Guya52dc3e2014-02-11 15:33:14 +00001888 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001889 if (userInfo.restrictedProfileParentId != UserInfo.NO_PROFILE_GROUP_ID) {
1890 serializer.attribute(null, ATTR_RESTRICTED_PROFILE_PARENT_ID,
1891 Integer.toString(userInfo.restrictedProfileParentId));
1892 }
Amith Yamasani12747872015-12-07 14:19:49 -08001893 // Write seed data
1894 if (userData.persistSeedData) {
1895 if (userData.seedAccountName != null) {
1896 serializer.attribute(null, ATTR_SEED_ACCOUNT_NAME, userData.seedAccountName);
1897 }
1898 if (userData.seedAccountType != null) {
1899 serializer.attribute(null, ATTR_SEED_ACCOUNT_TYPE, userData.seedAccountType);
1900 }
1901 }
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001902 if (userInfo.name != null) {
1903 serializer.startTag(null, TAG_NAME);
1904 serializer.text(userInfo.name);
1905 serializer.endTag(null, TAG_NAME);
1906 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001907 synchronized (mRestrictionsLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001908 UserRestrictionsUtils.writeRestrictions(serializer,
1909 mBaseUserRestrictions.get(userInfo.id), TAG_RESTRICTIONS);
1910 UserRestrictionsUtils.writeRestrictions(serializer,
1911 mDevicePolicyLocalUserRestrictions.get(userInfo.id),
1912 TAG_DEVICE_POLICY_RESTRICTIONS);
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001913 }
Amith Yamasani12747872015-12-07 14:19:49 -08001914
1915 if (userData.account != null) {
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001916 serializer.startTag(null, TAG_ACCOUNT);
Amith Yamasani12747872015-12-07 14:19:49 -08001917 serializer.text(userData.account);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001918 serializer.endTag(null, TAG_ACCOUNT);
1919 }
1920
Amith Yamasani12747872015-12-07 14:19:49 -08001921 if (userData.persistSeedData && userData.seedAccountOptions != null) {
1922 serializer.startTag(null, TAG_SEED_ACCOUNT_OPTIONS);
1923 userData.seedAccountOptions.saveToXml(serializer);
1924 serializer.endTag(null, TAG_SEED_ACCOUNT_OPTIONS);
1925 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001926 serializer.endTag(null, TAG_USER);
1927
1928 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001929 userFile.finishWrite(fos);
1930 } catch (Exception ioe) {
Jeff Sharkeycd575992016-03-29 14:12:49 -06001931 Slog.e(LOG_TAG, "Error writing user info " + userData.info.id, ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -07001932 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001933 }
1934 }
1935
1936 /*
1937 * Writes the user list file in this format:
1938 *
Amith Yamasani2a003292012-08-14 18:25:45 -07001939 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001940 * <user id="0"></user>
1941 * <user id="2"></user>
1942 * </users>
1943 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001944 private void writeUserListLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001945 if (DBG) {
1946 debug("writeUserList");
1947 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001948 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001949 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001950 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001951 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001952 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1953
1954 // XmlSerializer serializer = XmlUtils.serializerInstance();
1955 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001956 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001957 serializer.startDocument(null, true);
1958 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1959
1960 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -07001961 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -07001962 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001963
Adam Lesinskieddeb492014-09-08 17:50:03 -07001964 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001965 synchronized (mGuestRestrictions) {
1966 UserRestrictionsUtils
1967 .writeRestrictions(serializer, mGuestRestrictions, TAG_RESTRICTIONS);
1968 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301969 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001970 synchronized (mRestrictionsLock) {
1971 UserRestrictionsUtils.writeRestrictions(serializer,
1972 mDevicePolicyGlobalUserRestrictions, TAG_DEVICE_POLICY_RESTRICTIONS);
1973 }
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001974 serializer.startTag(null, TAG_GLOBAL_RESTRICTION_OWNER_ID);
1975 serializer.attribute(null, ATTR_ID, Integer.toString(mGlobalRestrictionOwnerUserId));
1976 serializer.endTag(null, TAG_GLOBAL_RESTRICTION_OWNER_ID);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001977 int[] userIdsToWrite;
1978 synchronized (mUsersLock) {
1979 userIdsToWrite = new int[mUsers.size()];
1980 for (int i = 0; i < userIdsToWrite.length; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001981 UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001982 userIdsToWrite[i] = user.id;
1983 }
1984 }
1985 for (int id : userIdsToWrite) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001986 serializer.startTag(null, TAG_USER);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001987 serializer.attribute(null, ATTR_ID, Integer.toString(id));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001988 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001989 }
1990
1991 serializer.endTag(null, TAG_USERS);
1992
1993 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001994 userListFile.finishWrite(fos);
1995 } catch (Exception e) {
1996 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -07001997 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001998 }
1999 }
2000
Amith Yamasani12747872015-12-07 14:19:49 -08002001 private UserData readUserLP(int id) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002002 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -07002003 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002004 String name = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -08002005 String account = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002006 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -07002007 long creationTime = 0L;
2008 long lastLoggedInTime = 0L;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002009 String lastLoggedInFingerprint = null;
Kenny Guy2a764942014-04-02 13:29:20 +01002010 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002011 int restrictedProfileParentId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002012 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -07002013 boolean guestToRemove = false;
Amith Yamasani12747872015-12-07 14:19:49 -08002014 boolean persistSeedData = false;
2015 String seedAccountName = null;
2016 String seedAccountType = null;
2017 PersistableBundle seedAccountOptions = null;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002018 Bundle baseRestrictions = new Bundle();
2019 Bundle localRestrictions = new Bundle();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002020
2021 FileInputStream fis = null;
2022 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07002023 AtomicFile userFile =
Amith Yamasanifc95e702013-09-26 13:20:17 -07002024 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
Amith Yamasani2a003292012-08-14 18:25:45 -07002025 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002026 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002027 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002028 int type;
2029 while ((type = parser.next()) != XmlPullParser.START_TAG
2030 && type != XmlPullParser.END_DOCUMENT) {
Amith Yamasani12747872015-12-07 14:19:49 -08002031 // Skip
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002032 }
2033
2034 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07002035 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002036 return null;
2037 }
2038
2039 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -07002040 int storedId = readIntAttribute(parser, ATTR_ID, -1);
2041 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -07002042 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002043 return null;
2044 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002045 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
2046 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002047 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -07002048 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
2049 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002050 lastLoggedInFingerprint = parser.getAttributeValue(null,
2051 ATTR_LAST_LOGGED_IN_FINGERPRINT);
Kenny Guy2a764942014-04-02 13:29:20 +01002052 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
2053 UserInfo.NO_PROFILE_GROUP_ID);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002054 restrictedProfileParentId = readIntAttribute(parser,
2055 ATTR_RESTRICTED_PROFILE_PARENT_ID, UserInfo.NO_PROFILE_GROUP_ID);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002056 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
2057 if ("true".equals(valueString)) {
2058 partial = true;
2059 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002060 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
2061 if ("true".equals(valueString)) {
2062 guestToRemove = true;
2063 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002064
Amith Yamasani12747872015-12-07 14:19:49 -08002065 seedAccountName = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_NAME);
2066 seedAccountType = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_TYPE);
2067 if (seedAccountName != null || seedAccountType != null) {
2068 persistSeedData = true;
2069 }
2070
Amith Yamasanie4cf7342012-12-17 11:12:09 -08002071 int outerDepth = parser.getDepth();
2072 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2073 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2074 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2075 continue;
2076 }
2077 String tag = parser.getName();
2078 if (TAG_NAME.equals(tag)) {
2079 type = parser.next();
2080 if (type == XmlPullParser.TEXT) {
2081 name = parser.getText();
2082 }
2083 } else if (TAG_RESTRICTIONS.equals(tag)) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002084 UserRestrictionsUtils.readRestrictions(parser, baseRestrictions);
2085 } else if (TAG_DEVICE_POLICY_RESTRICTIONS.equals(tag)) {
2086 UserRestrictionsUtils.readRestrictions(parser, localRestrictions);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08002087 } else if (TAG_ACCOUNT.equals(tag)) {
2088 type = parser.next();
2089 if (type == XmlPullParser.TEXT) {
2090 account = parser.getText();
2091 }
Amith Yamasani12747872015-12-07 14:19:49 -08002092 } else if (TAG_SEED_ACCOUNT_OPTIONS.equals(tag)) {
2093 seedAccountOptions = PersistableBundle.restoreFromXml(parser);
2094 persistSeedData = true;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002095 }
2096 }
2097 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002098
Amith Yamasani12747872015-12-07 14:19:49 -08002099 // Create the UserInfo object that gets passed around
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002100 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -07002101 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -07002102 userInfo.creationTime = creationTime;
2103 userInfo.lastLoggedInTime = lastLoggedInTime;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002104 userInfo.lastLoggedInFingerprint = lastLoggedInFingerprint;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002105 userInfo.partial = partial;
Adam Lesinskieddeb492014-09-08 17:50:03 -07002106 userInfo.guestToRemove = guestToRemove;
Kenny Guy2a764942014-04-02 13:29:20 +01002107 userInfo.profileGroupId = profileGroupId;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002108 userInfo.restrictedProfileParentId = restrictedProfileParentId;
Amith Yamasani12747872015-12-07 14:19:49 -08002109
2110 // Create the UserData object that's internal to this class
2111 UserData userData = new UserData();
2112 userData.info = userInfo;
2113 userData.account = account;
2114 userData.seedAccountName = seedAccountName;
2115 userData.seedAccountType = seedAccountType;
2116 userData.persistSeedData = persistSeedData;
2117 userData.seedAccountOptions = seedAccountOptions;
2118
Makoto Onuki068c54a2015-10-13 14:34:03 -07002119 synchronized (mRestrictionsLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002120 mBaseUserRestrictions.put(id, baseRestrictions);
2121 mDevicePolicyLocalUserRestrictions.put(id, localRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002122 }
Amith Yamasani12747872015-12-07 14:19:49 -08002123 return userData;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002124 } catch (IOException ioe) {
2125 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08002126 } finally {
2127 if (fis != null) {
2128 try {
2129 fis.close();
2130 } catch (IOException e) {
2131 }
2132 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002133 }
2134 return null;
2135 }
2136
Amith Yamasani920ace02012-09-20 22:15:37 -07002137 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
2138 String valueString = parser.getAttributeValue(null, attr);
2139 if (valueString == null) return defaultValue;
2140 try {
2141 return Integer.parseInt(valueString);
2142 } catch (NumberFormatException nfe) {
2143 return defaultValue;
2144 }
2145 }
2146
2147 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
2148 String valueString = parser.getAttributeValue(null, attr);
2149 if (valueString == null) return defaultValue;
2150 try {
2151 return Long.parseLong(valueString);
2152 } catch (NumberFormatException nfe) {
2153 return defaultValue;
2154 }
2155 }
2156
Amith Yamasanib82add22013-07-09 11:24:44 -07002157 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002158 * Removes the app restrictions file for a specific package and user id, if it exists.
2159 */
2160 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
2161 synchronized (mPackagesLock) {
2162 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07002163 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002164 if (resFile.exists()) {
2165 resFile.delete();
2166 }
2167 }
2168 }
2169
Kenny Guya52dc3e2014-02-11 15:33:14 +00002170 @Override
Kenny Guy2a764942014-04-02 13:29:20 +01002171 public UserInfo createProfileForUser(String name, int flags, int userId) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002172 checkManageOrCreateUsersPermission(flags);
Kenny Guy2a764942014-04-02 13:29:20 +01002173 return createUserInternal(name, flags, userId);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002174 }
2175
Amith Yamasani258848d2012-08-10 17:06:33 -07002176 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07002177 public UserInfo createUser(String name, int flags) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002178 checkManageOrCreateUsersPermission(flags);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00002179 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002180 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07002181
Jessica Hummelbe81c802014-04-22 15:49:22 +01002182 private UserInfo createUserInternal(String name, int flags, int parentId) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002183 if (hasUserRestriction(UserManager.DISALLOW_ADD_USER, UserHandle.getCallingUserId())) {
Julia Reynolds75175022014-06-26 16:35:00 -04002184 Log.w(LOG_TAG, "Cannot add user. DISALLOW_ADD_USER is enabled.");
2185 return null;
2186 }
phweisse9c44062016-02-10 12:57:38 +01002187 return createUserInternalUnchecked(name, flags, parentId);
2188 }
2189
2190 private UserInfo createUserInternalUnchecked(String name, int flags, int parentId) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07002191 if (ActivityManager.isLowRamDeviceStatic()) {
2192 return null;
2193 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07002194 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Nicolas Prevot12678a92015-05-13 12:15:03 -07002195 final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002196 final boolean isRestricted = (flags & UserInfo.FLAG_RESTRICTED) != 0;
Amith Yamasani52c21e32016-05-31 09:12:20 -07002197 final boolean isDemo = (flags & UserInfo.FLAG_DEMO) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002198 final long ident = Binder.clearCallingIdentity();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002199 UserInfo userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08002200 UserData userData;
Amith Yamasanibb054c92015-07-09 14:16:27 -07002201 final int userId;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002202 try {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002203 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002204 UserData parent = null;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002205 if (parentId != UserHandle.USER_NULL) {
2206 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002207 parent = getUserDataLU(parentId);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00002208 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002209 if (parent == null) return null;
2210 }
2211 if (isManagedProfile && !canAddMoreManagedProfiles(parentId, false)) {
2212 Log.e(LOG_TAG, "Cannot add more managed profiles for user " + parentId);
2213 return null;
2214 }
Amith Yamasani52c21e32016-05-31 09:12:20 -07002215 if (!isGuest && !isManagedProfile && !isDemo && isUserLimitReached()) {
2216 // If we're not adding a guest/demo user or a managed profile and the limit has
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002217 // been reached, cannot add a user.
2218 return null;
2219 }
2220 // If we're adding a guest and there already exists one, bail.
2221 if (isGuest && findCurrentGuestUser() != null) {
2222 return null;
2223 }
2224 // In legacy mode, restricted profile's parent can only be the owner user
2225 if (isRestricted && !UserManager.isSplitSystemUser()
2226 && (parentId != UserHandle.USER_SYSTEM)) {
2227 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
2228 return null;
2229 }
2230 if (isRestricted && UserManager.isSplitSystemUser()) {
2231 if (parent == null) {
2232 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be "
2233 + "specified");
Nicolas Prevot12678a92015-05-13 12:15:03 -07002234 return null;
2235 }
Amith Yamasani12747872015-12-07 14:19:49 -08002236 if (!parent.info.canHaveProfile()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002237 Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be "
2238 + "created for the specified parent user id " + parentId);
Amith Yamasani95ab7842014-08-11 17:09:26 -07002239 return null;
2240 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002241 }
Suprabh Shuklacc30b0e72016-05-20 14:41:22 -07002242 if (!UserManager.isSplitSystemUser() && (flags & UserInfo.FLAG_EPHEMERAL) != 0
2243 && (flags & UserInfo.FLAG_DEMO) == 0) {
Lenka Trochtova024f9792016-02-17 13:55:17 +01002244 Log.e(LOG_TAG,
2245 "Ephemeral users are supported on split-system-user systems only.");
2246 return null;
2247 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002248 // In split system user mode, we assign the first human user the primary flag.
2249 // And if there is no device owner, we also assign the admin flag to primary user.
2250 if (UserManager.isSplitSystemUser()
2251 && !isGuest && !isManagedProfile && getPrimaryUser() == null) {
2252 flags |= UserInfo.FLAG_PRIMARY;
Makoto Onukie7927da2015-11-25 10:05:17 -08002253 synchronized (mUsersLock) {
2254 if (!mIsDeviceManaged) {
2255 flags |= UserInfo.FLAG_ADMIN;
2256 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07002257 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002258 }
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002259
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002260 userId = getNextAvailableId();
2261 Environment.getUserSystemDirectory(userId).mkdirs();
Lenka Trochtova02fee152015-12-22 14:26:18 +01002262 boolean ephemeralGuests = Resources.getSystem()
2263 .getBoolean(com.android.internal.R.bool.config_guestUserEphemeral);
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002264
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002265 synchronized (mUsersLock) {
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002266 // Add ephemeral flag to guests/users if required. Also inherit it from parent.
2267 if ((isGuest && ephemeralGuests) || mForceEphemeralUsers
2268 || (parent != null && parent.info.isEphemeral())) {
2269 flags |= UserInfo.FLAG_EPHEMERAL;
2270 }
2271
2272 userInfo = new UserInfo(userId, name, null, flags);
2273 userInfo.serialNumber = mNextSerialNumber++;
2274 long now = System.currentTimeMillis();
2275 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
2276 userInfo.partial = true;
Fyodor Kupolov83c24242016-03-31 13:30:42 -07002277 userInfo.lastLoggedInFingerprint = Build.FINGERPRINT;
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002278 userData = new UserData();
2279 userData.info = userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08002280 mUsers.put(userId, userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002281 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06002282 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002283 writeUserListLP();
2284 if (parent != null) {
2285 if (isManagedProfile) {
Amith Yamasani12747872015-12-07 14:19:49 -08002286 if (parent.info.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
2287 parent.info.profileGroupId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002288 writeUserLP(parent);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002289 }
Amith Yamasani12747872015-12-07 14:19:49 -08002290 userInfo.profileGroupId = parent.info.profileGroupId;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002291 } else if (isRestricted) {
Amith Yamasani12747872015-12-07 14:19:49 -08002292 if (parent.info.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) {
2293 parent.info.restrictedProfileParentId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002294 writeUserLP(parent);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002295 }
Amith Yamasani12747872015-12-07 14:19:49 -08002296 userInfo.restrictedProfileParentId = parent.info.restrictedProfileParentId;
Makoto Onuki068c54a2015-10-13 14:34:03 -07002297 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002298 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07002299 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002300 final StorageManager storage = mContext.getSystemService(StorageManager.class);
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002301 storage.createUserKey(userId, userInfo.serialNumber, userInfo.isEphemeral());
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002302 mPm.prepareUserData(userId, userInfo.serialNumber,
Jeff Sharkey47f71082016-02-01 17:03:54 -07002303 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002304 mPm.createNewUser(userId);
2305 userInfo.partial = false;
2306 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002307 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002308 }
2309 updateUserIds();
2310 Bundle restrictions = new Bundle();
Fyodor Kupolove04462c2015-11-30 15:02:53 -08002311 if (isGuest) {
2312 synchronized (mGuestRestrictions) {
2313 restrictions.putAll(mGuestRestrictions);
2314 }
2315 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002316 synchronized (mRestrictionsLock) {
2317 mBaseUserRestrictions.append(userId, restrictions);
2318 }
Fyodor Kupolov5fd967d2016-07-12 14:46:19 -07002319 mPm.onNewUserCreated(userId);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002320 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
2321 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
2322 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
2323 android.Manifest.permission.MANAGE_USERS);
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -08002324 MetricsLogger.count(mContext, isGuest ? TRON_GUEST_CREATED : TRON_USER_CREATED, 1);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002325 } finally {
2326 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07002327 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002328 return userInfo;
2329 }
2330
Amith Yamasani0b285492011-04-14 17:35:23 -07002331 /**
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002332 * @hide
2333 */
Amith Yamasani12747872015-12-07 14:19:49 -08002334 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002335 public UserInfo createRestrictedProfile(String name, int parentUserId) {
Sudheer Shanka53d41472016-06-16 09:11:08 -07002336 checkManageOrCreateUsersPermission("setupRestrictedProfile");
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002337 final UserInfo user = createProfileForUser(name, UserInfo.FLAG_RESTRICTED, parentUserId);
2338 if (user == null) {
2339 return null;
2340 }
Fyodor Kupolov9e912ba2016-02-09 18:29:43 -08002341 long identity = Binder.clearCallingIdentity();
2342 try {
2343 setUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, true, user.id);
2344 // Change the setting before applying the DISALLOW_SHARE_LOCATION restriction, otherwise
2345 // the putIntForUser() will fail.
2346 android.provider.Settings.Secure.putIntForUser(mContext.getContentResolver(),
2347 android.provider.Settings.Secure.LOCATION_MODE,
2348 android.provider.Settings.Secure.LOCATION_MODE_OFF, user.id);
2349 setUserRestriction(UserManager.DISALLOW_SHARE_LOCATION, true, user.id);
2350 } finally {
2351 Binder.restoreCallingIdentity(identity);
2352 }
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002353 return user;
2354 }
2355
2356 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07002357 * Find the current guest user. If the Guest user is partial,
2358 * then do not include it in the results as it is about to die.
Adam Lesinskieddeb492014-09-08 17:50:03 -07002359 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002360 private UserInfo findCurrentGuestUser() {
2361 synchronized (mUsersLock) {
2362 final int size = mUsers.size();
2363 for (int i = 0; i < size; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002364 final UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002365 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
2366 return user;
2367 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002368 }
2369 }
2370 return null;
2371 }
2372
2373 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07002374 * Mark this guest user for deletion to allow us to create another guest
2375 * and switch to that user before actually removing this guest.
2376 * @param userHandle the userid of the current guest
2377 * @return whether the user could be marked for deletion
2378 */
Amith Yamasani12747872015-12-07 14:19:49 -08002379 @Override
Amith Yamasani1df14732014-08-29 21:37:27 -07002380 public boolean markGuestForDeletion(int userHandle) {
2381 checkManageUsersPermission("Only the system can remove users");
2382 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
2383 UserManager.DISALLOW_REMOVE_USER, false)) {
2384 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
2385 return false;
2386 }
2387
2388 long ident = Binder.clearCallingIdentity();
2389 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002390 final UserData userData;
Amith Yamasani1df14732014-08-29 21:37:27 -07002391 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002392 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002393 userData = mUsers.get(userHandle);
2394 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002395 return false;
2396 }
Amith Yamasani1df14732014-08-29 21:37:27 -07002397 }
Amith Yamasani12747872015-12-07 14:19:49 -08002398 if (!userData.info.isGuest()) {
Amith Yamasani1df14732014-08-29 21:37:27 -07002399 return false;
2400 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002401 // We set this to a guest user that is to be removed. This is a temporary state
2402 // where we are allowed to add new Guest users, even if this one is still not
2403 // removed. This user will still show up in getUserInfo() calls.
2404 // If we don't get around to removing this Guest user, it will be purged on next
2405 // startup.
Amith Yamasani12747872015-12-07 14:19:49 -08002406 userData.info.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07002407 // Mark it as disabled, so that it isn't returned any more when
2408 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002409 userData.info.flags |= UserInfo.FLAG_DISABLED;
2410 writeUserLP(userData);
Amith Yamasani1df14732014-08-29 21:37:27 -07002411 }
2412 } finally {
2413 Binder.restoreCallingIdentity(ident);
2414 }
2415 return true;
2416 }
2417
2418 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002419 * Removes a user and all data directories created for that user. This method should be called
2420 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07002421 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07002422 */
Amith Yamasani12747872015-12-07 14:19:49 -08002423 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -07002424 public boolean removeUser(int userHandle) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002425 checkManageOrCreateUsersPermission("Only the system can remove users");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04002426 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
2427 UserManager.DISALLOW_REMOVE_USER, false)) {
2428 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
2429 return false;
2430 }
2431
Kenny Guyee58b4f2014-05-23 15:19:53 +01002432 long ident = Binder.clearCallingIdentity();
2433 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002434 final UserData userData;
Fyodor Kupolov0df68cd2015-10-01 13:54:22 -07002435 int currentUser = ActivityManager.getCurrentUser();
2436 if (currentUser == userHandle) {
2437 Log.w(LOG_TAG, "Current user cannot be removed");
2438 return false;
2439 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002440 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002441 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002442 userData = mUsers.get(userHandle);
2443 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002444 return false;
2445 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002446
Fyodor Kupolov82402752015-10-28 14:54:51 -07002447 // We remember deleted user IDs to prevent them from being
2448 // reused during the current boot; they can still be reused
2449 // after a reboot.
2450 mRemovingUserIds.put(userHandle, true);
2451 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002452
Kenny Guyee58b4f2014-05-23 15:19:53 +01002453 try {
2454 mAppOpsService.removeUser(userHandle);
2455 } catch (RemoteException e) {
2456 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
2457 }
2458 // Set this to a partially created user, so that the user will be purged
2459 // on next startup, in case the runtime stops now before stopping and
2460 // removing the user completely.
Amith Yamasani12747872015-12-07 14:19:49 -08002461 userData.info.partial = true;
Kenny Guyee58b4f2014-05-23 15:19:53 +01002462 // Mark it as disabled, so that it isn't returned any more when
2463 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002464 userData.info.flags |= UserInfo.FLAG_DISABLED;
2465 writeUserLP(userData);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002466 }
2467
Amith Yamasani12747872015-12-07 14:19:49 -08002468 if (userData.info.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
2469 && userData.info.isManagedProfile()) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002470 // Send broadcast to notify system that the user removed was a
2471 // managed user.
Amith Yamasani12747872015-12-07 14:19:49 -08002472 sendProfileRemovedBroadcast(userData.info.profileGroupId, userData.info.id);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002473 }
2474
2475 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
2476 int res;
2477 try {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07002478 res = ActivityManagerNative.getDefault().stopUser(userHandle, /* force= */ true,
2479 new IStopUserCallback.Stub() {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002480 @Override
2481 public void userStopped(int userId) {
2482 finishRemoveUser(userId);
2483 }
2484 @Override
2485 public void userStopAborted(int userId) {
2486 }
2487 });
2488 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002489 return false;
2490 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002491 return res == ActivityManager.USER_OP_SUCCESS;
2492 } finally {
2493 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002494 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002495 }
2496
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002497 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07002498 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002499 // Let other services shutdown any activity and clean up their state before completely
2500 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002501 long ident = Binder.clearCallingIdentity();
2502 try {
2503 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
2504 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002505 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
2506 android.Manifest.permission.MANAGE_USERS,
2507
2508 new BroadcastReceiver() {
2509 @Override
2510 public void onReceive(Context context, Intent intent) {
2511 if (DBG) {
2512 Slog.i(LOG_TAG,
2513 "USER_REMOVED broadcast sent, cleaning up user data "
2514 + userHandle);
2515 }
2516 new Thread() {
Amith Yamasani12747872015-12-07 14:19:49 -08002517 @Override
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002518 public void run() {
Amith Yamasani515d4062015-09-28 11:30:06 -07002519 // Clean up any ActivityManager state
2520 LocalServices.getService(ActivityManagerInternal.class)
2521 .onUserRemoved(userHandle);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002522 removeUserState(userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002523 }
2524 }.start();
2525 }
2526 },
2527
2528 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002529 } finally {
2530 Binder.restoreCallingIdentity(ident);
2531 }
Amith Yamasani2a003292012-08-14 18:25:45 -07002532 }
2533
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002534 private void removeUserState(final int userHandle) {
Paul Crowley91293792016-03-25 15:23:07 -07002535 try {
2536 mContext.getSystemService(StorageManager.class).destroyUserKey(userHandle);
2537 } catch (IllegalStateException e) {
2538 // This may be simply because the user was partially created.
2539 Slog.i(LOG_TAG,
2540 "Destroying key for user " + userHandle + " failed, continuing anyway", e);
2541 }
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002542
Amith Yamasanid04aaa32016-06-13 12:09:36 -07002543 // Cleanup gatekeeper secure user id
2544 try {
2545 final IGateKeeperService gk = GateKeeper.getService();
2546 if (gk != null) {
2547 gk.clearSecureUserId(userHandle);
2548 }
2549 } catch (Exception ex) {
2550 Slog.w(LOG_TAG, "unable to clear GK secure user id");
2551 }
2552
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002553 // Cleanup package manager settings
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002554 mPm.cleanUpUser(this, userHandle);
Amith Yamasanid04aaa32016-06-13 12:09:36 -07002555
2556 // Clean up all data before removing metadata
2557 mPm.destroyUserData(userHandle,
2558 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2559
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002560 // Remove this user from the list
Fyodor Kupolov82402752015-10-28 14:54:51 -07002561 synchronized (mUsersLock) {
2562 mUsers.remove(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08002563 mIsUserManaged.delete(userHandle);
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00002564 }
2565 synchronized (mUserStates) {
2566 mUserStates.delete(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08002567 }
2568 synchronized (mRestrictionsLock) {
2569 mBaseUserRestrictions.remove(userHandle);
2570 mAppliedUserRestrictions.remove(userHandle);
2571 mCachedEffectiveUserRestrictions.remove(userHandle);
2572 mDevicePolicyLocalUserRestrictions.remove(userHandle);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002573 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002574 // Update the user list
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002575 synchronized (mPackagesLock) {
2576 writeUserListLP();
2577 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06002578 // Remove user file
2579 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
2580 userFile.delete();
Fyodor Kupolov82402752015-10-28 14:54:51 -07002581 updateUserIds();
Amith Yamasani61f57372012-08-31 12:12:28 -07002582 }
2583
Kenny Guyf8d3a232014-05-15 16:09:52 +01002584 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01002585 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01002586 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
2587 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002588 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
Jeff Sharkeyaf6ec292015-12-17 11:19:00 -07002589 managedProfileIntent.putExtra(Intent.EXTRA_USER_HANDLE, removedUserId);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002590 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01002591 }
2592
Amith Yamasani2a003292012-08-14 18:25:45 -07002593 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002594 public Bundle getApplicationRestrictions(String packageName) {
2595 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
2596 }
2597
2598 @Override
2599 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002600 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07002601 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00002602 checkSystemOrRoot("get application restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002603 }
2604 synchronized (mPackagesLock) {
2605 // Read the restrictions from XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07002606 return readApplicationRestrictionsLP(packageName, userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002607 }
2608 }
2609
2610 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002611 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002612 int userId) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00002613 checkSystemOrRoot("set application restrictions");
Fyodor Kupolov0d88d542016-04-19 11:37:22 -07002614 if (restrictions != null) {
2615 restrictions.setDefusable(true);
2616 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002617 synchronized (mPackagesLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01002618 if (restrictions == null || restrictions.isEmpty()) {
2619 cleanAppRestrictionsForPackage(packageName, userId);
2620 } else {
2621 // Write the restrictions to XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07002622 writeApplicationRestrictionsLP(packageName, restrictions, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01002623 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002624 }
Robin Lee66e5d962014-04-09 16:44:21 +01002625
Fyodor Kupolovd2846122016-02-11 18:06:34 -08002626 // Notify package of changes via an intent - only sent to explicitly registered receivers.
2627 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
2628 changeIntent.setPackage(packageName);
2629 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
2630 mContext.sendBroadcastAsUser(changeIntent, UserHandle.of(userId));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002631 }
2632
2633 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07002634 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002635 try {
2636 return mContext.getPackageManager().getApplicationInfo(packageName,
Fyodor Kupolovd2846122016-02-11 18:06:34 -08002637 PackageManager.MATCH_UNINSTALLED_PACKAGES).uid;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002638 } catch (NameNotFoundException nnfe) {
2639 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07002640 } finally {
2641 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002642 }
2643 }
2644
Fyodor Kupolov82402752015-10-28 14:54:51 -07002645 private Bundle readApplicationRestrictionsLP(String packageName, int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002646 AtomicFile restrictionsFile =
2647 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
2648 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002649 return readApplicationRestrictionsLP(restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002650 }
2651
2652 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002653 static Bundle readApplicationRestrictionsLP(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002654 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002655 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002656 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07002657 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002658 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002659
2660 FileInputStream fis = null;
2661 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002662 fis = restrictionsFile.openRead();
2663 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002664 parser.setInput(fis, StandardCharsets.UTF_8.name());
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002665 XmlUtils.nextElement(parser);
2666 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002667 Slog.e(LOG_TAG, "Unable to read restrictions file "
2668 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002669 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002670 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002671 while (parser.next() != XmlPullParser.END_DOCUMENT) {
2672 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002673 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002674 } catch (IOException|XmlPullParserException e) {
2675 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002676 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002677 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002678 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002679 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002680 }
2681
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002682 private static void readEntry(Bundle restrictions, ArrayList<String> values,
2683 XmlPullParser parser) throws XmlPullParserException, IOException {
2684 int type = parser.getEventType();
2685 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
2686 String key = parser.getAttributeValue(null, ATTR_KEY);
2687 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
2688 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
2689 if (multiple != null) {
2690 values.clear();
2691 int count = Integer.parseInt(multiple);
2692 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
2693 if (type == XmlPullParser.START_TAG
2694 && parser.getName().equals(TAG_VALUE)) {
2695 values.add(parser.nextText().trim());
2696 count--;
2697 }
2698 }
2699 String [] valueStrings = new String[values.size()];
2700 values.toArray(valueStrings);
2701 restrictions.putStringArray(key, valueStrings);
2702 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
2703 restrictions.putBundle(key, readBundleEntry(parser, values));
2704 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
2705 final int outerDepth = parser.getDepth();
2706 ArrayList<Bundle> bundleList = new ArrayList<>();
2707 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2708 Bundle childBundle = readBundleEntry(parser, values);
2709 bundleList.add(childBundle);
2710 }
2711 restrictions.putParcelableArray(key,
2712 bundleList.toArray(new Bundle[bundleList.size()]));
2713 } else {
2714 String value = parser.nextText().trim();
2715 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
2716 restrictions.putBoolean(key, Boolean.parseBoolean(value));
2717 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
2718 restrictions.putInt(key, Integer.parseInt(value));
2719 } else {
2720 restrictions.putString(key, value);
2721 }
2722 }
2723 }
2724 }
2725
2726 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
2727 throws IOException, XmlPullParserException {
2728 Bundle childBundle = new Bundle();
2729 final int outerDepth = parser.getDepth();
2730 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2731 readEntry(childBundle, values, parser);
2732 }
2733 return childBundle;
2734 }
2735
Fyodor Kupolov82402752015-10-28 14:54:51 -07002736 private void writeApplicationRestrictionsLP(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002737 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002738 AtomicFile restrictionsFile = new AtomicFile(
2739 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07002740 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002741 writeApplicationRestrictionsLP(restrictions, restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002742 }
2743
2744 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002745 static void writeApplicationRestrictionsLP(Bundle restrictions, AtomicFile restrictionsFile) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002746 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002747 try {
2748 fos = restrictionsFile.startWrite();
2749 final BufferedOutputStream bos = new BufferedOutputStream(fos);
2750
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002751 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002752 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002753 serializer.startDocument(null, true);
2754 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2755
2756 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002757 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002758 serializer.endTag(null, TAG_RESTRICTIONS);
2759
2760 serializer.endDocument();
2761 restrictionsFile.finishWrite(fos);
2762 } catch (Exception e) {
2763 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002764 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
2765 }
2766 }
2767
2768 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
2769 throws IOException {
2770 for (String key : restrictions.keySet()) {
2771 Object value = restrictions.get(key);
2772 serializer.startTag(null, TAG_ENTRY);
2773 serializer.attribute(null, ATTR_KEY, key);
2774
2775 if (value instanceof Boolean) {
2776 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
2777 serializer.text(value.toString());
2778 } else if (value instanceof Integer) {
2779 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
2780 serializer.text(value.toString());
2781 } else if (value == null || value instanceof String) {
2782 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
2783 serializer.text(value != null ? (String) value : "");
2784 } else if (value instanceof Bundle) {
2785 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2786 writeBundle((Bundle) value, serializer);
2787 } else if (value instanceof Parcelable[]) {
2788 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
2789 Parcelable[] array = (Parcelable[]) value;
2790 for (Parcelable parcelable : array) {
2791 if (!(parcelable instanceof Bundle)) {
2792 throw new IllegalArgumentException("bundle-array can only hold Bundles");
2793 }
2794 serializer.startTag(null, TAG_ENTRY);
2795 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2796 writeBundle((Bundle) parcelable, serializer);
2797 serializer.endTag(null, TAG_ENTRY);
2798 }
2799 } else {
2800 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
2801 String[] values = (String[]) value;
2802 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
2803 for (String choice : values) {
2804 serializer.startTag(null, TAG_VALUE);
2805 serializer.text(choice != null ? choice : "");
2806 serializer.endTag(null, TAG_VALUE);
2807 }
2808 }
2809 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002810 }
2811 }
2812
2813 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07002814 public int getUserSerialNumber(int userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002815 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002816 if (!exists(userHandle)) return -1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002817 return getUserInfoLU(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07002818 }
2819 }
2820
2821 @Override
2822 public int getUserHandle(int userSerialNumber) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002823 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002824 for (int userId : mUserIds) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002825 UserInfo info = getUserInfoLU(userId);
Kenny Guy945f8832015-02-10 15:17:26 +00002826 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07002827 }
2828 // Not found
2829 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07002830 }
2831 }
2832
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002833 @Override
2834 public long getUserCreationTime(int userHandle) {
2835 int callingUserId = UserHandle.getCallingUserId();
2836 UserInfo userInfo = null;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002837 synchronized (mUsersLock) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002838 if (callingUserId == userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002839 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002840 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002841 UserInfo parent = getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002842 if (parent != null && parent.id == callingUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002843 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002844 }
2845 }
2846 }
2847 if (userInfo == null) {
2848 throw new SecurityException("userHandle can only be the calling user or a managed "
2849 + "profile associated with this user");
2850 }
2851 return userInfo.creationTime;
2852 }
2853
Amith Yamasani0b285492011-04-14 17:35:23 -07002854 /**
2855 * Caches the list of user ids in an array, adjusting the array size when necessary.
2856 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002857 private void updateUserIds() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002858 int num = 0;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002859 synchronized (mUsersLock) {
2860 final int userSize = mUsers.size();
2861 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002862 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002863 num++;
2864 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002865 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002866 final int[] newUsers = new int[num];
2867 int n = 0;
2868 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002869 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002870 newUsers[n++] = mUsers.keyAt(i);
2871 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002872 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002873 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07002874 }
2875 }
2876
2877 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002878 * Called right before a user is started. This gives us a chance to prepare
2879 * app storage and apply any user restrictions.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002880 */
2881 public void onBeforeStartUser(int userId) {
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07002882 UserInfo userInfo = getUserInfo(userId);
2883 if (userInfo == null) {
2884 return;
2885 }
2886 final int userSerial = userInfo.serialNumber;
2887 // Migrate only if build fingerprints mismatch
2888 boolean migrateAppsData = !Build.FINGERPRINT.equals(userInfo.lastLoggedInFingerprint);
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002889 mPm.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_DE);
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07002890 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_DE, migrateAppsData);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002891
2892 if (userId != UserHandle.USER_SYSTEM) {
2893 synchronized (mRestrictionsLock) {
2894 applyUserRestrictionsLR(userId);
2895 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002896 }
Amith Yamasanieb437d42016-04-29 09:31:25 -07002897
2898 maybeInitializeDemoMode(userId);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002899 }
2900
2901 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002902 * Called right before a user is unlocked. This gives us a chance to prepare
2903 * app storage.
2904 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002905 public void onBeforeUnlockUser(@UserIdInt int userId) {
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07002906 UserInfo userInfo = getUserInfo(userId);
2907 if (userInfo == null) {
2908 return;
2909 }
2910 final int userSerial = userInfo.serialNumber;
2911 // Migrate only if build fingerprints mismatch
2912 boolean migrateAppsData = !Build.FINGERPRINT.equals(userInfo.lastLoggedInFingerprint);
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002913 mPm.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_CE);
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07002914 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_CE, migrateAppsData);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002915 }
2916
2917 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002918 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasanieb437d42016-04-29 09:31:25 -07002919 * This is called with ActivityManagerService lock held.
Amith Yamasani920ace02012-09-20 22:15:37 -07002920 * @param userId the user that was just foregrounded
2921 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002922 public void onUserLoggedIn(@UserIdInt int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -08002923 UserData userData = getUserDataNoChecks(userId);
2924 if (userData == null || userData.info.partial) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002925 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
2926 return;
2927 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002928
2929 final long now = System.currentTimeMillis();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002930 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani12747872015-12-07 14:19:49 -08002931 userData.info.lastLoggedInTime = now;
Amith Yamasani920ace02012-09-20 22:15:37 -07002932 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002933 userData.info.lastLoggedInFingerprint = Build.FINGERPRINT;
2934 scheduleWriteUser(userData);
Amith Yamasani920ace02012-09-20 22:15:37 -07002935 }
2936
Amith Yamasanieb437d42016-04-29 09:31:25 -07002937 private void maybeInitializeDemoMode(int userId) {
Suprabh Shukla0271fd62016-06-27 18:56:23 -07002938 if (UserManager.isDeviceInDemoMode(mContext) && userId != UserHandle.USER_SYSTEM) {
Amith Yamasanieb437d42016-04-29 09:31:25 -07002939 String demoLauncher =
2940 mContext.getResources().getString(
2941 com.android.internal.R.string.config_demoModeLauncherComponent);
2942 if (!TextUtils.isEmpty(demoLauncher)) {
2943 ComponentName componentToEnable = ComponentName.unflattenFromString(demoLauncher);
Sudheer Shanka194e4152016-07-06 17:49:37 -07002944 String demoLauncherPkg = componentToEnable.getPackageName();
Amith Yamasanieb437d42016-04-29 09:31:25 -07002945 try {
Sudheer Shanka194e4152016-07-06 17:49:37 -07002946 final IPackageManager iPm = AppGlobals.getPackageManager();
2947 iPm.setComponentEnabledSetting(componentToEnable,
Amith Yamasanieb437d42016-04-29 09:31:25 -07002948 PackageManager.COMPONENT_ENABLED_STATE_ENABLED, /* flags= */ 0,
2949 /* userId= */ userId);
Sudheer Shanka194e4152016-07-06 17:49:37 -07002950 iPm.setApplicationEnabledSetting(demoLauncherPkg,
2951 PackageManager.COMPONENT_ENABLED_STATE_ENABLED, /* flags= */ 0,
2952 /* userId= */ userId, null);
Amith Yamasanieb437d42016-04-29 09:31:25 -07002953 } catch (RemoteException re) {
2954 // Internal, shouldn't happen
2955 }
2956 }
2957 }
2958 }
2959
Amith Yamasani920ace02012-09-20 22:15:37 -07002960 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002961 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani742a6712011-05-04 14:49:28 -07002962 * TODO: May not be a good idea to recycle ids, in case it results in confusion
2963 * for data and battery stats collection, or unexpected cross-talk.
Amith Yamasani0b285492011-04-14 17:35:23 -07002964 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002965 private int getNextAvailableId() {
2966 synchronized (mUsersLock) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002967 int i = MIN_USER_ID;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002968 while (i < MAX_USER_ID) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002969 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002970 return i;
Amith Yamasani195263742012-08-21 15:40:12 -07002971 }
2972 i++;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002973 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002974 }
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002975 throw new IllegalStateException("No user id available!");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002976 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002977
Amith Yamasanifc95e702013-09-26 13:20:17 -07002978 private String packageToRestrictionsFileName(String packageName) {
2979 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
2980 }
2981
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002982 /**
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002983 * Enforce that serial number stored in user directory inode matches the
2984 * given expected value. Gracefully sets the serial number if currently
2985 * undefined.
2986 *
2987 * @throws IOException when problem extracting serial number, or serial
2988 * number is mismatched.
2989 */
2990 public static void enforceSerialNumber(File file, int serialNumber) throws IOException {
Jeff Sharkeya52c9d92016-06-27 17:27:43 -06002991 if (StorageManager.isFileEncryptedEmulatedOnly()) {
2992 // When we're emulating FBE, the directory may have been chmod
2993 // 000'ed, meaning we can't read the serial number to enforce it;
2994 // instead of destroying the user, just log a warning.
2995 Slog.w(LOG_TAG, "Device is emulating FBE; assuming current serial number is valid");
2996 return;
2997 }
2998
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002999 final int foundSerial = getSerialNumber(file);
3000 Slog.v(LOG_TAG, "Found " + file + " with serial number " + foundSerial);
3001
3002 if (foundSerial == -1) {
3003 Slog.d(LOG_TAG, "Serial number missing on " + file + "; assuming current is valid");
3004 try {
3005 setSerialNumber(file, serialNumber);
3006 } catch (IOException e) {
3007 Slog.w(LOG_TAG, "Failed to set serial number on " + file, e);
3008 }
3009
3010 } else if (foundSerial != serialNumber) {
3011 throw new IOException("Found serial number " + foundSerial
3012 + " doesn't match expected " + serialNumber);
3013 }
3014 }
3015
3016 /**
3017 * Set serial number stored in user directory inode.
3018 *
3019 * @throws IOException if serial number was already set
3020 */
3021 private static void setSerialNumber(File file, int serialNumber)
3022 throws IOException {
3023 try {
3024 final byte[] buf = Integer.toString(serialNumber).getBytes(StandardCharsets.UTF_8);
3025 Os.setxattr(file.getAbsolutePath(), XATTR_SERIAL, buf, OsConstants.XATTR_CREATE);
3026 } catch (ErrnoException e) {
3027 throw e.rethrowAsIOException();
3028 }
3029 }
3030
3031 /**
3032 * Return serial number stored in user directory inode.
3033 *
3034 * @return parsed serial number, or -1 if not set
3035 */
3036 private static int getSerialNumber(File file) throws IOException {
3037 try {
3038 final byte[] buf = new byte[256];
3039 final int len = Os.getxattr(file.getAbsolutePath(), XATTR_SERIAL, buf);
3040 final String serial = new String(buf, 0, len);
3041 try {
3042 return Integer.parseInt(serial);
3043 } catch (NumberFormatException e) {
3044 throw new IOException("Bad serial number: " + serial);
3045 }
3046 } catch (ErrnoException e) {
3047 if (e.errno == OsConstants.ENODATA) {
3048 return -1;
3049 } else {
3050 throw e.rethrowAsIOException();
3051 }
3052 }
3053 }
3054
Amith Yamasani920ace02012-09-20 22:15:37 -07003055 @Override
Amith Yamasani12747872015-12-07 14:19:49 -08003056 public void setSeedAccountData(int userId, String accountName, String accountType,
3057 PersistableBundle accountOptions, boolean persist) {
3058 checkManageUsersPermission("Require MANAGE_USERS permission to set user seed data");
3059 synchronized (mPackagesLock) {
3060 final UserData userData;
3061 synchronized (mUsersLock) {
3062 userData = getUserDataLU(userId);
3063 if (userData == null) {
3064 Slog.e(LOG_TAG, "No such user for settings seed data u=" + userId);
3065 return;
3066 }
3067 userData.seedAccountName = accountName;
3068 userData.seedAccountType = accountType;
3069 userData.seedAccountOptions = accountOptions;
3070 userData.persistSeedData = persist;
3071 }
3072 if (persist) {
3073 writeUserLP(userData);
3074 }
3075 }
3076 }
3077
3078 @Override
3079 public String getSeedAccountName() throws RemoteException {
3080 checkManageUsersPermission("Cannot get seed account information");
3081 synchronized (mUsersLock) {
3082 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3083 return userData.seedAccountName;
3084 }
3085 }
3086
3087 @Override
3088 public String getSeedAccountType() throws RemoteException {
3089 checkManageUsersPermission("Cannot get seed account information");
3090 synchronized (mUsersLock) {
3091 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3092 return userData.seedAccountType;
3093 }
3094 }
3095
3096 @Override
3097 public PersistableBundle getSeedAccountOptions() throws RemoteException {
3098 checkManageUsersPermission("Cannot get seed account information");
3099 synchronized (mUsersLock) {
3100 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3101 return userData.seedAccountOptions;
3102 }
3103 }
3104
3105 @Override
3106 public void clearSeedAccountData() throws RemoteException {
3107 checkManageUsersPermission("Cannot clear seed account information");
3108 synchronized (mPackagesLock) {
3109 UserData userData;
3110 synchronized (mUsersLock) {
3111 userData = getUserDataLU(UserHandle.getCallingUserId());
3112 if (userData == null) return;
3113 userData.clearSeedAccountData();
3114 }
3115 writeUserLP(userData);
3116 }
3117 }
3118
3119 @Override
3120 public boolean someUserHasSeedAccount(String accountName, String accountType)
3121 throws RemoteException {
3122 checkManageUsersPermission("Cannot check seed account information");
3123 synchronized (mUsersLock) {
3124 final int userSize = mUsers.size();
3125 for (int i = 0; i < userSize; i++) {
3126 final UserData data = mUsers.valueAt(i);
3127 if (data.info.isInitialized()) continue;
3128 if (data.seedAccountName == null || !data.seedAccountName.equals(accountName)) {
3129 continue;
3130 }
3131 if (data.seedAccountType == null || !data.seedAccountType.equals(accountType)) {
3132 continue;
3133 }
3134 return true;
3135 }
3136 }
3137 return false;
3138 }
3139
3140 @Override
Todd Kennedy60459ab2015-10-30 11:32:16 -07003141 public void onShellCommand(FileDescriptor in, FileDescriptor out,
3142 FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
3143 (new Shell()).exec(this, in, out, err, args, resultReceiver);
3144 }
3145
3146 int onShellCommand(Shell shell, String cmd) {
3147 if (cmd == null) {
3148 return shell.handleDefaultCommands(cmd);
3149 }
3150
3151 final PrintWriter pw = shell.getOutPrintWriter();
3152 try {
3153 switch(cmd) {
3154 case "list":
3155 return runList(pw);
3156 }
3157 } catch (RemoteException e) {
3158 pw.println("Remote exception: " + e);
3159 }
3160 return -1;
3161 }
3162
3163 private int runList(PrintWriter pw) throws RemoteException {
3164 final IActivityManager am = ActivityManagerNative.getDefault();
3165 final List<UserInfo> users = getUsers(false);
3166 if (users == null) {
3167 pw.println("Error: couldn't get users");
3168 return 1;
3169 } else {
3170 pw.println("Users:");
3171 for (int i = 0; i < users.size(); i++) {
Jeff Sharkeye17ac152015-11-06 22:40:29 -08003172 String running = am.isUserRunning(users.get(i).id, 0) ? " running" : "";
Todd Kennedy60459ab2015-10-30 11:32:16 -07003173 pw.println("\t" + users.get(i).toString() + running);
3174 }
3175 return 0;
3176 }
3177 }
3178
3179 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -07003180 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
3181 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
3182 != PackageManager.PERMISSION_GRANTED) {
3183 pw.println("Permission Denial: can't dump UserManager from from pid="
3184 + Binder.getCallingPid()
3185 + ", uid=" + Binder.getCallingUid()
3186 + " without permission "
3187 + android.Manifest.permission.DUMP);
3188 return;
3189 }
3190
3191 long now = System.currentTimeMillis();
3192 StringBuilder sb = new StringBuilder();
3193 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003194 synchronized (mUsersLock) {
3195 pw.println("Users:");
3196 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003197 UserData userData = mUsers.valueAt(i);
3198 if (userData == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003199 continue;
3200 }
Amith Yamasani12747872015-12-07 14:19:49 -08003201 UserInfo userInfo = userData.info;
3202 final int userId = userInfo.id;
3203 pw.print(" "); pw.print(userInfo);
3204 pw.print(" serialNo="); pw.print(userInfo.serialNumber);
Makoto Onukie7927da2015-11-25 10:05:17 -08003205 if (mRemovingUserIds.get(userId)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003206 pw.print(" <removing> ");
3207 }
Amith Yamasani12747872015-12-07 14:19:49 -08003208 if (userInfo.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003209 pw.print(" <partial>");
3210 }
3211 pw.println();
3212 pw.print(" Created: ");
Amith Yamasani12747872015-12-07 14:19:49 -08003213 if (userInfo.creationTime == 0) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003214 pw.println("<unknown>");
3215 } else {
3216 sb.setLength(0);
Amith Yamasani12747872015-12-07 14:19:49 -08003217 TimeUtils.formatDuration(now - userInfo.creationTime, sb);
Fyodor Kupolov82402752015-10-28 14:54:51 -07003218 sb.append(" ago");
3219 pw.println(sb);
3220 }
3221 pw.print(" Last logged in: ");
Amith Yamasani12747872015-12-07 14:19:49 -08003222 if (userInfo.lastLoggedInTime == 0) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003223 pw.println("<unknown>");
3224 } else {
3225 sb.setLength(0);
Amith Yamasani12747872015-12-07 14:19:49 -08003226 TimeUtils.formatDuration(now - userInfo.lastLoggedInTime, sb);
Fyodor Kupolov82402752015-10-28 14:54:51 -07003227 sb.append(" ago");
3228 pw.println(sb);
3229 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003230 pw.print(" Last logged in fingerprint: ");
3231 pw.println(userInfo.lastLoggedInFingerprint);
Makoto Onukie7927da2015-11-25 10:05:17 -08003232 pw.print(" Has profile owner: ");
3233 pw.println(mIsUserManaged.get(userId));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003234 pw.println(" Restrictions:");
3235 synchronized (mRestrictionsLock) {
3236 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003237 pw, " ", mBaseUserRestrictions.get(userInfo.id));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003238 pw.println(" Device policy local restrictions:");
3239 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003240 pw, " ", mDevicePolicyLocalUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003241 pw.println(" Effective restrictions:");
3242 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003243 pw, " ", mCachedEffectiveUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003244 }
Amith Yamasani12747872015-12-07 14:19:49 -08003245
3246 if (userData.account != null) {
3247 pw.print(" Account name: " + userData.account);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08003248 pw.println();
3249 }
Amith Yamasani12747872015-12-07 14:19:49 -08003250
3251 if (userData.seedAccountName != null) {
3252 pw.print(" Seed account name: " + userData.seedAccountName);
3253 pw.println();
3254 if (userData.seedAccountType != null) {
3255 pw.print(" account type: " + userData.seedAccountType);
3256 pw.println();
3257 }
3258 if (userData.seedAccountOptions != null) {
3259 pw.print(" account options exist");
3260 pw.println();
3261 }
3262 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003263 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003264 }
Amith Yamasani12747872015-12-07 14:19:49 -08003265 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003266 pw.println(" Device policy global restrictions:");
3267 synchronized (mRestrictionsLock) {
3268 UserRestrictionsUtils
3269 .dumpRestrictions(pw, " ", mDevicePolicyGlobalUserRestrictions);
3270 }
Makoto Onukia4f11972015-10-01 13:19:58 -07003271 pw.println();
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01003272 pw.println(" Global restrictions owner id:" + mGlobalRestrictionOwnerUserId);
3273 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003274 pw.println(" Guest restrictions:");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003275 synchronized (mGuestRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003276 UserRestrictionsUtils.dumpRestrictions(pw, " ", mGuestRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003277 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003278 synchronized (mUsersLock) {
3279 pw.println();
3280 pw.println(" Device managed: " + mIsDeviceManaged);
3281 }
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003282 synchronized (mUserStates) {
3283 pw.println(" Started users state: " + mUserStates);
3284 }
Amith Yamasani12747872015-12-07 14:19:49 -08003285 // Dump some capabilities
3286 pw.println();
3287 pw.println(" Max users: " + UserManager.getMaxSupportedUsers());
3288 pw.println(" Supports switchable users: " + UserManager.supportsMultipleUsers());
Lenka Trochtova02fee152015-12-22 14:26:18 +01003289 pw.println(" All guests ephemeral: " + Resources.getSystem().getBoolean(
3290 com.android.internal.R.bool.config_guestUserEphemeral));
Amith Yamasani920ace02012-09-20 22:15:37 -07003291 }
3292 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08003293
3294 final class MainHandler extends Handler {
3295
3296 @Override
3297 public void handleMessage(Message msg) {
3298 switch (msg.what) {
3299 case WRITE_USER_MSG:
3300 removeMessages(WRITE_USER_MSG, msg.obj);
3301 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08003302 int userId = ((UserData) msg.obj).info.id;
3303 UserData userData = getUserDataNoChecks(userId);
3304 if (userData != null) {
3305 writeUserLP(userData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08003306 }
3307 }
3308 }
3309 }
3310 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07003311
3312 /**
3313 * @param userId
3314 * @return whether the user has been initialized yet
3315 */
3316 boolean isInitialized(int userId) {
3317 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
3318 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003319
3320 private class LocalService extends UserManagerInternal {
Makoto Onuki068c54a2015-10-13 14:34:03 -07003321 @Override
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003322 public void setDevicePolicyUserRestrictions(int userId, @NonNull Bundle localRestrictions,
3323 @Nullable Bundle globalRestrictions) {
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08003324 UserManagerService.this.setDevicePolicyUserRestrictionsInner(userId, localRestrictions,
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003325 globalRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003326 }
3327
3328 @Override
3329 public Bundle getBaseUserRestrictions(int userId) {
3330 synchronized (mRestrictionsLock) {
3331 return mBaseUserRestrictions.get(userId);
3332 }
3333 }
3334
3335 @Override
3336 public void setBaseUserRestrictionsByDpmsForMigration(
3337 int userId, Bundle baseRestrictions) {
3338 synchronized (mRestrictionsLock) {
3339 mBaseUserRestrictions.put(userId, new Bundle(baseRestrictions));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003340 invalidateEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003341 }
3342
Amith Yamasani12747872015-12-07 14:19:49 -08003343 final UserData userData = getUserDataNoChecks(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003344 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08003345 if (userData != null) {
3346 writeUserLP(userData);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003347 } else {
3348 Slog.w(LOG_TAG, "UserInfo not found for " + userId);
3349 }
3350 }
3351 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08003352
3353 @Override
3354 public boolean getUserRestriction(int userId, String key) {
3355 return getUserRestrictions(userId).getBoolean(key);
3356 }
3357
3358 @Override
3359 public void addUserRestrictionsListener(UserRestrictionsListener listener) {
3360 synchronized (mUserRestrictionsListeners) {
3361 mUserRestrictionsListeners.add(listener);
3362 }
3363 }
3364
3365 @Override
3366 public void removeUserRestrictionsListener(UserRestrictionsListener listener) {
3367 synchronized (mUserRestrictionsListeners) {
3368 mUserRestrictionsListeners.remove(listener);
3369 }
3370 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003371
3372 @Override
3373 public void setDeviceManaged(boolean isManaged) {
3374 synchronized (mUsersLock) {
3375 mIsDeviceManaged = isManaged;
3376 }
3377 }
3378
3379 @Override
3380 public void setUserManaged(int userId, boolean isManaged) {
3381 synchronized (mUsersLock) {
3382 mIsUserManaged.put(userId, isManaged);
3383 }
3384 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01003385
3386 @Override
3387 public void setUserIcon(int userId, Bitmap bitmap) {
3388 long ident = Binder.clearCallingIdentity();
3389 try {
3390 synchronized (mPackagesLock) {
3391 UserData userData = getUserDataNoChecks(userId);
3392 if (userData == null || userData.info.partial) {
3393 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
3394 return;
3395 }
3396 writeBitmapLP(userData.info, bitmap);
3397 writeUserLP(userData);
3398 }
3399 sendUserInfoChangedBroadcast(userId);
3400 } finally {
3401 Binder.restoreCallingIdentity(ident);
3402 }
3403 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01003404
3405 @Override
3406 public void setForceEphemeralUsers(boolean forceEphemeralUsers) {
3407 synchronized (mUsersLock) {
3408 mForceEphemeralUsers = forceEphemeralUsers;
3409 }
3410 }
3411
3412 @Override
3413 public void removeAllUsers() {
3414 if (UserHandle.USER_SYSTEM == ActivityManager.getCurrentUser()) {
3415 // Remove the non-system users straight away.
3416 removeNonSystemUsers();
3417 } else {
3418 // Switch to the system user first and then remove the other users.
3419 BroadcastReceiver userSwitchedReceiver = new BroadcastReceiver() {
3420 @Override
3421 public void onReceive(Context context, Intent intent) {
3422 int userId =
3423 intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3424 if (userId != UserHandle.USER_SYSTEM) {
3425 return;
3426 }
3427 mContext.unregisterReceiver(this);
3428 removeNonSystemUsers();
3429 }
3430 };
3431 IntentFilter userSwitchedFilter = new IntentFilter();
3432 userSwitchedFilter.addAction(Intent.ACTION_USER_SWITCHED);
3433 mContext.registerReceiver(
3434 userSwitchedReceiver, userSwitchedFilter, null, mHandler);
3435
3436 // Switch to the system user.
3437 ActivityManager am =
3438 (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
3439 am.switchUser(UserHandle.USER_SYSTEM);
3440 }
3441 }
phweisse9c44062016-02-10 12:57:38 +01003442
3443 @Override
Lenka Trochtova1ddda472016-02-12 10:42:12 +01003444 public void onEphemeralUserStop(int userId) {
3445 synchronized (mUsersLock) {
3446 UserInfo userInfo = getUserInfoLU(userId);
3447 if (userInfo != null && userInfo.isEphemeral()) {
3448 // Do not allow switching back to the ephemeral user again as the user is going
3449 // to be deleted.
3450 userInfo.flags |= UserInfo.FLAG_DISABLED;
3451 if (userInfo.isGuest()) {
3452 // Indicate that the guest will be deleted after it stops.
3453 userInfo.guestToRemove = true;
3454 }
3455 }
3456 }
3457 }
3458
3459 @Override
phweisse9c44062016-02-10 12:57:38 +01003460 public UserInfo createUserEvenWhenDisallowed(String name, int flags) {
3461 UserInfo user = createUserInternalUnchecked(name, flags, UserHandle.USER_NULL);
3462 // Keep this in sync with UserManager.createUser
3463 if (user != null && !user.isAdmin()) {
3464 setUserRestriction(UserManager.DISALLOW_SMS, true, user.id);
3465 setUserRestriction(UserManager.DISALLOW_OUTGOING_CALLS, true, user.id);
3466 }
3467 return user;
3468 }
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003469
3470 @Override
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003471 public boolean isUserRunning(int userId) {
3472 synchronized (mUserStates) {
3473 return mUserStates.get(userId, -1) >= 0;
3474 }
3475 }
3476
3477 @Override
3478 public void setUserState(int userId, int userState) {
3479 synchronized (mUserStates) {
3480 mUserStates.put(userId, userState);
3481 }
3482 }
3483
3484 @Override
3485 public void removeUserState(int userId) {
3486 synchronized (mUserStates) {
3487 mUserStates.delete(userId);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003488 }
3489 }
3490
3491 @Override
3492 public boolean isUserUnlockingOrUnlocked(int userId) {
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003493 synchronized (mUserStates) {
3494 int state = mUserStates.get(userId, -1);
3495 return (state == UserState.STATE_RUNNING_UNLOCKING)
3496 || (state == UserState.STATE_RUNNING_UNLOCKED);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003497 }
3498 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01003499 }
3500
3501 /* Remove all the users except of the system one. */
3502 private void removeNonSystemUsers() {
3503 ArrayList<UserInfo> usersToRemove = new ArrayList<>();
3504 synchronized (mUsersLock) {
3505 final int userSize = mUsers.size();
3506 for (int i = 0; i < userSize; i++) {
3507 UserInfo ui = mUsers.valueAt(i).info;
3508 if (ui.id != UserHandle.USER_SYSTEM) {
3509 usersToRemove.add(ui);
3510 }
3511 }
3512 }
3513 for (UserInfo ui: usersToRemove) {
3514 removeUser(ui.id);
3515 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003516 }
Todd Kennedy60459ab2015-10-30 11:32:16 -07003517
3518 private class Shell extends ShellCommand {
3519 @Override
3520 public int onCommand(String cmd) {
3521 return onShellCommand(this, cmd);
3522 }
3523
3524 @Override
3525 public void onHelp() {
3526 final PrintWriter pw = getOutPrintWriter();
3527 pw.println("User manager (user) commands:");
3528 pw.println(" help");
3529 pw.println(" Print this help text.");
3530 pw.println("");
3531 pw.println(" list");
3532 pw.println(" Prints all users on the system.");
3533 }
3534 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003535
3536 private static void debug(String message) {
3537 Log.d(LOG_TAG, message +
3538 (DBG_WITH_STACKTRACE ? " called at\n" + Debug.getCallers(10, " ") : ""));
3539 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003540}