blob: 2ccb6c172a28f5eb21dceb8b32ca535edacbad56 [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;
Andrew Scull85a63bc2016-10-24 13:47:47 +010029import android.app.ActivityManagerNative;
Todd Kennedy60459ab2015-10-30 11:32:16 -070030import android.app.IActivityManager;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070031import android.app.IStopUserCallback;
Benjamin Franzf02420c2016-04-04 18:52:21 +010032import android.app.KeyguardManager;
Ricky Waib1dd80b2016-06-07 18:00:55 +010033import android.app.PendingIntent;
arangelov9b632d72018-12-07 23:21:22 +000034import android.app.admin.DevicePolicyEventLogger;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070035import android.content.BroadcastReceiver;
Amith Yamasani258848d2012-08-10 17:06:33 -070036import android.content.Context;
37import android.content.Intent;
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +010038import android.content.IntentFilter;
Benjamin Franzf02420c2016-04-04 18:52:21 +010039import android.content.IntentSender;
Amith Yamasani0b285492011-04-14 17:35:23 -070040import android.content.pm.PackageManager;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -080041import android.content.pm.PackageManager.NameNotFoundException;
Tony Make3d1f652017-12-12 11:00:37 +000042import android.content.pm.ShortcutServiceInternal;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070043import android.content.pm.UserInfo;
Lenka Trochtova02fee152015-12-22 14:26:18 +010044import android.content.res.Resources;
Amith Yamasanie928d7d2012-09-17 21:46:51 -070045import android.graphics.Bitmap;
Amith Yamasani258848d2012-08-10 17:06:33 -070046import android.os.Binder;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -060047import android.os.Build;
Amith Yamasanie4cf7342012-12-17 11:12:09 -080048import android.os.Bundle;
Makoto Onuki1a2cd742015-11-16 13:51:27 -080049import android.os.Debug;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070050import android.os.Environment;
51import android.os.FileUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080052import android.os.Handler;
Svet Ganov9cea80cd2016-02-16 11:47:00 -080053import android.os.IBinder;
Tony Mak64fd8c02017-12-01 19:11:59 +000054import android.os.IProgressListener;
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;
Dianne Hackborn354736e2016-08-22 17:00:05 -070065import android.os.ShellCallback;
Todd Kennedy60459ab2015-10-30 11:32:16 -070066import android.os.ShellCommand;
Makoto Onuki73dded22017-12-20 13:14:48 +090067import android.os.SystemClock;
Kenny Guy02c89902016-11-15 19:36:38 +000068import android.os.SystemProperties;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070069import android.os.UserHandle;
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070070import android.os.UserManager;
Pavel Grafov6a40f092016-10-25 15:46:51 +010071import android.os.UserManager.EnforcingUser;
Makoto Onuki068c54a2015-10-13 14:34:03 -070072import android.os.UserManagerInternal;
Makoto Onukid45a4a22015-11-02 17:17:38 -080073import android.os.UserManagerInternal.UserRestrictionsListener;
Paul Crowley85e4e812015-05-19 12:42:00 +010074import android.os.storage.StorageManager;
Amith Yamasanid04aaa32016-06-13 12:09:36 -070075import android.security.GateKeeper;
76import android.service.gatekeeper.IGateKeeperService;
arangelov9b632d72018-12-07 23:21:22 +000077import android.stats.devicepolicy.DevicePolicyEnums;
Bookatz75f0a072019-08-05 14:12:16 -070078import android.util.ArraySet;
Amith Yamasani2a003292012-08-14 18:25:45 -070079import android.util.AtomicFile;
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -070080import android.util.IntArray;
Amith Yamasani655d0e22013-06-12 14:19:10 -070081import android.util.Log;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070082import android.util.Slog;
83import android.util.SparseArray;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080084import android.util.SparseBooleanArray;
Amith Yamasaniea1b9d72016-05-27 15:57:38 +000085import android.util.SparseIntArray;
Amith Yamasani920ace02012-09-20 22:15:37 -070086import android.util.TimeUtils;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070087import android.util.Xml;
88
Makoto Onuki068c54a2015-10-13 14:34:03 -070089import com.android.internal.annotations.GuardedBy;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070090import com.android.internal.annotations.VisibleForTesting;
Jason Monk62062992014-05-06 09:55:28 -040091import com.android.internal.app.IAppOpsService;
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -080092import com.android.internal.logging.MetricsLogger;
Fyodor Kupolova68a2862018-01-30 18:22:00 -080093import com.android.internal.os.BackgroundThread;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -060094import com.android.internal.util.DumpUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080095import com.android.internal.util.FastXmlSerializer;
Makoto Onuki068c54a2015-10-13 14:34:03 -070096import com.android.internal.util.Preconditions;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070097import com.android.internal.util.XmlUtils;
Clara Bayarri10ad84a2015-12-01 17:38:05 +000098import com.android.internal.widget.LockPatternUtils;
Amith Yamasani515d4062015-09-28 11:30:06 -070099import com.android.server.LocalServices;
Jeff Sharkey5f3e9342017-03-13 14:53:11 -0600100import com.android.server.LockGuard;
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700101import com.android.server.SystemService;
Amith Yamasaniea1b9d72016-05-27 15:57:38 +0000102import com.android.server.am.UserState;
Suprabh Shuklac5e057c2016-08-08 16:22:44 -0700103import com.android.server.storage.DeviceStorageMonitorInternal;
Felipe Leme3aad1be2019-05-31 11:43:12 -0700104import com.android.server.utils.TimingsTraceAndSlog;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700105import com.android.server.wm.ActivityTaskManagerInternal;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800106
arangelov9b632d72018-12-07 23:21:22 +0000107import libcore.io.IoUtils;
108
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800109import org.xmlpull.v1.XmlPullParser;
110import org.xmlpull.v1.XmlPullParserException;
111import org.xmlpull.v1.XmlSerializer;
112
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700113import java.io.BufferedOutputStream;
114import java.io.File;
Amith Yamasani920ace02012-09-20 22:15:37 -0700115import java.io.FileDescriptor;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700116import java.io.FileInputStream;
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700117import java.io.FileNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700118import java.io.FileOutputStream;
Tony Mak64fd8c02017-12-01 19:11:59 +0000119import java.io.IOException;
Kenny Guy02c89902016-11-15 19:36:38 +0000120import java.io.InputStream;
121import java.io.OutputStream;
Amith Yamasani920ace02012-09-20 22:15:37 -0700122import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100123import java.nio.charset.StandardCharsets;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700124import java.util.ArrayList;
Pavel Grafov6a40f092016-10-25 15:46:51 +0100125import java.util.Collections;
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700126import java.util.LinkedList;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700127import java.util.List;
Narayan Kamath607223f2018-02-19 14:09:02 +0000128import java.util.Objects;
Bookatz75f0a072019-08-05 14:12:16 -0700129import java.util.Set;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700130
Makoto Onuki068c54a2015-10-13 14:34:03 -0700131/**
132 * Service for {@link UserManager}.
133 *
134 * Method naming convention:
Fyodor Kupolov82402752015-10-28 14:54:51 -0700135 * <ul>
Fyodor Kupolovd31cee92017-09-05 16:31:08 -0700136 * <li> Methods suffixed with "LAr" should be called within the {@link #mAppRestrictionsLock} lock.
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800137 * <li> Methods suffixed with "LP" should be called within the {@link #mPackagesLock} lock.
Fyodor Kupolov82402752015-10-28 14:54:51 -0700138 * <li> Methods suffixed with "LR" should be called within the {@link #mRestrictionsLock} lock.
139 * <li> Methods suffixed with "LU" should be called within the {@link #mUsersLock} lock.
140 * </ul>
Makoto Onuki068c54a2015-10-13 14:34:03 -0700141 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700142public class UserManagerService extends IUserManager.Stub {
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700143
Amith Yamasani2a003292012-08-14 18:25:45 -0700144 private static final String LOG_TAG = "UserManagerService";
Makoto Onuki81c61ea2016-01-22 11:22:26 -0800145 static final boolean DBG = false; // DO NOT SUBMIT WITH TRUE
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800146 private static final boolean DBG_WITH_STACKTRACE = false; // DO NOT SUBMIT WITH TRUE
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700147 // Can be used for manual testing of id recycling
148 private static final boolean RELEASE_DELETED_USER_ID = false; // DO NOT SUBMIT WITH TRUE
Amith Yamasani16389312012-10-17 21:20:14 -0700149
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700150 private static final String TAG_NAME = "name";
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800151 private static final String TAG_ACCOUNT = "account";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700152 private static final String ATTR_FLAGS = "flags";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700153 private static final String ATTR_ICON_PATH = "icon";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700154 private static final String ATTR_ID = "id";
Amith Yamasani920ace02012-09-20 22:15:37 -0700155 private static final String ATTR_CREATION_TIME = "created";
156 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -0600157 private static final String ATTR_LAST_LOGGED_IN_FINGERPRINT = "lastLoggedInFingerprint";
Amith Yamasani2a003292012-08-14 18:25:45 -0700158 private static final String ATTR_SERIAL_NO = "serialNumber";
159 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700160 private static final String ATTR_PARTIAL = "partial";
Adam Lesinskieddeb492014-09-08 17:50:03 -0700161 private static final String ATTR_GUEST_TO_REMOVE = "guestToRemove";
Amith Yamasani6f34b412012-10-22 18:19:27 -0700162 private static final String ATTR_USER_VERSION = "version";
Kenny Guy2a764942014-04-02 13:29:20 +0100163 private static final String ATTR_PROFILE_GROUP_ID = "profileGroupId";
Kenny Guy02c89902016-11-15 19:36:38 +0000164 private static final String ATTR_PROFILE_BADGE = "profileBadge";
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700165 private static final String ATTR_RESTRICTED_PROFILE_PARENT_ID = "restrictedProfileParentId";
Amith Yamasani12747872015-12-07 14:19:49 -0800166 private static final String ATTR_SEED_ACCOUNT_NAME = "seedAccountName";
167 private static final String ATTR_SEED_ACCOUNT_TYPE = "seedAccountType";
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530168 private static final String TAG_GUEST_RESTRICTIONS = "guestRestrictions";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700169 private static final String TAG_USERS = "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700170 private static final String TAG_USER = "user";
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800171 private static final String TAG_RESTRICTIONS = "restrictions";
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800172 private static final String TAG_DEVICE_POLICY_RESTRICTIONS = "device_policy_restrictions";
Pavel Grafov6a40f092016-10-25 15:46:51 +0100173 private static final String TAG_DEVICE_POLICY_GLOBAL_RESTRICTIONS =
174 "device_policy_global_restrictions";
175 /** Legacy name for device owner id tag. */
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +0100176 private static final String TAG_GLOBAL_RESTRICTION_OWNER_ID = "globalRestrictionOwnerUserId";
Pavel Grafov6a40f092016-10-25 15:46:51 +0100177 private static final String TAG_DEVICE_OWNER_USER_ID = "deviceOwnerUserId";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800178 private static final String TAG_ENTRY = "entry";
179 private static final String TAG_VALUE = "value";
Amith Yamasani12747872015-12-07 14:19:49 -0800180 private static final String TAG_SEED_ACCOUNT_OPTIONS = "seedAccountOptions";
arangelov9b632d72018-12-07 23:21:22 +0000181 private static final String TAG_LAST_REQUEST_QUIET_MODE_ENABLED_CALL =
182 "lastRequestQuietModeEnabledCall";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800183 private static final String ATTR_KEY = "key";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700184 private static final String ATTR_VALUE_TYPE = "type";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800185 private static final String ATTR_MULTIPLE = "m";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700186
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700187 private static final String ATTR_TYPE_STRING_ARRAY = "sa";
188 private static final String ATTR_TYPE_STRING = "s";
189 private static final String ATTR_TYPE_BOOLEAN = "b";
Amith Yamasani5b5aa402014-06-01 20:10:14 -0700190 private static final String ATTR_TYPE_INTEGER = "i";
Fyodor Kupolov262f9952015-03-23 18:55:11 -0700191 private static final String ATTR_TYPE_BUNDLE = "B";
192 private static final String ATTR_TYPE_BUNDLE_ARRAY = "BA";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700193
Amith Yamasani0b285492011-04-14 17:35:23 -0700194 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700195 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700196 private static final String USER_PHOTO_FILENAME = "photo.png";
Adrian Roos1bdff912015-02-17 15:51:35 +0100197 private static final String USER_PHOTO_FILENAME_TMP = USER_PHOTO_FILENAME + ".tmp";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700198
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800199 private static final String RESTRICTIONS_FILE_PREFIX = "res_";
Amith Yamasanifc95e702013-09-26 13:20:17 -0700200 private static final String XML_SUFFIX = ".xml";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800201
Sudheer Shankaf5cea032016-06-08 17:13:24 -0700202 private static final int ALLOWED_FLAGS_FOR_CREATE_USERS_PERMISSION =
203 UserInfo.FLAG_MANAGED_PROFILE
204 | UserInfo.FLAG_EPHEMERAL
205 | UserInfo.FLAG_RESTRICTED
Sudheer Shanka234d1af2016-08-26 15:42:53 -0700206 | UserInfo.FLAG_GUEST
207 | UserInfo.FLAG_DEMO;
Sudheer Shankaf5cea032016-06-08 17:13:24 -0700208
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700209 @VisibleForTesting
210 static final int MIN_USER_ID = 10;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700211 // We need to keep process uid within Integer.MAX_VALUE.
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700212 @VisibleForTesting
213 static final int MAX_USER_ID = Integer.MAX_VALUE / UserHandle.PER_USER_RANGE;
214
215 // Max size of the queue of recently removed users
216 @VisibleForTesting
217 static final int MAX_RECENTLY_REMOVED_IDS_SIZE = 100;
Amith Yamasani634cf312012-10-04 17:34:21 -0700218
Bookatz75f0a072019-08-05 14:12:16 -0700219 private static final int USER_VERSION = 8;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700220
Amith Yamasani920ace02012-09-20 22:15:37 -0700221 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
222
Nicolas Prevotb8186812015-08-06 15:00:03 +0100223 // Maximum number of managed profiles permitted per user is 1. This cannot be increased
Amith Yamasani95ab7842014-08-11 17:09:26 -0700224 // without first making sure that the rest of the framework is prepared for it.
Kenny Guy02c89902016-11-15 19:36:38 +0000225 @VisibleForTesting
226 static final int MAX_MANAGED_PROFILES = 1;
Amith Yamasani95ab7842014-08-11 17:09:26 -0700227
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800228 static final int WRITE_USER_MSG = 1;
229 static final int WRITE_USER_DELAY = 2*1000; // 2 seconds
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530230
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -0800231 // Tron counters
232 private static final String TRON_GUEST_CREATED = "users_guest_created";
233 private static final String TRON_USER_CREATED = "users_user_created";
Christine Franks88220562017-05-24 11:11:21 -0700234 private static final String TRON_DEMO_CREATED = "users_demo_created";
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -0800235
Dianne Hackborn4428e172012-08-24 17:43:05 -0700236 private final Context mContext;
237 private final PackageManagerService mPm;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700238 private final Object mPackagesLock;
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800239 private final UserDataPreparer mUserDataPreparer;
Fyodor Kupolov82402752015-10-28 14:54:51 -0700240 // Short-term lock for internal state, when interaction/sync with PM is not required
Jeff Sharkey5f3e9342017-03-13 14:53:11 -0600241 private final Object mUsersLock = LockGuard.installNewLock(LockGuard.INDEX_USER);
Fyodor Kupolov82402752015-10-28 14:54:51 -0700242 private final Object mRestrictionsLock = new Object();
Fyodor Kupolovd31cee92017-09-05 16:31:08 -0700243 // Used for serializing access to app restriction files
244 private final Object mAppRestrictionsLock = new Object();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700245
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800246 private final Handler mHandler;
247
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700248 private final File mUsersDir;
249 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700250
Svet Ganov9cea80cd2016-02-16 11:47:00 -0800251 private static final IBinder mUserRestriconToken = new Binder();
252
Makoto Onuki068c54a2015-10-13 14:34:03 -0700253 /**
Makoto Onuki73dded22017-12-20 13:14:48 +0900254 * Internal non-parcelable wrapper for UserInfo that is not exposed to other system apps.
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800255 */
Kenny Guy02c89902016-11-15 19:36:38 +0000256 @VisibleForTesting
257 static class UserData {
Amith Yamasani12747872015-12-07 14:19:49 -0800258 // Basic user information and properties
259 UserInfo info;
260 // Account name used when there is a strong association between a user and an account
261 String account;
262 // Account information for seeding into a newly created user. This could also be
263 // used for login validation for an existing user, for updating their credentials.
264 // In the latter case, data may not need to be persisted as it is only valid for the
265 // current login session.
266 String seedAccountName;
267 String seedAccountType;
268 PersistableBundle seedAccountOptions;
269 // Whether to perist the seed account information to be available after a boot
270 boolean persistSeedData;
271
Makoto Onuki73dded22017-12-20 13:14:48 +0900272 /** Elapsed realtime since boot when the user started. */
273 long startRealtime;
274
275 /** Elapsed realtime since boot when the user was unlocked. */
276 long unlockRealtime;
277
arangelov9b632d72018-12-07 23:21:22 +0000278 private long mLastRequestQuietModeEnabledMillis;
279
280 void setLastRequestQuietModeEnabledMillis(long millis) {
281 mLastRequestQuietModeEnabledMillis = millis;
282 }
283
284 long getLastRequestQuietModeEnabledMillis() {
285 return mLastRequestQuietModeEnabledMillis;
286 }
287
Amith Yamasani12747872015-12-07 14:19:49 -0800288 void clearSeedAccountData() {
289 seedAccountName = null;
290 seedAccountType = null;
291 seedAccountOptions = null;
292 persistSeedData = false;
293 }
294 }
295
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800296 @GuardedBy("mUsersLock")
Amith Yamasani12747872015-12-07 14:19:49 -0800297 private final SparseArray<UserData> mUsers = new SparseArray<>();
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800298
299 /**
Makoto Onuki068c54a2015-10-13 14:34:03 -0700300 * User restrictions set via UserManager. This doesn't include restrictions set by
Pavel Grafov6a40f092016-10-25 15:46:51 +0100301 * device owner / profile owners. Only non-empty restriction bundles are stored.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700302 *
303 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
304 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
305 * maybe shared between {@link #mBaseUserRestrictions} and
306 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
307 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700308 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700309 */
310 @GuardedBy("mRestrictionsLock")
311 private final SparseArray<Bundle> mBaseUserRestrictions = new SparseArray<>();
312
313 /**
314 * Cached user restrictions that are in effect -- i.e. {@link #mBaseUserRestrictions} combined
315 * with device / profile owner restrictions. We'll initialize it lazily; use
316 * {@link #getEffectiveUserRestrictions} to access it.
317 *
318 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
319 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
320 * maybe shared between {@link #mBaseUserRestrictions} and
321 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
322 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700323 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700324 */
325 @GuardedBy("mRestrictionsLock")
326 private final SparseArray<Bundle> mCachedEffectiveUserRestrictions = new SparseArray<>();
327
Makoto Onuki4f160732015-10-27 17:15:38 -0700328 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800329 * User restrictions that have already been applied in
330 * {@link #updateUserRestrictionsInternalLR(Bundle, int)}. We use it to detect restrictions
331 * that have changed since the last
332 * {@link #updateUserRestrictionsInternalLR(Bundle, int)} call.
Makoto Onuki4f160732015-10-27 17:15:38 -0700333 */
334 @GuardedBy("mRestrictionsLock")
335 private final SparseArray<Bundle> mAppliedUserRestrictions = new SparseArray<>();
336
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800337 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800338 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
Pavel Grafov6a40f092016-10-25 15:46:51 +0100339 * that should be applied to all users, including guests. Only non-empty restriction bundles are
340 * stored.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800341 */
342 @GuardedBy("mRestrictionsLock")
Pavel Grafov6a40f092016-10-25 15:46:51 +0100343 private final SparseArray<Bundle> mDevicePolicyGlobalUserRestrictions = new SparseArray<>();
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800344
345 /**
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +0100346 * Id of the user that set global restrictions.
347 */
348 @GuardedBy("mRestrictionsLock")
Pavel Grafov6a40f092016-10-25 15:46:51 +0100349 private int mDeviceOwnerUserId = UserHandle.USER_NULL;
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +0100350
351 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800352 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
Pavel Grafov6a40f092016-10-25 15:46:51 +0100353 * for each user. Only non-empty restriction bundles are stored.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800354 */
355 @GuardedBy("mRestrictionsLock")
356 private final SparseArray<Bundle> mDevicePolicyLocalUserRestrictions = new SparseArray<>();
357
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800358 @GuardedBy("mGuestRestrictions")
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530359 private final Bundle mGuestRestrictions = new Bundle();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800360
361 /**
362 * Set of user IDs being actively removed. Removed IDs linger in this set
363 * for several seconds to work around a VFS caching issue.
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700364 * Use {@link #addRemovingUserIdLocked(int)} to add elements to this array
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800365 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700366 @GuardedBy("mUsersLock")
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800367 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700368
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700369 /**
370 * Queue of recently removed userIds. Used for recycling of userIds
371 */
372 @GuardedBy("mUsersLock")
373 private final LinkedList<Integer> mRecentlyRemovedIds = new LinkedList<>();
374
Fyodor Kupolov82402752015-10-28 14:54:51 -0700375 @GuardedBy("mUsersLock")
Amith Yamasani0b285492011-04-14 17:35:23 -0700376 private int[] mUserIds;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800377 @GuardedBy("mPackagesLock")
Amith Yamasani2a003292012-08-14 18:25:45 -0700378 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700379 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700380
Jason Monk62062992014-05-06 09:55:28 -0400381 private IAppOpsService mAppOpsService;
382
Makoto Onuki068c54a2015-10-13 14:34:03 -0700383 private final LocalService mLocalService;
384
Makoto Onukie7927da2015-11-25 10:05:17 -0800385 @GuardedBy("mUsersLock")
386 private boolean mIsDeviceManaged;
387
388 @GuardedBy("mUsersLock")
389 private final SparseBooleanArray mIsUserManaged = new SparseBooleanArray();
390
Makoto Onukid45a4a22015-11-02 17:17:38 -0800391 @GuardedBy("mUserRestrictionsListeners")
392 private final ArrayList<UserRestrictionsListener> mUserRestrictionsListeners =
393 new ArrayList<>();
394
Clara Bayarria1771112015-12-18 16:29:18 +0000395 private final LockPatternUtils mLockPatternUtils;
396
Ricky Waib1dd80b2016-06-07 18:00:55 +0100397 private final String ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK =
398 "com.android.server.pm.DISABLE_QUIET_MODE_AFTER_UNLOCK";
399
400 private final BroadcastReceiver mDisableQuietModeCallback = new BroadcastReceiver() {
401 @Override
402 public void onReceive(Context context, Intent intent) {
Tony Mak64fd8c02017-12-01 19:11:59 +0000403 if (!ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK.equals(intent.getAction())) {
404 return;
Ricky Waib1dd80b2016-06-07 18:00:55 +0100405 }
Tony Mak64fd8c02017-12-01 19:11:59 +0000406 final IntentSender target = intent.getParcelableExtra(Intent.EXTRA_INTENT);
407 final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_ID, UserHandle.USER_NULL);
Fyodor Kupolova68a2862018-01-30 18:22:00 -0800408 // Call setQuietModeEnabled on bg thread to avoid ANR
arangelov9b632d72018-12-07 23:21:22 +0000409 BackgroundThread.getHandler().post(() ->
410 setQuietModeEnabled(userHandle, false, target, /* callingPackage */ null));
Ricky Waib1dd80b2016-06-07 18:00:55 +0100411 }
412 };
413
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +0100414 /**
Tony Mak64fd8c02017-12-01 19:11:59 +0000415 * Start an {@link IntentSender} when user is unlocked after disabling quiet mode.
416 *
Tony Makbece85d2018-01-12 12:10:17 +0000417 * @see {@link #requestQuietModeEnabled(String, boolean, int, IntentSender)}
Tony Mak64fd8c02017-12-01 19:11:59 +0000418 */
419 private class DisableQuietModeUserUnlockedCallback extends IProgressListener.Stub {
420 private final IntentSender mTarget;
421
422 public DisableQuietModeUserUnlockedCallback(IntentSender target) {
423 Preconditions.checkNotNull(target);
424 mTarget = target;
425 }
426
427 @Override
428 public void onStarted(int id, Bundle extras) {}
429
430 @Override
431 public void onProgress(int id, int progress, Bundle extras) {}
432
433 @Override
434 public void onFinished(int id, Bundle extras) {
435 try {
436 mContext.startIntentSender(mTarget, null, 0, 0, 0);
437 } catch (IntentSender.SendIntentException e) {
438 Slog.e(LOG_TAG, "Failed to start the target in the callback", e);
439 }
440 }
441 }
442
443 /**
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +0100444 * Whether all users should be created ephemeral.
445 */
446 @GuardedBy("mUsersLock")
447 private boolean mForceEphemeralUsers;
448
Amith Yamasaniea1b9d72016-05-27 15:57:38 +0000449 @GuardedBy("mUserStates")
450 private final SparseIntArray mUserStates = new SparseIntArray();
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -0700451
Amith Yamasani258848d2012-08-10 17:06:33 -0700452 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700453
Dianne Hackborn4428e172012-08-24 17:43:05 -0700454 public static UserManagerService getInstance() {
455 synchronized (UserManagerService.class) {
456 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700457 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700458 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700459
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700460 public static class LifeCycle extends SystemService {
461
462 private UserManagerService mUms;
463
464 /**
465 * @param context
466 */
467 public LifeCycle(Context context) {
468 super(context);
469 }
470
471 @Override
472 public void onStart() {
473 mUms = UserManagerService.getInstance();
474 publishBinderService(Context.USER_SERVICE, mUms);
475 }
476
477 @Override
478 public void onBootPhase(int phase) {
479 if (phase == SystemService.PHASE_ACTIVITY_MANAGER_READY) {
480 mUms.cleanupPartialUsers();
481 }
482 }
Makoto Onuki73dded22017-12-20 13:14:48 +0900483
484 @Override
485 public void onStartUser(int userHandle) {
486 synchronized (mUms.mUsersLock) {
487 final UserData user = mUms.getUserDataLU(userHandle);
488 if (user != null) {
489 user.startRealtime = SystemClock.elapsedRealtime();
490 }
491 }
492 }
493
494 @Override
495 public void onUnlockUser(int userHandle) {
496 synchronized (mUms.mUsersLock) {
497 final UserData user = mUms.getUserDataLU(userHandle);
498 if (user != null) {
499 user.unlockRealtime = SystemClock.elapsedRealtime();
500 }
501 }
502 }
503
504 @Override
505 public void onStopUser(int userHandle) {
506 synchronized (mUms.mUsersLock) {
507 final UserData user = mUms.getUserDataLU(userHandle);
508 if (user != null) {
509 user.startRealtime = 0;
510 user.unlockRealtime = 0;
511 }
512 }
513 }
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700514 }
515
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700516 // TODO b/28848102 Add support for test dependencies injection
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800517 @VisibleForTesting
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700518 UserManagerService(Context context) {
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800519 this(context, null, null, new Object(), context.getCacheDir());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700520 }
521
Dianne Hackborn4428e172012-08-24 17:43:05 -0700522 /**
523 * Called by package manager to create the service. This is closely
524 * associated with the package manager, and the given lock is the
525 * package manager's own lock.
526 */
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800527 UserManagerService(Context context, PackageManagerService pm, UserDataPreparer userDataPreparer,
528 Object packagesLock) {
529 this(context, pm, userDataPreparer, packagesLock, Environment.getDataDirectory());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700530 }
531
Dianne Hackborn4428e172012-08-24 17:43:05 -0700532 private UserManagerService(Context context, PackageManagerService pm,
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800533 UserDataPreparer userDataPreparer, Object packagesLock, File dataDir) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700534 mContext = context;
535 mPm = pm;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700536 mPackagesLock = packagesLock;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800537 mHandler = new MainHandler();
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800538 mUserDataPreparer = userDataPreparer;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800539 synchronized (mPackagesLock) {
540 mUsersDir = new File(dataDir, USER_INFO_DIR);
541 mUsersDir.mkdirs();
542 // Make zeroth user directory, for services to migrate their files to that location
543 File userZeroDir = new File(mUsersDir, String.valueOf(UserHandle.USER_SYSTEM));
544 userZeroDir.mkdirs();
545 FileUtils.setPermissions(mUsersDir.toString(),
546 FileUtils.S_IRWXU | FileUtils.S_IRWXG | FileUtils.S_IROTH | FileUtils.S_IXOTH,
547 -1, -1);
548 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
549 initDefaultGuestRestrictions();
550 readUserListLP();
551 sInstance = this;
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700552 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700553 mLocalService = new LocalService();
554 LocalServices.addService(UserManagerInternal.class, mLocalService);
Clara Bayarria1771112015-12-18 16:29:18 +0000555 mLockPatternUtils = new LockPatternUtils(mContext);
Amith Yamasaniea1b9d72016-05-27 15:57:38 +0000556 mUserStates.put(UserHandle.USER_SYSTEM, UserState.STATE_BOOTING);
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700557 }
558
559 void systemReady() {
Jason Monk62062992014-05-06 09:55:28 -0400560 mAppOpsService = IAppOpsService.Stub.asInterface(
561 ServiceManager.getService(Context.APP_OPS_SERVICE));
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800562
563 synchronized (mRestrictionsLock) {
564 applyUserRestrictionsLR(UserHandle.USER_SYSTEM);
Jason Monk62062992014-05-06 09:55:28 -0400565 }
Samuel Tand9453b82016-03-14 15:57:02 -0700566
567 UserInfo currentGuestUser = findCurrentGuestUser();
568 if (currentGuestUser != null && !hasUserRestriction(
569 UserManager.DISALLOW_CONFIG_WIFI, currentGuestUser.id)) {
570 // If a guest user currently exists, apply the DISALLOW_CONFIG_WIFI option
571 // to it, in case this guest was created in a previous version where this
572 // user restriction was not a default guest restriction.
573 setUserRestriction(UserManager.DISALLOW_CONFIG_WIFI, true, currentGuestUser.id);
574 }
Amith Yamasanieb437d42016-04-29 09:31:25 -0700575
Ricky Waib1dd80b2016-06-07 18:00:55 +0100576 mContext.registerReceiver(mDisableQuietModeCallback,
577 new IntentFilter(ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK),
578 null, mHandler);
Amith Yamasani258848d2012-08-10 17:06:33 -0700579 }
580
Patrick Baumann6ae7afc2019-07-30 13:11:28 -0700581 /**
582 * This method retrieves the {@link UserManagerInternal} only for the purpose of
583 * PackageManagerService construction.
584 */
585 UserManagerInternal getInternalForInjectorOnly() {
586 return mLocalService;
587 }
588
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700589 void cleanupPartialUsers() {
590 // Prune out any partially created, partially removed and ephemeral users.
591 ArrayList<UserInfo> partials = new ArrayList<>();
592 synchronized (mUsersLock) {
593 final int userSize = mUsers.size();
594 for (int i = 0; i < userSize; i++) {
595 UserInfo ui = mUsers.valueAt(i).info;
596 if ((ui.partial || ui.guestToRemove || ui.isEphemeral()) && i != 0) {
597 partials.add(ui);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700598 addRemovingUserIdLocked(ui.id);
Amith Yamasaniae261892016-06-27 10:40:09 -0700599 ui.partial = true;
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700600 }
601 }
602 }
603 final int partialsSize = partials.size();
604 for (int i = 0; i < partialsSize; i++) {
605 UserInfo ui = partials.get(i);
606 Slog.w(LOG_TAG, "Removing partially created user " + ui.id
607 + " (name=" + ui.name + ")");
608 removeUserState(ui.id);
609 }
610 }
611
Amith Yamasani258848d2012-08-10 17:06:33 -0700612 @Override
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800613 public String getUserAccount(int userId) {
614 checkManageUserAndAcrossUsersFullPermission("get user account");
615 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800616 return mUsers.get(userId).account;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800617 }
618 }
619
620 @Override
621 public void setUserAccount(int userId, String accountName) {
622 checkManageUserAndAcrossUsersFullPermission("set user account");
Amith Yamasani12747872015-12-07 14:19:49 -0800623 UserData userToUpdate = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800624 synchronized (mPackagesLock) {
625 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800626 final UserData userData = mUsers.get(userId);
627 if (userData == null) {
628 Slog.e(LOG_TAG, "User not found for setting user account: u" + userId);
629 return;
630 }
631 String currentAccount = userData.account;
Narayan Kamath607223f2018-02-19 14:09:02 +0000632 if (!Objects.equals(currentAccount, accountName)) {
Amith Yamasani12747872015-12-07 14:19:49 -0800633 userData.account = accountName;
634 userToUpdate = userData;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800635 }
636 }
637
638 if (userToUpdate != null) {
639 writeUserLP(userToUpdate);
640 }
641 }
642 }
643
644 @Override
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700645 public UserInfo getPrimaryUser() {
646 checkManageUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700647 synchronized (mUsersLock) {
Amith Yamasani515d4062015-09-28 11:30:06 -0700648 final int userSize = mUsers.size();
649 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800650 UserInfo ui = mUsers.valueAt(i).info;
Xiaohui Chend3e9e182015-11-18 13:37:32 -0800651 if (ui.isPrimary() && !mRemovingUserIds.get(ui.id)) {
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700652 return ui;
653 }
654 }
655 }
656 return null;
657 }
658
659 @Override
Xiaohui Chen594f2082015-08-18 11:04:20 -0700660 public @NonNull List<UserInfo> getUsers(boolean excludeDying) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -0700661 checkManageOrCreateUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700662 synchronized (mUsersLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700663 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasani515d4062015-09-28 11:30:06 -0700664 final int userSize = mUsers.size();
665 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800666 UserInfo ui = mUsers.valueAt(i).info;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700667 if (ui.partial) {
668 continue;
669 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800670 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Amith Yamasani6f48d6e2016-03-23 14:28:25 -0700671 users.add(userWithName(ui));
Amith Yamasani920ace02012-09-20 22:15:37 -0700672 }
Amith Yamasani13593602012-03-22 16:16:17 -0700673 }
674 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700675 }
Amith Yamasani13593602012-03-22 16:16:17 -0700676 }
677
Amith Yamasani258848d2012-08-10 17:06:33 -0700678 @Override
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100679 public List<UserInfo> getProfiles(int userId, boolean enabledOnly) {
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700680 boolean returnFullInfo = true;
Amith Yamasani4f582632014-02-19 14:31:52 -0800681 if (userId != UserHandle.getCallingUserId()) {
Sudheer Shanka74680912016-07-29 11:03:37 -0700682 checkManageOrCreateUsersPermission("getting profiles related to user " + userId);
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700683 } else {
684 returnFullInfo = hasManageUsersPermission();
Amith Yamasani4f582632014-02-19 14:31:52 -0800685 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700686 final long ident = Binder.clearCallingIdentity();
687 try {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700688 synchronized (mUsersLock) {
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700689 return getProfilesLU(userId, enabledOnly, returnFullInfo);
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100690 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700691 } finally {
692 Binder.restoreCallingIdentity(ident);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000693 }
694 }
695
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700696 @Override
697 public int[] getProfileIds(int userId, boolean enabledOnly) {
698 if (userId != UserHandle.getCallingUserId()) {
bohu12d23a12016-09-26 16:20:07 -0700699 checkManageOrCreateUsersPermission("getting profiles related to user " + userId);
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700700 }
701 final long ident = Binder.clearCallingIdentity();
702 try {
703 synchronized (mUsersLock) {
704 return getProfileIdsLU(userId, enabledOnly).toArray();
705 }
706 } finally {
707 Binder.restoreCallingIdentity(ident);
708 }
709 }
710
Amith Yamasanibe465322014-04-24 13:45:17 -0700711 /** Assume permissions already checked and caller's identity cleared */
Andreas Gampe2e8c7672018-07-20 13:01:08 -0700712 @GuardedBy("mUsersLock")
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700713 private List<UserInfo> getProfilesLU(int userId, boolean enabledOnly, boolean fullInfo) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700714 IntArray profileIds = getProfileIdsLU(userId, enabledOnly);
715 ArrayList<UserInfo> users = new ArrayList<>(profileIds.size());
716 for (int i = 0; i < profileIds.size(); i++) {
717 int profileId = profileIds.get(i);
718 UserInfo userInfo = mUsers.get(profileId).info;
719 // If full info is not required - clear PII data to prevent 3P apps from reading it
720 if (!fullInfo) {
721 userInfo = new UserInfo(userInfo);
722 userInfo.name = null;
723 userInfo.iconPath = null;
724 } else {
725 userInfo = userWithName(userInfo);
726 }
727 users.add(userInfo);
728 }
729 return users;
730 }
731
732 /**
733 * Assume permissions already checked and caller's identity cleared
734 */
Andreas Gampe2e8c7672018-07-20 13:01:08 -0700735 @GuardedBy("mUsersLock")
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700736 private IntArray getProfileIdsLU(int userId, boolean enabledOnly) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700737 UserInfo user = getUserInfoLU(userId);
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700738 IntArray result = new IntArray(mUsers.size());
Amith Yamasanidda003f2014-08-28 18:06:51 -0700739 if (user == null) {
740 // Probably a dying user
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700741 return result;
Amith Yamasanidda003f2014-08-28 18:06:51 -0700742 }
Amith Yamasani515d4062015-09-28 11:30:06 -0700743 final int userSize = mUsers.size();
744 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800745 UserInfo profile = mUsers.valueAt(i).info;
Amith Yamasanibe465322014-04-24 13:45:17 -0700746 if (!isProfileOf(user, profile)) {
747 continue;
748 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100749 if (enabledOnly && !profile.isEnabled()) {
750 continue;
Amith Yamasanibe465322014-04-24 13:45:17 -0700751 }
Amith Yamasani70fcf0c2014-07-11 08:40:19 -0700752 if (mRemovingUserIds.get(profile.id)) {
753 continue;
754 }
Tony Mak80189cd2016-04-05 17:21:42 +0100755 if (profile.partial) {
756 continue;
757 }
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700758 result.add(profile.id);
Amith Yamasanibe465322014-04-24 13:45:17 -0700759 }
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700760 return result;
Amith Yamasanibe465322014-04-24 13:45:17 -0700761 }
762
Jessica Hummelbe81c802014-04-22 15:49:22 +0100763 @Override
Andres Moralesc5548c02015-08-05 10:23:12 -0700764 public int getCredentialOwnerProfile(int userHandle) {
765 checkManageUsersPermission("get the credential owner");
Clara Bayarria1771112015-12-18 16:29:18 +0000766 if (!mLockPatternUtils.isSeparateProfileChallengeEnabled(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700767 synchronized (mUsersLock) {
768 UserInfo profileParent = getProfileParentLU(userHandle);
Andres Moralesc5548c02015-08-05 10:23:12 -0700769 if (profileParent != null) {
770 return profileParent.id;
771 }
772 }
773 }
774
775 return userHandle;
776 }
777
778 @Override
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700779 public boolean isSameProfileGroup(int userId, int otherUserId) {
780 if (userId == otherUserId) return true;
781 checkManageUsersPermission("check if in the same profile group");
Fyodor Kupolov0fb772e2016-10-13 16:27:34 -0700782 return isSameProfileGroupNoChecks(userId, otherUserId);
783 }
784
785 private boolean isSameProfileGroupNoChecks(int userId, int otherUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700786 synchronized (mUsersLock) {
787 UserInfo userInfo = getUserInfoLU(userId);
788 if (userInfo == null || userInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
789 return false;
790 }
791 UserInfo otherUserInfo = getUserInfoLU(otherUserId);
792 if (otherUserInfo == null
793 || otherUserInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
794 return false;
795 }
796 return userInfo.profileGroupId == otherUserInfo.profileGroupId;
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700797 }
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700798 }
799
800 @Override
Jessica Hummelbe81c802014-04-22 15:49:22 +0100801 public UserInfo getProfileParent(int userHandle) {
802 checkManageUsersPermission("get the profile parent");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700803 synchronized (mUsersLock) {
804 return getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700805 }
806 }
807
Jakub Pawlowski0f1f5b72017-11-15 14:50:43 -0800808 @Override
809 public int getProfileParentId(int userHandle) {
810 checkManageUsersPermission("get the profile parent");
Sunny Goyal145c8f82018-02-15 14:27:09 -0800811 return mLocalService.getProfileParentId(userHandle);
Jakub Pawlowski0f1f5b72017-11-15 14:50:43 -0800812 }
813
Andreas Gampe2e8c7672018-07-20 13:01:08 -0700814 @GuardedBy("mUsersLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -0700815 private UserInfo getProfileParentLU(int userHandle) {
816 UserInfo profile = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700817 if (profile == null) {
818 return null;
819 }
820 int parentUserId = profile.profileGroupId;
Amith Yamasani801e3422017-01-25 11:35:44 -0800821 if (parentUserId == userHandle || parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700822 return null;
823 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700824 return getUserInfoLU(parentUserId);
Jessica Hummelbe81c802014-04-22 15:49:22 +0100825 }
826 }
827
Fyodor Kupolov82402752015-10-28 14:54:51 -0700828 private static boolean isProfileOf(UserInfo user, UserInfo profile) {
Kenny Guy2a764942014-04-02 13:29:20 +0100829 return user.id == profile.id ||
830 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
831 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000832 }
833
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000834 private void broadcastProfileAvailabilityChanges(UserHandle profileHandle,
Rubin Xuf13c9802016-01-21 18:06:00 +0000835 UserHandle parentHandle, boolean inQuietMode) {
Rubin Xue95057a2016-04-01 16:49:25 +0100836 Intent intent = new Intent();
837 if (inQuietMode) {
838 intent.setAction(Intent.ACTION_MANAGED_PROFILE_UNAVAILABLE);
839 } else {
840 intent.setAction(Intent.ACTION_MANAGED_PROFILE_AVAILABLE);
841 }
Rubin Xuf13c9802016-01-21 18:06:00 +0000842 intent.putExtra(Intent.EXTRA_QUIET_MODE, inQuietMode);
843 intent.putExtra(Intent.EXTRA_USER, profileHandle);
844 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileHandle.getIdentifier());
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000845 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Rubin Xuf13c9802016-01-21 18:06:00 +0000846 mContext.sendBroadcastAsUser(intent, parentHandle);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000847 }
848
849 @Override
Tony Makbece85d2018-01-12 12:10:17 +0000850 public boolean requestQuietModeEnabled(@NonNull String callingPackage, boolean enableQuietMode,
Tony Make3d1f652017-12-12 11:00:37 +0000851 int userHandle, @Nullable IntentSender target) {
852 Preconditions.checkNotNull(callingPackage);
853
Tony Makb7e6fd42017-12-05 19:40:28 +0000854 if (enableQuietMode && target != null) {
855 throw new IllegalArgumentException(
856 "target should only be specified when we are disabling quiet mode.");
857 }
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000858
Tony Makd390ae92017-12-28 13:23:10 +0000859 ensureCanModifyQuietMode(callingPackage, Binder.getCallingUid(), target != null);
Tony Makb7e6fd42017-12-05 19:40:28 +0000860 final long identity = Binder.clearCallingIdentity();
861 try {
arangelov9b632d72018-12-07 23:21:22 +0000862 boolean result = false;
Tony Makb7e6fd42017-12-05 19:40:28 +0000863 if (enableQuietMode) {
arangelov9b632d72018-12-07 23:21:22 +0000864 setQuietModeEnabled(
865 userHandle, true /* enableQuietMode */, target, callingPackage);
866 result = true;
Tony Makb7e6fd42017-12-05 19:40:28 +0000867 } else {
868 boolean needToShowConfirmCredential =
869 mLockPatternUtils.isSecure(userHandle)
870 && !StorageManager.isUserKeyUnlocked(userHandle);
871 if (needToShowConfirmCredential) {
872 showConfirmCredentialToDisableQuietMode(userHandle, target);
Tony Makb7e6fd42017-12-05 19:40:28 +0000873 } else {
arangelov9b632d72018-12-07 23:21:22 +0000874 setQuietModeEnabled(
875 userHandle, false /* enableQuietMode */, target, callingPackage);
876 result = true;
Tony Makb7e6fd42017-12-05 19:40:28 +0000877 }
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000878 }
arangelov9b632d72018-12-07 23:21:22 +0000879 return result;
Tony Makb7e6fd42017-12-05 19:40:28 +0000880 } finally {
881 Binder.restoreCallingIdentity(identity);
882 }
883 }
884
Tony Make3d1f652017-12-12 11:00:37 +0000885 /**
Tony Makd390ae92017-12-28 13:23:10 +0000886 * The caller can modify quiet mode if it meets one of these conditions:
Tony Make3d1f652017-12-12 11:00:37 +0000887 * <ul>
888 * <li>Has system UID or root UID</li>
889 * <li>Has {@link Manifest.permission#MODIFY_QUIET_MODE}</li>
890 * <li>Has {@link Manifest.permission#MANAGE_USERS}</li>
891 * </ul>
Tony Makd390ae92017-12-28 13:23:10 +0000892 * <p>
893 * If caller wants to start an intent after disabling the quiet mode, it must has
894 * {@link Manifest.permission#MANAGE_USERS}.
Tony Make3d1f652017-12-12 11:00:37 +0000895 */
Tony Makd390ae92017-12-28 13:23:10 +0000896 private void ensureCanModifyQuietMode(String callingPackage, int callingUid,
897 boolean startIntent) {
Tony Make3d1f652017-12-12 11:00:37 +0000898 if (hasManageUsersPermission()) {
Tony Makd390ae92017-12-28 13:23:10 +0000899 return;
Tony Make3d1f652017-12-12 11:00:37 +0000900 }
Tony Makd390ae92017-12-28 13:23:10 +0000901 if (startIntent) {
902 throw new SecurityException("MANAGE_USERS permission is required to start intent "
903 + "after disabling quiet mode.");
904 }
jovanakf24ad492018-05-18 12:15:59 -0700905 final boolean hasModifyQuietModePermission = hasPermissionGranted(
906 Manifest.permission.MODIFY_QUIET_MODE, callingUid);
Tony Make3d1f652017-12-12 11:00:37 +0000907 if (hasModifyQuietModePermission) {
Tony Makd390ae92017-12-28 13:23:10 +0000908 return;
Tony Make3d1f652017-12-12 11:00:37 +0000909 }
910
Tony Makd390ae92017-12-28 13:23:10 +0000911 verifyCallingPackage(callingPackage, callingUid);
Tony Make3d1f652017-12-12 11:00:37 +0000912 final ShortcutServiceInternal shortcutInternal =
913 LocalServices.getService(ShortcutServiceInternal.class);
914 if (shortcutInternal != null) {
915 boolean isForegroundLauncher =
916 shortcutInternal.isForegroundDefaultLauncher(callingPackage, callingUid);
917 if (isForegroundLauncher) {
Tony Makd390ae92017-12-28 13:23:10 +0000918 return;
Tony Make3d1f652017-12-12 11:00:37 +0000919 }
920 }
Tony Makd390ae92017-12-28 13:23:10 +0000921 throw new SecurityException("Can't modify quiet mode, caller is neither foreground "
922 + "default launcher nor has MANAGE_USERS/MODIFY_QUIET_MODE permission");
Tony Make3d1f652017-12-12 11:00:37 +0000923 }
924
arangelov9b632d72018-12-07 23:21:22 +0000925 private void setQuietModeEnabled(int userHandle, boolean enableQuietMode,
926 IntentSender target, @Nullable String callingPackage) {
Tony Makb7e6fd42017-12-05 19:40:28 +0000927 final UserInfo profile, parent;
928 final UserData profileUserData;
929 synchronized (mUsersLock) {
930 profile = getUserInfoLU(userHandle);
931 parent = getProfileParentLU(userHandle);
932
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000933 if (profile == null || !profile.isManagedProfile()) {
934 throw new IllegalArgumentException("User " + userHandle + " is not a profile");
935 }
Tony Makb7e6fd42017-12-05 19:40:28 +0000936 if (profile.isQuietModeEnabled() == enableQuietMode) {
937 Slog.i(LOG_TAG, "Quiet mode is already " + enableQuietMode);
938 return;
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000939 }
Tony Makb7e6fd42017-12-05 19:40:28 +0000940 profile.flags ^= UserInfo.FLAG_QUIET_MODE;
941 profileUserData = getUserDataLU(profile.id);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000942 }
Tony Makb7e6fd42017-12-05 19:40:28 +0000943 synchronized (mPackagesLock) {
944 writeUserLP(profileUserData);
945 }
946 try {
947 if (enableQuietMode) {
948 ActivityManager.getService().stopUser(userHandle, /* force */true, null);
949 LocalServices.getService(ActivityManagerInternal.class)
950 .killForegroundAppsForUser(userHandle);
951 } else {
952 IProgressListener callback = target != null
953 ? new DisableQuietModeUserUnlockedCallback(target)
954 : null;
955 ActivityManager.getService().startUserInBackgroundWithListener(
956 userHandle, callback);
Rubin Xuf13c9802016-01-21 18:06:00 +0000957 }
arangelov9b632d72018-12-07 23:21:22 +0000958 logQuietModeEnabled(userHandle, enableQuietMode, callingPackage);
Tony Makb7e6fd42017-12-05 19:40:28 +0000959 } catch (RemoteException e) {
960 // Should not happen, same process.
961 e.rethrowAsRuntimeException();
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000962 }
Tony Makb7e6fd42017-12-05 19:40:28 +0000963 broadcastProfileAvailabilityChanges(profile.getUserHandle(), parent.getUserHandle(),
964 enableQuietMode);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000965 }
966
arangelov9b632d72018-12-07 23:21:22 +0000967 private void logQuietModeEnabled(int userHandle, boolean enableQuietMode,
968 @Nullable String callingPackage) {
969 UserData userData;
970 synchronized (mUsersLock) {
971 userData = getUserDataLU(userHandle);
972 }
973 if (userData == null) {
974 return;
975 }
976 final long now = System.currentTimeMillis();
977 final long period = (userData.getLastRequestQuietModeEnabledMillis() != 0L
978 ? now - userData.getLastRequestQuietModeEnabledMillis()
979 : now - userData.info.creationTime);
980 DevicePolicyEventLogger
981 .createEvent(DevicePolicyEnums.REQUEST_QUIET_MODE_ENABLED)
982 .setStrings(callingPackage)
983 .setBoolean(enableQuietMode)
984 .setTimePeriod(period)
985 .write();
986 userData.setLastRequestQuietModeEnabledMillis(now);
987 }
988
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000989 @Override
990 public boolean isQuietModeEnabled(int userHandle) {
991 synchronized (mPackagesLock) {
992 UserInfo info;
993 synchronized (mUsersLock) {
994 info = getUserInfoLU(userHandle);
995 }
996 if (info == null || !info.isManagedProfile()) {
Rubin Xuf13c9802016-01-21 18:06:00 +0000997 return false;
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000998 }
999 return info.isQuietModeEnabled();
1000 }
1001 }
1002
Tony Makb7e6fd42017-12-05 19:40:28 +00001003 /**
1004 * Show confirm credential screen to unlock user in order to turn off quiet mode.
1005 */
1006 private void showConfirmCredentialToDisableQuietMode(
Tony Mak64fd8c02017-12-01 19:11:59 +00001007 @UserIdInt int userHandle, @Nullable IntentSender target) {
Tony Makb7e6fd42017-12-05 19:40:28 +00001008 // otherwise, we show a profile challenge to trigger decryption of the user
1009 final KeyguardManager km = (KeyguardManager) mContext.getSystemService(
1010 Context.KEYGUARD_SERVICE);
1011 // We should use userHandle not credentialOwnerUserId here, as even if it is unified
1012 // lock, confirm screenlock page will know and show personal challenge, and unlock
1013 // work profile when personal challenge is correct
1014 final Intent unlockIntent = km.createConfirmDeviceCredentialIntent(null, null,
1015 userHandle);
1016 if (unlockIntent == null) {
1017 return;
Benjamin Franzf02420c2016-04-04 18:52:21 +01001018 }
Tony Makb7e6fd42017-12-05 19:40:28 +00001019 final Intent callBackIntent = new Intent(
1020 ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK);
1021 if (target != null) {
1022 callBackIntent.putExtra(Intent.EXTRA_INTENT, target);
Benjamin Franzf02420c2016-04-04 18:52:21 +01001023 }
Tony Makb7e6fd42017-12-05 19:40:28 +00001024 callBackIntent.putExtra(Intent.EXTRA_USER_ID, userHandle);
1025 callBackIntent.setPackage(mContext.getPackageName());
1026 callBackIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1027 final PendingIntent pendingIntent = PendingIntent.getBroadcast(
1028 mContext,
1029 0,
1030 callBackIntent,
1031 PendingIntent.FLAG_CANCEL_CURRENT |
1032 PendingIntent.FLAG_ONE_SHOT |
1033 PendingIntent.FLAG_IMMUTABLE);
1034 // After unlocking the challenge, it will disable quiet mode and run the original
1035 // intentSender
1036 unlockIntent.putExtra(Intent.EXTRA_INTENT, pendingIntent.getIntentSender());
1037 unlockIntent.setFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
1038 mContext.startActivity(unlockIntent);
Benjamin Franzf02420c2016-04-04 18:52:21 +01001039 }
1040
1041 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +01001042 public void setUserEnabled(int userId) {
1043 checkManageUsersPermission("enable user");
1044 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001045 UserInfo info;
1046 synchronized (mUsersLock) {
1047 info = getUserInfoLU(userId);
1048 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +01001049 if (info != null && !info.isEnabled()) {
1050 info.flags ^= UserInfo.FLAG_DISABLED;
Amith Yamasani12747872015-12-07 14:19:49 -08001051 writeUserLP(getUserDataLU(info.id));
Alexandra Gherghinadf35d572014-04-09 13:54:39 +01001052 }
1053 }
1054 }
1055
jovanakf24ad492018-05-18 12:15:59 -07001056 @Override
1057 public void setUserAdmin(int userId) {
1058 checkManageUserAndAcrossUsersFullPermission("set user admin");
1059
1060 synchronized (mPackagesLock) {
1061 UserInfo info;
1062 synchronized (mUsersLock) {
1063 info = getUserInfoLU(userId);
1064 }
1065 if (info == null || info.isAdmin()) {
1066 // Exit if no user found with that id, or the user is already an Admin.
1067 return;
1068 }
1069
1070 info.flags ^= UserInfo.FLAG_ADMIN;
1071 writeUserLP(getUserDataLU(info.id));
1072 }
1073
1074 // Remove non-admin restrictions.
1075 // Keep synchronized with createUserEvenWhenDisallowed.
1076 setUserRestriction(UserManager.DISALLOW_SMS, false, userId);
1077 setUserRestriction(UserManager.DISALLOW_OUTGOING_CALLS, false, userId);
1078 }
1079
Andrew Scull85a63bc2016-10-24 13:47:47 +01001080 /**
1081 * Evicts a user's CE key by stopping and restarting the user.
1082 *
1083 * The key is evicted automatically by the user controller when the user has stopped.
1084 */
1085 @Override
1086 public void evictCredentialEncryptionKey(@UserIdInt int userId) {
1087 checkManageUsersPermission("evict CE key");
1088 final IActivityManager am = ActivityManagerNative.getDefault();
1089 final long identity = Binder.clearCallingIdentity();
1090 try {
1091 am.restartUserInBackground(userId);
1092 } catch (RemoteException re) {
1093 throw re.rethrowAsRuntimeException();
1094 } finally {
1095 Binder.restoreCallingIdentity(identity);
1096 }
1097 }
1098
Alexandra Gherghinadf35d572014-04-09 13:54:39 +01001099 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -07001100 public UserInfo getUserInfo(int userId) {
Sudheer Shankaaccaa082016-06-14 16:22:57 -07001101 checkManageOrCreateUsersPermission("query user");
Tony Mak8673b282016-03-21 21:10:59 +00001102 synchronized (mUsersLock) {
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001103 return userWithName(getUserInfoLU(userId));
1104 }
1105 }
1106
1107 /**
1108 * Returns a UserInfo object with the name filled in, for Owner, or the original
1109 * if the name is already set.
1110 */
1111 private UserInfo userWithName(UserInfo orig) {
1112 if (orig != null && orig.name == null && orig.id == UserHandle.USER_SYSTEM) {
1113 UserInfo withName = new UserInfo(orig);
1114 withName.name = getOwnerName();
1115 return withName;
1116 } else {
1117 return orig;
Tony Mak8673b282016-03-21 21:10:59 +00001118 }
1119 }
1120
1121 @Override
Kenny Guy02c89902016-11-15 19:36:38 +00001122 public int getManagedProfileBadge(@UserIdInt int userId) {
Jon Miranda2b340a22019-01-25 14:03:49 -08001123 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "getManagedProfileBadge");
Kenny Guy02c89902016-11-15 19:36:38 +00001124 synchronized (mUsersLock) {
1125 UserInfo userInfo = getUserInfoLU(userId);
1126 return userInfo != null ? userInfo.profileBadge : 0;
1127 }
1128 }
1129
1130 @Override
Tony Mak8673b282016-03-21 21:10:59 +00001131 public boolean isManagedProfile(int userId) {
Jon Miranda2b340a22019-01-25 14:03:49 -08001132 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isManagedProfile");
Fyodor Kupolov82402752015-10-28 14:54:51 -07001133 synchronized (mUsersLock) {
Amith Yamasani1c41dc82016-06-28 16:13:15 -07001134 UserInfo userInfo = getUserInfoLU(userId);
Tony Mak8673b282016-03-21 21:10:59 +00001135 return userInfo != null && userInfo.isManagedProfile();
Amith Yamasani13593602012-03-22 16:16:17 -07001136 }
1137 }
1138
Amith Yamasani71e6c692013-03-24 17:39:28 -07001139 @Override
Fyodor Kupolovc413f702016-10-06 17:11:14 -07001140 public boolean isUserUnlockingOrUnlocked(int userId) {
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08001141 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isUserUnlockingOrUnlocked");
Fyodor Kupolovc413f702016-10-06 17:11:14 -07001142 return mLocalService.isUserUnlockingOrUnlocked(userId);
1143 }
1144
1145 @Override
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08001146 public boolean isUserUnlocked(int userId) {
1147 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isUserUnlocked");
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07001148 return mLocalService.isUserUnlocked(userId);
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08001149 }
1150
1151 @Override
1152 public boolean isUserRunning(int userId) {
1153 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isUserRunning");
1154 return mLocalService.isUserRunning(userId);
1155 }
1156
Makoto Onuki73dded22017-12-20 13:14:48 +09001157 @Override
Bookatzcde3d922019-03-08 14:30:00 -08001158 public String getUserName() {
1159 if (!hasManageUsersOrPermission(android.Manifest.permission.GET_ACCOUNTS_PRIVILEGED)) {
1160 throw new SecurityException("You need MANAGE_USERS or GET_ACCOUNTS_PRIVILEGED "
1161 + "permissions to: get user name");
1162 }
1163 final int userId = UserHandle.getUserId(Binder.getCallingUid());
1164 synchronized (mUsersLock) {
1165 UserInfo userInfo = userWithName(getUserInfoLU(userId));
1166 return userInfo == null ? "" : userInfo.name;
1167 }
1168 }
1169
1170 @Override
Makoto Onuki73dded22017-12-20 13:14:48 +09001171 public long getUserStartRealtime() {
1172 final int userId = UserHandle.getUserId(Binder.getCallingUid());
1173 synchronized (mUsersLock) {
1174 final UserData user = getUserDataLU(userId);
1175 if (user != null) {
1176 return user.startRealtime;
1177 }
1178 return 0;
1179 }
1180 }
1181
1182 @Override
1183 public long getUserUnlockRealtime() {
1184 synchronized (mUsersLock) {
1185 final UserData user = getUserDataLU(UserHandle.getUserId(Binder.getCallingUid()));
1186 if (user != null) {
1187 return user.unlockRealtime;
1188 }
1189 return 0;
1190 }
1191 }
1192
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08001193 private void checkManageOrInteractPermIfCallerInOtherProfileGroup(int userId, String name) {
1194 int callingUserId = UserHandle.getCallingUserId();
1195 if (callingUserId == userId || isSameProfileGroupNoChecks(callingUserId, userId) ||
1196 hasManageUsersPermission()) {
1197 return;
1198 }
jovanakf24ad492018-05-18 12:15:59 -07001199 if (!hasPermissionGranted(Manifest.permission.INTERACT_ACROSS_USERS,
1200 Binder.getCallingUid())) {
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08001201 throw new SecurityException("You need INTERACT_ACROSS_USERS or MANAGE_USERS permission "
1202 + "to: check " + name);
1203 }
1204 }
1205
1206 @Override
Amith Yamasani1c41dc82016-06-28 16:13:15 -07001207 public boolean isDemoUser(int userId) {
1208 int callingUserId = UserHandle.getCallingUserId();
1209 if (callingUserId != userId && !hasManageUsersPermission()) {
1210 throw new SecurityException("You need MANAGE_USERS permission to query if u=" + userId
1211 + " is a demo user");
1212 }
1213 synchronized (mUsersLock) {
1214 UserInfo userInfo = getUserInfoLU(userId);
1215 return userInfo != null && userInfo.isDemo();
1216 }
1217 }
1218
1219 @Override
Amith Yamasani71e6c692013-03-24 17:39:28 -07001220 public boolean isRestricted() {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001221 synchronized (mUsersLock) {
1222 return getUserInfoLU(UserHandle.getCallingUserId()).isRestricted();
Amith Yamasani71e6c692013-03-24 17:39:28 -07001223 }
1224 }
1225
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001226 @Override
1227 public boolean canHaveRestrictedProfile(int userId) {
1228 checkManageUsersPermission("canHaveRestrictedProfile");
Fyodor Kupolov82402752015-10-28 14:54:51 -07001229 synchronized (mUsersLock) {
1230 final UserInfo userInfo = getUserInfoLU(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001231 if (userInfo == null || !userInfo.canHaveProfile()) {
1232 return false;
1233 }
1234 if (!userInfo.isAdmin()) {
1235 return false;
1236 }
Makoto Onukie7927da2015-11-25 10:05:17 -08001237 // restricted profile can be created if there is no DO set and the admin user has no PO;
1238 return !mIsDeviceManaged && !mIsUserManaged.get(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001239 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001240 }
1241
Fyodor Kupolovca177562017-11-09 17:43:01 -08001242 @Override
1243 public boolean hasRestrictedProfiles() {
1244 checkManageUsersPermission("hasRestrictedProfiles");
1245 final int callingUserId = UserHandle.getCallingUserId();
1246 synchronized (mUsersLock) {
1247 final int userSize = mUsers.size();
1248 for (int i = 0; i < userSize; i++) {
1249 UserInfo profile = mUsers.valueAt(i).info;
1250 if (callingUserId != profile.id
1251 && profile.restrictedProfileParentId == callingUserId) {
1252 return true;
1253 }
1254 }
1255 return false;
1256 }
1257 }
1258
Amith Yamasani195263742012-08-21 15:40:12 -07001259 /*
1260 * Should be locked on mUsers before calling this.
1261 */
Andreas Gampe2e8c7672018-07-20 13:01:08 -07001262 @GuardedBy("mUsersLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001263 private UserInfo getUserInfoLU(int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -08001264 final UserData userData = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -07001265 // If it is partial and not in the process of being removed, return as unknown user.
Amith Yamasani12747872015-12-07 14:19:49 -08001266 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001267 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
1268 return null;
1269 }
Amith Yamasani12747872015-12-07 14:19:49 -08001270 return userData != null ? userData.info : null;
1271 }
1272
Andreas Gampe2e8c7672018-07-20 13:01:08 -07001273 @GuardedBy("mUsersLock")
Amith Yamasani12747872015-12-07 14:19:49 -08001274 private UserData getUserDataLU(int userId) {
1275 final UserData userData = mUsers.get(userId);
1276 // If it is partial and not in the process of being removed, return as unknown user.
1277 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
1278 return null;
1279 }
1280 return userData;
Amith Yamasani195263742012-08-21 15:40:12 -07001281 }
1282
Fyodor Kupolov82402752015-10-28 14:54:51 -07001283 /**
1284 * Obtains {@link #mUsersLock} and return UserInfo from mUsers.
1285 * <p>No permissions checking or any addition checks are made</p>
1286 */
1287 private UserInfo getUserInfoNoChecks(int userId) {
1288 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001289 final UserData userData = mUsers.get(userId);
1290 return userData != null ? userData.info : null;
1291 }
1292 }
1293
1294 /**
1295 * Obtains {@link #mUsersLock} and return UserData from mUsers.
1296 * <p>No permissions checking or any addition checks are made</p>
1297 */
1298 private UserData getUserDataNoChecks(int userId) {
1299 synchronized (mUsersLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001300 return mUsers.get(userId);
1301 }
1302 }
1303
Amith Yamasani236b2b52015-08-18 14:32:14 -07001304 /** Called by PackageManagerService */
Amith Yamasani13593602012-03-22 16:16:17 -07001305 public boolean exists(int userId) {
Todd Kennedy0eb97382017-10-03 16:57:22 -07001306 return mLocalService.exists(userId);
Amith Yamasani13593602012-03-22 16:16:17 -07001307 }
1308
Amith Yamasani258848d2012-08-10 17:06:33 -07001309 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001310 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001311 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001312 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -07001313 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001314 UserData userData = getUserDataNoChecks(userId);
1315 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001316 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
1317 return;
1318 }
Amith Yamasani12747872015-12-07 14:19:49 -08001319 if (name != null && !name.equals(userData.info.name)) {
1320 userData.info.name = name;
1321 writeUserLP(userData);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001322 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -07001323 }
1324 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001325 if (changed) {
Bookatzf9368552019-03-14 11:57:09 -07001326 long ident = Binder.clearCallingIdentity();
1327 try {
1328 sendUserInfoChangedBroadcast(userId);
1329 } finally {
1330 Binder.restoreCallingIdentity(ident);
1331 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001332 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001333 }
1334
Amith Yamasani258848d2012-08-10 17:06:33 -07001335 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001336 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001337 checkManageUsersPermission("update users");
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01001338 if (hasUserRestriction(UserManager.DISALLOW_SET_USER_ICON, userId)) {
1339 Log.w(LOG_TAG, "Cannot set user icon. DISALLOW_SET_USER_ICON is enabled.");
1340 return;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001341 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01001342 mLocalService.setUserIcon(userId, bitmap);
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001343 }
1344
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01001345
1346
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001347 private void sendUserInfoChangedBroadcast(int userId) {
1348 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
1349 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
1350 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -07001351 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001352 }
1353
Amith Yamasani258848d2012-08-10 17:06:33 -07001354 @Override
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001355 public ParcelFileDescriptor getUserIcon(int targetUserId) {
Bookatzcde3d922019-03-08 14:30:00 -08001356 if (!hasManageUsersOrPermission(android.Manifest.permission.GET_ACCOUNTS_PRIVILEGED)) {
1357 throw new SecurityException("You need MANAGE_USERS or GET_ACCOUNTS_PRIVILEGED "
1358 + "permissions to: get user icon");
1359 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001360 String iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001361 synchronized (mPackagesLock) {
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001362 UserInfo targetUserInfo = getUserInfoNoChecks(targetUserId);
1363 if (targetUserInfo == null || targetUserInfo.partial) {
1364 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + targetUserId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001365 return null;
1366 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001367
1368 final int callingUserId = UserHandle.getCallingUserId();
1369 final int callingGroupId = getUserInfoNoChecks(callingUserId).profileGroupId;
1370 final int targetGroupId = targetUserInfo.profileGroupId;
1371 final boolean sameGroup = (callingGroupId != UserInfo.NO_PROFILE_GROUP_ID
1372 && callingGroupId == targetGroupId);
1373 if ((callingUserId != targetUserId) && !sameGroup) {
Nicolas Prevot88cc3462014-05-14 14:51:48 +01001374 checkManageUsersPermission("get the icon of a user who is not related");
1375 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001376
1377 if (targetUserInfo.iconPath == null) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001378 return null;
1379 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001380 iconPath = targetUserInfo.iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001381 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001382
1383 try {
1384 return ParcelFileDescriptor.open(
1385 new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
1386 } catch (FileNotFoundException e) {
1387 Log.e(LOG_TAG, "Couldn't find icon file", e);
1388 }
1389 return null;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001390 }
1391
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001392 public void makeInitialized(int userId) {
1393 checkManageUsersPermission("makeInitialized");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001394 boolean scheduleWriteUser = false;
Amith Yamasani12747872015-12-07 14:19:49 -08001395 UserData userData;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001396 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001397 userData = mUsers.get(userId);
1398 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001399 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001400 return;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001401 }
Amith Yamasani12747872015-12-07 14:19:49 -08001402 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1403 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001404 scheduleWriteUser = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001405 }
1406 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001407 if (scheduleWriteUser) {
Amith Yamasani12747872015-12-07 14:19:49 -08001408 scheduleWriteUser(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001409 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001410 }
1411
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001412 /**
1413 * If default guest restrictions haven't been initialized yet, add the basic
1414 * restrictions.
1415 */
1416 private void initDefaultGuestRestrictions() {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001417 synchronized (mGuestRestrictions) {
1418 if (mGuestRestrictions.isEmpty()) {
Samuel Tand9453b82016-03-14 15:57:02 -07001419 mGuestRestrictions.putBoolean(UserManager.DISALLOW_CONFIG_WIFI, true);
Fyodor Kupolove04462c2015-11-30 15:02:53 -08001420 mGuestRestrictions.putBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, true);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001421 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
1422 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
1423 }
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001424 }
1425 }
1426
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001427 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301428 public Bundle getDefaultGuestRestrictions() {
1429 checkManageUsersPermission("getDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001430 synchronized (mGuestRestrictions) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301431 return new Bundle(mGuestRestrictions);
1432 }
1433 }
1434
1435 @Override
1436 public void setDefaultGuestRestrictions(Bundle restrictions) {
1437 checkManageUsersPermission("setDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001438 synchronized (mGuestRestrictions) {
1439 mGuestRestrictions.clear();
1440 mGuestRestrictions.putAll(restrictions);
1441 }
1442 synchronized (mPackagesLock) {
1443 writeUserListLP();
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301444 }
1445 }
1446
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001447 /**
Pavel Grafov6a40f092016-10-25 15:46:51 +01001448 * See {@link UserManagerInternal#setDevicePolicyUserRestrictions}
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001449 */
Pavel Grafov6a40f092016-10-25 15:46:51 +01001450 private void setDevicePolicyUserRestrictionsInner(int userId, @Nullable Bundle restrictions,
1451 boolean isDeviceOwner, int cameraRestrictionScope) {
1452 final Bundle global = new Bundle();
1453 final Bundle local = new Bundle();
1454
1455 // Sort restrictions into local and global ensuring they don't overlap.
1456 UserRestrictionsUtils.sortToGlobalAndLocal(restrictions, isDeviceOwner,
1457 cameraRestrictionScope, global, local);
1458
1459 boolean globalChanged, localChanged;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001460 synchronized (mRestrictionsLock) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001461 // Update global and local restrictions if they were changed.
1462 globalChanged = updateRestrictionsIfNeededLR(
1463 userId, global, mDevicePolicyGlobalUserRestrictions);
1464 localChanged = updateRestrictionsIfNeededLR(
1465 userId, local, mDevicePolicyLocalUserRestrictions);
1466
1467 if (isDeviceOwner) {
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001468 // Remember the global restriction owner userId to be able to make a distinction
1469 // in getUserRestrictionSource on who set local policies.
Pavel Grafov6a40f092016-10-25 15:46:51 +01001470 mDeviceOwnerUserId = userId;
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001471 } else {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001472 if (mDeviceOwnerUserId == userId) {
Zoltan Szatmary-Ban8a5536d2016-05-27 17:56:44 +01001473 // When profile owner sets restrictions it passes null global bundle and we
1474 // reset global restriction owner userId.
1475 // This means this user used to have DO, but now the DO is gone and the user
1476 // instead has PO.
Pavel Grafov6a40f092016-10-25 15:46:51 +01001477 mDeviceOwnerUserId = UserHandle.USER_NULL;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001478 }
1479 }
1480 }
1481 if (DBG) {
1482 Log.d(LOG_TAG, "setDevicePolicyUserRestrictions: userId=" + userId
1483 + " global=" + global + (globalChanged ? " (changed)" : "")
1484 + " local=" + local + (localChanged ? " (changed)" : "")
1485 );
1486 }
1487 // Don't call them within the mRestrictionsLock.
1488 synchronized (mPackagesLock) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001489 if (localChanged || globalChanged) {
Amith Yamasani12747872015-12-07 14:19:49 -08001490 writeUserLP(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001491 }
1492 }
1493
1494 synchronized (mRestrictionsLock) {
1495 if (globalChanged) {
1496 applyUserRestrictionsForAllUsersLR();
1497 } else if (localChanged) {
1498 applyUserRestrictionsLR(userId);
1499 }
1500 }
1501 }
1502
Pavel Grafov6a40f092016-10-25 15:46:51 +01001503 /**
1504 * Updates restriction bundle for a given user in a given restriction array. If new bundle is
1505 * empty, record is removed from the array.
1506 * @return whether restrictions bundle is different from the old one.
1507 */
1508 private boolean updateRestrictionsIfNeededLR(int userId, @Nullable Bundle restrictions,
1509 SparseArray<Bundle> restrictionsArray) {
1510 final boolean changed =
1511 !UserRestrictionsUtils.areEqual(restrictionsArray.get(userId), restrictions);
1512 if (changed) {
1513 if (!UserRestrictionsUtils.isEmpty(restrictions)) {
1514 restrictionsArray.put(userId, restrictions);
1515 } else {
1516 restrictionsArray.delete(userId);
1517 }
1518 }
1519 return changed;
1520 }
1521
Makoto Onuki068c54a2015-10-13 14:34:03 -07001522 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001523 private Bundle computeEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001524 final Bundle baseRestrictions =
1525 UserRestrictionsUtils.nonNull(mBaseUserRestrictions.get(userId));
Pavel Grafov6a40f092016-10-25 15:46:51 +01001526 final Bundle global = UserRestrictionsUtils.mergeAll(mDevicePolicyGlobalUserRestrictions);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001527 final Bundle local = mDevicePolicyLocalUserRestrictions.get(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001528
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001529 if (UserRestrictionsUtils.isEmpty(global) && UserRestrictionsUtils.isEmpty(local)) {
1530 // Common case first.
1531 return baseRestrictions;
Makoto Onuki068c54a2015-10-13 14:34:03 -07001532 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001533 final Bundle effective = UserRestrictionsUtils.clone(baseRestrictions);
1534 UserRestrictionsUtils.merge(effective, global);
1535 UserRestrictionsUtils.merge(effective, local);
1536
Makoto Onuki068c54a2015-10-13 14:34:03 -07001537 return effective;
1538 }
1539
1540 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001541 private void invalidateEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki068c54a2015-10-13 14:34:03 -07001542 if (DBG) {
1543 Log.d(LOG_TAG, "invalidateEffectiveUserRestrictions userId=" + userId);
1544 }
1545 mCachedEffectiveUserRestrictions.remove(userId);
1546 }
1547
1548 private Bundle getEffectiveUserRestrictions(int userId) {
1549 synchronized (mRestrictionsLock) {
1550 Bundle restrictions = mCachedEffectiveUserRestrictions.get(userId);
1551 if (restrictions == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001552 restrictions = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001553 mCachedEffectiveUserRestrictions.put(userId, restrictions);
1554 }
1555 return restrictions;
Amith Yamasani8cd28b52014-06-08 17:54:27 -07001556 }
1557 }
1558
Makoto Onuki068c54a2015-10-13 14:34:03 -07001559 /** @return a specific user restriction that's in effect currently. */
1560 @Override
1561 public boolean hasUserRestriction(String restrictionKey, int userId) {
Patrick Baumann2f2fd712019-07-31 15:18:53 -07001562 return mLocalService.hasUserRestriction(restrictionKey, userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001563 }
1564
Makoto Onukiacc50462018-02-14 14:13:49 -08001565 /** @return if any user has the given restriction. */
1566 @Override
1567 public boolean hasUserRestrictionOnAnyUser(String restrictionKey) {
1568 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1569 return false;
1570 }
1571 final List<UserInfo> users = getUsers(/* excludeDying= */ true);
1572 for (int i = 0; i < users.size(); i++) {
1573 final int userId = users.get(i).id;
1574 Bundle restrictions = getEffectiveUserRestrictions(userId);
1575 if (restrictions != null && restrictions.getBoolean(restrictionKey)) {
1576 return true;
1577 }
1578 }
1579 return false;
1580 }
1581
Makoto Onuki068c54a2015-10-13 14:34:03 -07001582 /**
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001583 * @hide
1584 *
1585 * Returns who set a user restriction on a user.
1586 * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
1587 * @param restrictionKey the string key representing the restriction
1588 * @param userId the id of the user for whom to retrieve the restrictions.
1589 * @return The source of user restriction. Any combination of
1590 * {@link UserManager#RESTRICTION_NOT_SET},
1591 * {@link UserManager#RESTRICTION_SOURCE_SYSTEM},
1592 * {@link UserManager#RESTRICTION_SOURCE_DEVICE_OWNER}
1593 * and {@link UserManager#RESTRICTION_SOURCE_PROFILE_OWNER}
1594 */
1595 @Override
1596 public int getUserRestrictionSource(String restrictionKey, int userId) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001597 List<EnforcingUser> enforcingUsers = getUserRestrictionSources(restrictionKey, userId);
1598 // Get "bitwise or" of restriction sources for all enforcing users.
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001599 int result = UserManager.RESTRICTION_NOT_SET;
Pavel Grafov6a40f092016-10-25 15:46:51 +01001600 for (int i = enforcingUsers.size() - 1; i >= 0; i--) {
1601 result |= enforcingUsers.get(i).getUserRestrictionSource();
1602 }
1603 return result;
1604 }
1605
1606 @Override
1607 public List<EnforcingUser> getUserRestrictionSources(
1608 String restrictionKey, @UserIdInt int userId) {
1609 checkManageUsersPermission("getUserRestrictionSource");
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001610
1611 // Shortcut for the most common case
1612 if (!hasUserRestriction(restrictionKey, userId)) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001613 return Collections.emptyList();
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001614 }
1615
Pavel Grafov6a40f092016-10-25 15:46:51 +01001616 final List<EnforcingUser> result = new ArrayList<>();
1617
1618 // Check if it is base restriction.
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001619 if (hasBaseUserRestriction(restrictionKey, userId)) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001620 result.add(new EnforcingUser(
1621 UserHandle.USER_NULL, UserManager.RESTRICTION_SOURCE_SYSTEM));
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001622 }
1623
Pavel Grafov6a40f092016-10-25 15:46:51 +01001624 synchronized (mRestrictionsLock) {
1625 // Check if it is set by profile owner.
1626 Bundle profileOwnerRestrictions = mDevicePolicyLocalUserRestrictions.get(userId);
1627 if (UserRestrictionsUtils.contains(profileOwnerRestrictions, restrictionKey)) {
1628 result.add(getEnforcingUserLocked(userId));
1629 }
1630
1631 // Iterate over all users who enforce global restrictions.
1632 for (int i = mDevicePolicyGlobalUserRestrictions.size() - 1; i >= 0; i--) {
1633 Bundle globalRestrictions = mDevicePolicyGlobalUserRestrictions.valueAt(i);
1634 int profileUserId = mDevicePolicyGlobalUserRestrictions.keyAt(i);
1635 if (UserRestrictionsUtils.contains(globalRestrictions, restrictionKey)) {
1636 result.add(getEnforcingUserLocked(profileUserId));
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001637 }
1638 }
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001639 }
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001640 return result;
1641 }
1642
Andreas Gampea36dc622018-02-05 17:19:22 -08001643 @GuardedBy("mRestrictionsLock")
Pavel Grafov6a40f092016-10-25 15:46:51 +01001644 private EnforcingUser getEnforcingUserLocked(@UserIdInt int userId) {
1645 int source = mDeviceOwnerUserId == userId ? UserManager.RESTRICTION_SOURCE_DEVICE_OWNER
1646 : UserManager.RESTRICTION_SOURCE_PROFILE_OWNER;
1647 return new EnforcingUser(userId, source);
1648 }
1649
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001650 /**
Makoto Onuki068c54a2015-10-13 14:34:03 -07001651 * @return UserRestrictions that are in effect currently. This always returns a new
1652 * {@link Bundle}.
1653 */
Amith Yamasani8cd28b52014-06-08 17:54:27 -07001654 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001655 public Bundle getUserRestrictions(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001656 return UserRestrictionsUtils.clone(getEffectiveUserRestrictions(userId));
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001657 }
1658
1659 @Override
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +00001660 public boolean hasBaseUserRestriction(String restrictionKey, int userId) {
1661 checkManageUsersPermission("hasBaseUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001662 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1663 return false;
1664 }
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +00001665 synchronized (mRestrictionsLock) {
1666 Bundle bundle = mBaseUserRestrictions.get(userId);
1667 return (bundle != null && bundle.getBoolean(restrictionKey, false));
1668 }
1669 }
1670
1671 @Override
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001672 public void setUserRestriction(String key, boolean value, int userId) {
Fyodor Kupolovd4b26042015-07-27 14:30:59 -07001673 checkManageUsersPermission("setUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001674 if (!UserRestrictionsUtils.isValidRestriction(key)) {
1675 return;
1676 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001677 synchronized (mRestrictionsLock) {
1678 // Note we can't modify Bundles stored in mBaseUserRestrictions directly, so create
1679 // a copy.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001680 final Bundle newRestrictions = UserRestrictionsUtils.clone(
1681 mBaseUserRestrictions.get(userId));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001682 newRestrictions.putBoolean(key, value);
1683
Fyodor Kupolov82402752015-10-28 14:54:51 -07001684 updateUserRestrictionsInternalLR(newRestrictions, userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001685 }
1686 }
1687
Makoto Onuki068c54a2015-10-13 14:34:03 -07001688 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001689 * Optionally updating user restrictions, calculate the effective user restrictions and also
1690 * propagate to other services and system settings.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001691 *
Pavel Grafov6a40f092016-10-25 15:46:51 +01001692 * @param newBaseRestrictions User restrictions to set.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001693 * If null, will not update user restrictions and only does the propagation.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001694 * @param userId target user ID.
1695 */
1696 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001697 private void updateUserRestrictionsInternalLR(
Pavel Grafov6a40f092016-10-25 15:46:51 +01001698 @Nullable Bundle newBaseRestrictions, int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001699 final Bundle prevAppliedRestrictions = UserRestrictionsUtils.nonNull(
1700 mAppliedUserRestrictions.get(userId));
1701
1702 // Update base restrictions.
Pavel Grafov6a40f092016-10-25 15:46:51 +01001703 if (newBaseRestrictions != null) {
1704 // If newBaseRestrictions == the current one, it's probably a bug.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001705 final Bundle prevBaseRestrictions = mBaseUserRestrictions.get(userId);
1706
Pavel Grafov6a40f092016-10-25 15:46:51 +01001707 Preconditions.checkState(prevBaseRestrictions != newBaseRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001708 Preconditions.checkState(mCachedEffectiveUserRestrictions.get(userId)
Pavel Grafov6a40f092016-10-25 15:46:51 +01001709 != newBaseRestrictions);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001710
Pavel Grafov6a40f092016-10-25 15:46:51 +01001711 if (updateRestrictionsIfNeededLR(userId, newBaseRestrictions, mBaseUserRestrictions)) {
Amith Yamasani12747872015-12-07 14:19:49 -08001712 scheduleWriteUser(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001713 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001714 }
1715
Fyodor Kupolov82402752015-10-28 14:54:51 -07001716 final Bundle effective = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001717
Makoto Onuki759a7632015-10-28 16:43:10 -07001718 mCachedEffectiveUserRestrictions.put(userId, effective);
1719
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001720 // Apply the new restrictions.
Makoto Onuki4f160732015-10-27 17:15:38 -07001721 if (DBG) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001722 debug("Applying user restrictions: userId=" + userId
1723 + " new=" + effective + " prev=" + prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001724 }
1725
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001726 if (mAppOpsService != null) { // We skip it until system-ready.
Fyodor Kupolovec30ca32016-06-16 15:09:29 -07001727 mHandler.post(new Runnable() {
1728 @Override
1729 public void run() {
1730 try {
1731 mAppOpsService.setUserRestrictions(effective, mUserRestriconToken, userId);
1732 } catch (RemoteException e) {
1733 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
1734 }
1735 }
1736 });
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001737 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001738
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001739 propagateUserRestrictionsLR(userId, effective, prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001740
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001741 mAppliedUserRestrictions.put(userId, new Bundle(effective));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001742 }
1743
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001744 private void propagateUserRestrictionsLR(final int userId,
Makoto Onukid45a4a22015-11-02 17:17:38 -08001745 Bundle newRestrictions, Bundle prevRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001746 // Note this method doesn't touch any state, meaning it doesn't require mRestrictionsLock
1747 // actually, but we still need some kind of synchronization otherwise we might end up
1748 // calling listeners out-of-order, thus "LR".
1749
1750 if (UserRestrictionsUtils.areEqual(newRestrictions, prevRestrictions)) {
1751 return;
1752 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08001753
1754 final Bundle newRestrictionsFinal = new Bundle(newRestrictions);
1755 final Bundle prevRestrictionsFinal = new Bundle(prevRestrictions);
1756
1757 mHandler.post(new Runnable() {
1758 @Override
1759 public void run() {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07001760 UserRestrictionsUtils.applyUserRestrictions(
1761 mContext, userId, newRestrictionsFinal, prevRestrictionsFinal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001762
Makoto Onukid45a4a22015-11-02 17:17:38 -08001763 final UserRestrictionsListener[] listeners;
1764 synchronized (mUserRestrictionsListeners) {
1765 listeners = new UserRestrictionsListener[mUserRestrictionsListeners.size()];
1766 mUserRestrictionsListeners.toArray(listeners);
1767 }
1768 for (int i = 0; i < listeners.length; i++) {
1769 listeners[i].onUserRestrictionsChanged(userId,
1770 newRestrictionsFinal, prevRestrictionsFinal);
1771 }
Makoto Onukie72f81b2017-03-16 14:08:19 -07001772
1773 final Intent broadcast = new Intent(UserManager.ACTION_USER_RESTRICTIONS_CHANGED)
1774 .setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
1775 mContext.sendBroadcastAsUser(broadcast, UserHandle.of(userId));
Makoto Onukid45a4a22015-11-02 17:17:38 -08001776 }
1777 });
1778 }
1779
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001780 // Package private for the inner class.
Andreas Gampe2e8c7672018-07-20 13:01:08 -07001781 @GuardedBy("mRestrictionsLock")
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001782 void applyUserRestrictionsLR(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001783 updateUserRestrictionsInternalLR(null, userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001784 }
1785
1786 @GuardedBy("mRestrictionsLock")
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001787 // Package private for the inner class.
1788 void applyUserRestrictionsForAllUsersLR() {
1789 if (DBG) {
1790 debug("applyUserRestrictionsForAllUsersLR");
1791 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001792 // First, invalidate all cached values.
Makoto Onuki4f160732015-10-27 17:15:38 -07001793 mCachedEffectiveUserRestrictions.clear();
1794
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001795 // We don't want to call into ActivityManagerService while taking a lock, so we'll call
Makoto Onuki068c54a2015-10-13 14:34:03 -07001796 // it on a handler.
1797 final Runnable r = new Runnable() {
1798 @Override
1799 public void run() {
1800 // Then get the list of running users.
1801 final int[] runningUsers;
1802 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001803 runningUsers = ActivityManager.getService().getRunningUserIds();
Makoto Onuki068c54a2015-10-13 14:34:03 -07001804 } catch (RemoteException e) {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001805 Log.w(LOG_TAG, "Unable to access ActivityManagerService");
Makoto Onuki068c54a2015-10-13 14:34:03 -07001806 return;
1807 }
1808 // Then re-calculate the effective restrictions and apply, only for running users.
1809 // It's okay if a new user has started after the getRunningUserIds() call,
1810 // because we'll do the same thing (re-calculate the restrictions and apply)
1811 // when we start a user.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001812 synchronized (mRestrictionsLock) {
1813 for (int i = 0; i < runningUsers.length; i++) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001814 applyUserRestrictionsLR(runningUsers[i]);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001815 }
1816 }
1817 }
1818 };
1819 mHandler.post(r);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001820 }
1821
Amith Yamasani258848d2012-08-10 17:06:33 -07001822 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001823 * Check if we've hit the limit of how many users can be created.
1824 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001825 private boolean isUserLimitReached() {
1826 int count;
1827 synchronized (mUsersLock) {
1828 count = getAliveUsersExcludingGuestsCountLU();
1829 }
1830 return count >= UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001831 }
1832
1833 @Override
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001834 public boolean canAddMoreManagedProfiles(int userId, boolean allowedToRemoveOne) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001835 checkManageUsersPermission("check if more managed profiles can be added.");
1836 if (ActivityManager.isLowRamDeviceStatic()) {
1837 return false;
1838 }
Fyodor Kupolovb6157992015-06-05 15:32:28 -07001839 if (!mContext.getPackageManager().hasSystemFeature(
1840 PackageManager.FEATURE_MANAGED_USERS)) {
1841 return false;
1842 }
Nicolas Prevotb8186812015-08-06 15:00:03 +01001843 // Limit number of managed profiles that can be created
Benjamin Franzc8776152017-01-06 14:16:41 +00001844 final int managedProfilesCount = getProfiles(userId, false).size() - 1;
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001845 final int profilesRemovedCount = managedProfilesCount > 0 && allowedToRemoveOne ? 1 : 0;
Kenny Guy02c89902016-11-15 19:36:38 +00001846 if (managedProfilesCount - profilesRemovedCount >= getMaxManagedProfiles()) {
Nicolas Prevotb8186812015-08-06 15:00:03 +01001847 return false;
1848 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001849 synchronized(mUsersLock) {
1850 UserInfo userInfo = getUserInfoLU(userId);
yuanhao47f9f7c2017-01-18 09:54:45 +08001851 if (userInfo == null || !userInfo.canHaveProfile()) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001852 return false;
1853 }
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001854 int usersCountAfterRemoving = getAliveUsersExcludingGuestsCountLU()
1855 - profilesRemovedCount;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001856 // We allow creating a managed profile in the special case where there is only one user.
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001857 return usersCountAfterRemoving == 1
1858 || usersCountAfterRemoving < UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001859 }
1860 }
1861
Andreas Gampe2e8c7672018-07-20 13:01:08 -07001862 @GuardedBy("mUsersLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001863 private int getAliveUsersExcludingGuestsCountLU() {
Amith Yamasanif584f012014-05-19 17:57:25 -07001864 int aliveUserCount = 0;
1865 final int totalUserCount = mUsers.size();
1866 // Skip over users being removed
1867 for (int i = 0; i < totalUserCount; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001868 UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov6e99d3f2016-11-01 17:18:41 -07001869 if (!mRemovingUserIds.get(user.id) && !user.isGuest()) {
Amith Yamasanif584f012014-05-19 17:57:25 -07001870 aliveUserCount++;
1871 }
1872 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001873 return aliveUserCount;
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001874 }
1875
1876 /**
Amith Yamasani195263742012-08-21 15:40:12 -07001877 * Enforces that only the system UID or root's UID or apps that have the
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001878 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} and
1879 * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL INTERACT_ACROSS_USERS_FULL}
1880 * permissions can make certain calls to the UserManager.
1881 *
1882 * @param message used as message if SecurityException is thrown
1883 * @throws SecurityException if the caller does not have enough privilege.
1884 */
1885 private static final void checkManageUserAndAcrossUsersFullPermission(String message) {
1886 final int uid = Binder.getCallingUid();
jovanakf24ad492018-05-18 12:15:59 -07001887
1888 if (uid == Process.SYSTEM_UID || uid == 0) {
1889 // System UID or root's UID are granted privilege.
1890 return;
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001891 }
jovanakf24ad492018-05-18 12:15:59 -07001892
1893 if (hasPermissionGranted(Manifest.permission.MANAGE_USERS, uid)
1894 && hasPermissionGranted(Manifest.permission.INTERACT_ACROSS_USERS_FULL, uid)) {
1895 // Apps with both permissions are granted privilege.
1896 return;
1897 }
1898
1899 throw new SecurityException(
1900 "You need MANAGE_USERS and INTERACT_ACROSS_USERS_FULL permission to: " + message);
1901 }
1902
1903 private static boolean hasPermissionGranted(String permission, int uid) {
1904 return ActivityManager.checkComponentPermission(
1905 permission, uid, /* owningUid = */-1, /* exported = */ true) ==
1906 PackageManager.PERMISSION_GRANTED;
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001907 }
1908
1909 /**
1910 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001911 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -07001912 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -07001913 *
1914 * @param message used as message if SecurityException is thrown
1915 * @throws SecurityException if the caller is not system or root
Tony Mak4dc008c2016-03-16 10:46:49 +00001916 * @see #hasManageUsersPermission()
Amith Yamasani258848d2012-08-10 17:06:33 -07001917 */
Amith Yamasanibe465322014-04-24 13:45:17 -07001918 private static final void checkManageUsersPermission(String message) {
Tony Mak4dc008c2016-03-16 10:46:49 +00001919 if (!hasManageUsersPermission()) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001920 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
1921 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -04001922 }
1923
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001924 /**
Sudheer Shankaf5cea032016-06-08 17:13:24 -07001925 * Enforces that only the system UID or root's UID or apps that have the
1926 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or
1927 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS}
1928 * can make certain calls to the UserManager.
1929 *
1930 * @param message used as message if SecurityException is thrown
1931 * @throws SecurityException if the caller is not system or root
1932 * @see #hasManageOrCreateUsersPermission()
1933 */
1934 private static final void checkManageOrCreateUsersPermission(String message) {
1935 if (!hasManageOrCreateUsersPermission()) {
1936 throw new SecurityException(
1937 "You either need MANAGE_USERS or CREATE_USERS permission to: " + message);
1938 }
1939 }
1940
1941 /**
1942 * Similar to {@link #checkManageOrCreateUsersPermission(String)} but when the caller is tries
1943 * to create user/profiles other than what is allowed for
1944 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS} permission, then it will only
1945 * allow callers with {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} permission.
1946 */
1947 private static final void checkManageOrCreateUsersPermission(int creationFlags) {
1948 if ((creationFlags & ~ALLOWED_FLAGS_FOR_CREATE_USERS_PERMISSION) == 0) {
1949 if (!hasManageOrCreateUsersPermission()) {
1950 throw new SecurityException("You either need MANAGE_USERS or CREATE_USERS "
1951 + "permission to create an user with flags: " + creationFlags);
1952 }
1953 } else if (!hasManageUsersPermission()) {
1954 throw new SecurityException("You need MANAGE_USERS permission to create an user "
1955 + " with flags: " + creationFlags);
1956 }
1957 }
1958
1959 /**
Tony Mak4dc008c2016-03-16 10:46:49 +00001960 * @return whether the calling UID is system UID or root's UID or the calling app has the
1961 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}.
1962 */
1963 private static final boolean hasManageUsersPermission() {
1964 final int callingUid = Binder.getCallingUid();
1965 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
1966 || callingUid == Process.ROOT_UID
jovanakf24ad492018-05-18 12:15:59 -07001967 || hasPermissionGranted(android.Manifest.permission.MANAGE_USERS, callingUid);
Tony Mak4dc008c2016-03-16 10:46:49 +00001968 }
1969
1970 /**
Sudheer Shankaf5cea032016-06-08 17:13:24 -07001971 * @return whether the calling UID is system UID or root's UID or the calling app has the
Bookatzcde3d922019-03-08 14:30:00 -08001972 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or the provided permission.
Sudheer Shankaf5cea032016-06-08 17:13:24 -07001973 */
Bookatzcde3d922019-03-08 14:30:00 -08001974 private static final boolean hasManageUsersOrPermission(String alternativePermission) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07001975 final int callingUid = Binder.getCallingUid();
1976 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
1977 || callingUid == Process.ROOT_UID
jovanakf24ad492018-05-18 12:15:59 -07001978 || hasPermissionGranted(android.Manifest.permission.MANAGE_USERS, callingUid)
Bookatzcde3d922019-03-08 14:30:00 -08001979 || hasPermissionGranted(alternativePermission, callingUid);
1980 }
1981
1982 /**
1983 * @return whether the calling UID is system UID or root's UID or the calling app has the
1984 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or
1985 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS}.
1986 */
1987 private static final boolean hasManageOrCreateUsersPermission() {
1988 return hasManageUsersOrPermission(android.Manifest.permission.CREATE_USERS);
Sudheer Shankaf5cea032016-06-08 17:13:24 -07001989 }
1990
1991 /**
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001992 * Enforces that only the system UID or root's UID (on any user) can make certain calls to the
1993 * UserManager.
1994 *
1995 * @param message used as message if SecurityException is thrown
1996 * @throws SecurityException if the caller is not system or root
1997 */
1998 private static void checkSystemOrRoot(String message) {
1999 final int uid = Binder.getCallingUid();
2000 if (!UserHandle.isSameApp(uid, Process.SYSTEM_UID) && uid != Process.ROOT_UID) {
2001 throw new SecurityException("Only system may: " + message);
2002 }
2003 }
2004
Fyodor Kupolov82402752015-10-28 14:54:51 -07002005 private void writeBitmapLP(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002006 try {
2007 File dir = new File(mUsersDir, Integer.toString(info.id));
2008 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +01002009 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002010 if (!dir.exists()) {
2011 dir.mkdir();
2012 FileUtils.setPermissions(
2013 dir.getPath(),
2014 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
2015 -1, -1);
2016 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07002017 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +01002018 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01002019 && tmp.renameTo(file) && SELinux.restorecon(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -07002020 info.iconPath = file.getAbsolutePath();
2021 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07002022 try {
2023 os.close();
2024 } catch (IOException ioe) {
2025 // What the ... !
2026 }
Adrian Roos1bdff912015-02-17 15:51:35 +01002027 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002028 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002029 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002030 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002031 }
2032
Amith Yamasani0b285492011-04-14 17:35:23 -07002033 /**
2034 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
2035 * cache it elsewhere.
2036 * @return the array of user ids.
2037 */
Dianne Hackborn1676c852012-09-10 14:52:30 -07002038 public int[] getUserIds() {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002039 synchronized (mUsersLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07002040 return mUserIds;
2041 }
Amith Yamasani0b285492011-04-14 17:35:23 -07002042 }
2043
Andreas Gampe2e8c7672018-07-20 13:01:08 -07002044 @GuardedBy({"mRestrictionsLock", "mPackagesLock"})
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002045 private void readUserListLP() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002046 if (!mUserListFile.exists()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002047 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002048 return;
2049 }
2050 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07002051 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002052 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07002053 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002054 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002055 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002056 int type;
2057 while ((type = parser.next()) != XmlPullParser.START_TAG
2058 && type != XmlPullParser.END_DOCUMENT) {
Amith Yamasani12747872015-12-07 14:19:49 -08002059 // Skip
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002060 }
2061
2062 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07002063 Slog.e(LOG_TAG, "Unable to read user list");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002064 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002065 return;
2066 }
2067
Amith Yamasani2a003292012-08-14 18:25:45 -07002068 mNextSerialNumber = -1;
2069 if (parser.getName().equals(TAG_USERS)) {
2070 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
2071 if (lastSerialNumber != null) {
2072 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
2073 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07002074 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
2075 if (versionNumber != null) {
2076 mUserVersion = Integer.parseInt(versionNumber);
2077 }
Amith Yamasani2a003292012-08-14 18:25:45 -07002078 }
2079
Pavel Grafov6a40f092016-10-25 15:46:51 +01002080 // Pre-O global user restriction were stored as a single bundle (as opposed to per-user
2081 // currently), take care of it in case of upgrade.
2082 Bundle oldDevicePolicyGlobalUserRestrictions = null;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002083
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002084 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05302085 if (type == XmlPullParser.START_TAG) {
2086 final String name = parser.getName();
2087 if (name.equals(TAG_USER)) {
2088 String id = parser.getAttributeValue(null, ATTR_ID);
Amith Yamasani6f34b412012-10-22 18:19:27 -07002089
Amith Yamasani12747872015-12-07 14:19:49 -08002090 UserData userData = readUserLP(Integer.parseInt(id));
2091
2092 if (userData != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002093 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002094 mUsers.put(userData.info.id, userData);
2095 if (mNextSerialNumber < 0
2096 || mNextSerialNumber <= userData.info.id) {
2097 mNextSerialNumber = userData.info.id + 1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002098 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05302099 }
Amith Yamasani2a003292012-08-14 18:25:45 -07002100 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05302101 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -08002102 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2103 && type != XmlPullParser.END_TAG) {
2104 if (type == XmlPullParser.START_TAG) {
2105 if (parser.getName().equals(TAG_RESTRICTIONS)) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002106 synchronized (mGuestRestrictions) {
Fyodor Kupoloveafee022017-03-15 17:09:04 -07002107 UserRestrictionsUtils
2108 .readRestrictions(parser, mGuestRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002109 }
Amith Yamasanida0b1682014-11-21 12:58:17 -08002110 }
2111 break;
2112 }
2113 }
Pavel Grafov6a40f092016-10-25 15:46:51 +01002114 } else if (name.equals(TAG_DEVICE_OWNER_USER_ID)
2115 // Legacy name, should only be encountered when upgrading from pre-O.
2116 || name.equals(TAG_GLOBAL_RESTRICTION_OWNER_ID)) {
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01002117 String ownerUserId = parser.getAttributeValue(null, ATTR_ID);
2118 if (ownerUserId != null) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01002119 mDeviceOwnerUserId = Integer.parseInt(ownerUserId);
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01002120 }
Pavel Grafov6a40f092016-10-25 15:46:51 +01002121 } else if (name.equals(TAG_DEVICE_POLICY_RESTRICTIONS)) {
2122 // Should only happen when upgrading from pre-O (version < 7).
2123 oldDevicePolicyGlobalUserRestrictions =
2124 UserRestrictionsUtils.readRestrictions(parser);
Amith Yamasani258848d2012-08-10 17:06:33 -07002125 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002126 }
2127 }
Pavel Grafov6a40f092016-10-25 15:46:51 +01002128
Fyodor Kupolov82402752015-10-28 14:54:51 -07002129 updateUserIds();
Pavel Grafov6a40f092016-10-25 15:46:51 +01002130 upgradeIfNecessaryLP(oldDevicePolicyGlobalUserRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002131 } catch (IOException | XmlPullParserException e) {
2132 fallbackToSingleUserLP();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08002133 } finally {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002134 IoUtils.closeQuietly(fis);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002135 }
2136 }
2137
Amith Yamasani6f34b412012-10-22 18:19:27 -07002138 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -08002139 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Pavel Grafov6a40f092016-10-25 15:46:51 +01002140 * @param oldGlobalUserRestrictions Pre-O global device policy restrictions.
Amith Yamasani6f34b412012-10-22 18:19:27 -07002141 */
Andreas Gampe2e8c7672018-07-20 13:01:08 -07002142 @GuardedBy({"mRestrictionsLock", "mPackagesLock"})
Pavel Grafov6a40f092016-10-25 15:46:51 +01002143 private void upgradeIfNecessaryLP(Bundle oldGlobalUserRestrictions) {
Bookatz75f0a072019-08-05 14:12:16 -07002144 Set<Integer> userIdsToWrite = new ArraySet<>();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002145 final int originalVersion = mUserVersion;
Amith Yamasani6f34b412012-10-22 18:19:27 -07002146 int userVersion = mUserVersion;
2147 if (userVersion < 1) {
2148 // Assign a proper name for the owner, if not initialized correctly before
Amith Yamasani12747872015-12-07 14:19:49 -08002149 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
2150 if ("Primary".equals(userData.info.name)) {
2151 userData.info.name =
2152 mContext.getResources().getString(com.android.internal.R.string.owner_name);
Bookatz75f0a072019-08-05 14:12:16 -07002153 userIdsToWrite.add(userData.info.id);
Amith Yamasani6f34b412012-10-22 18:19:27 -07002154 }
2155 userVersion = 1;
2156 }
2157
Amith Yamasanibc9625052012-11-15 14:39:18 -08002158 if (userVersion < 2) {
2159 // Owner should be marked as initialized
Amith Yamasani12747872015-12-07 14:19:49 -08002160 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
2161 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
2162 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
Bookatz75f0a072019-08-05 14:12:16 -07002163 userIdsToWrite.add(userData.info.id);
Amith Yamasanibc9625052012-11-15 14:39:18 -08002164 }
2165 userVersion = 2;
2166 }
2167
Amith Yamasani350962c2013-08-06 11:18:53 -07002168
Amith Yamasani5e486f52013-08-07 11:06:44 -07002169 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -07002170 userVersion = 4;
2171 }
2172
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07002173 if (userVersion < 5) {
2174 initDefaultGuestRestrictions();
2175 userVersion = 5;
2176 }
2177
Fyodor Kupolov1c363152015-09-02 13:27:21 -07002178 if (userVersion < 6) {
2179 final boolean splitSystemUser = UserManager.isSplitSystemUser();
Fyodor Kupolov82402752015-10-28 14:54:51 -07002180 synchronized (mUsersLock) {
2181 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002182 UserData userData = mUsers.valueAt(i);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002183 // In non-split mode, only user 0 can have restricted profiles
Amith Yamasani12747872015-12-07 14:19:49 -08002184 if (!splitSystemUser && userData.info.isRestricted()
2185 && (userData.info.restrictedProfileParentId
2186 == UserInfo.NO_PROFILE_GROUP_ID)) {
2187 userData.info.restrictedProfileParentId = UserHandle.USER_SYSTEM;
Bookatz75f0a072019-08-05 14:12:16 -07002188 userIdsToWrite.add(userData.info.id);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002189 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07002190 }
2191 }
2192 userVersion = 6;
2193 }
2194
Pavel Grafov6a40f092016-10-25 15:46:51 +01002195 if (userVersion < 7) {
2196 // Previously only one user could enforce global restrictions, now it is per-user.
2197 synchronized (mRestrictionsLock) {
2198 if (!UserRestrictionsUtils.isEmpty(oldGlobalUserRestrictions)
2199 && mDeviceOwnerUserId != UserHandle.USER_NULL) {
2200 mDevicePolicyGlobalUserRestrictions.put(
2201 mDeviceOwnerUserId, oldGlobalUserRestrictions);
2202 }
2203 // ENSURE_VERIFY_APPS is now enforced globally even if put by profile owner, so move
2204 // it from local to global bundle for all users who set it.
2205 UserRestrictionsUtils.moveRestriction(UserManager.ENSURE_VERIFY_APPS,
2206 mDevicePolicyLocalUserRestrictions, mDevicePolicyGlobalUserRestrictions
2207 );
2208 }
2209 userVersion = 7;
2210 }
2211
Bookatz75f0a072019-08-05 14:12:16 -07002212 if (userVersion < 8) {
2213 // Added FLAG_FULL and FLAG_SYSTEM flags.
2214 synchronized (mUsersLock) {
2215 UserData userData = mUsers.get(UserHandle.USER_SYSTEM);
2216 userData.info.flags |= UserInfo.FLAG_SYSTEM;
2217 if (!UserManager.isHeadlessSystemUserMode()) {
2218 userData.info.flags |= UserInfo.FLAG_FULL;
2219 }
2220 userIdsToWrite.add(userData.info.id);
2221
2222 // Mark FULL all non-profile users except USER_SYSTEM.
2223 // Start index at 1 since USER_SYSTEM is the smallest userId and we're skipping it.
2224 for (int i = 1; i < mUsers.size(); i++) {
2225 userData = mUsers.valueAt(i);
2226 if ((userData.info.flags & UserInfo.FLAG_MANAGED_PROFILE) == 0) {
2227 userData.info.flags |= UserInfo.FLAG_FULL;
2228 userIdsToWrite.add(userData.info.id);
2229 }
2230 }
2231 }
2232 userVersion = 8;
2233 }
2234
Amith Yamasani6f34b412012-10-22 18:19:27 -07002235 if (userVersion < USER_VERSION) {
2236 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
2237 + USER_VERSION);
2238 } else {
2239 mUserVersion = userVersion;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002240
2241 if (originalVersion < mUserVersion) {
Bookatz75f0a072019-08-05 14:12:16 -07002242 for (int userId : userIdsToWrite) {
2243 UserData userData = getUserDataNoChecks(userId);
2244 if (userData != null) {
2245 writeUserLP(userData);
2246 }
2247 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002248 writeUserListLP();
2249 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07002250 }
2251 }
2252
Andreas Gampe2e8c7672018-07-20 13:01:08 -07002253 @GuardedBy({"mPackagesLock", "mRestrictionsLock"})
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002254 private void fallbackToSingleUserLP() {
Bookatz75f0a072019-08-05 14:12:16 -07002255 int flags = UserInfo.FLAG_SYSTEM | UserInfo.FLAG_INITIALIZED;
Ying Zhengcbe643a2019-07-03 18:11:25 +00002256 // In split system user mode, the admin and primary flags are assigned to the first human
2257 // user.
2258 if (!UserManager.isSplitSystemUser()) {
2259 flags |= UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY;
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07002260 }
Bookatz75f0a072019-08-05 14:12:16 -07002261 if (!UserManager.isHeadlessSystemUserMode()) {
2262 flags |= UserInfo.FLAG_FULL;
2263 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -07002264 // Create the system user
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07002265 UserInfo system = new UserInfo(UserHandle.USER_SYSTEM, null, null, flags);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002266 UserData userData = putUserInfo(system);
Amith Yamasani634cf312012-10-04 17:34:21 -07002267 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -04002268 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -08002269
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05002270 Bundle restrictions = new Bundle();
Mahaver Chopra3d9805d2016-07-07 16:25:05 +01002271 try {
2272 final String[] defaultFirstUserRestrictions = mContext.getResources().getStringArray(
2273 com.android.internal.R.array.config_defaultFirstUserRestrictions);
2274 for (String userRestriction : defaultFirstUserRestrictions) {
2275 if (UserRestrictionsUtils.isValidRestriction(userRestriction)) {
2276 restrictions.putBoolean(userRestriction, true);
2277 }
2278 }
2279 } catch (Resources.NotFoundException e) {
2280 Log.e(LOG_TAG, "Couldn't find resource: config_defaultFirstUserRestrictions", e);
2281 }
2282
Pavel Grafov6a40f092016-10-25 15:46:51 +01002283 if (!restrictions.isEmpty()) {
2284 synchronized (mRestrictionsLock) {
2285 mBaseUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions);
2286 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07002287 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08002288
Fyodor Kupolov82402752015-10-28 14:54:51 -07002289 updateUserIds();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07002290 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002291
Amith Yamasani12747872015-12-07 14:19:49 -08002292 writeUserLP(userData);
Jeff Sharkeycd575992016-03-29 14:12:49 -06002293 writeUserListLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002294 }
2295
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07002296 private String getOwnerName() {
2297 return mContext.getResources().getString(com.android.internal.R.string.owner_name);
2298 }
2299
Bookatz75f0a072019-08-05 14:12:16 -07002300 private void scheduleWriteUser(UserData userData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002301 if (DBG) {
2302 debug("scheduleWriteUser");
2303 }
Makoto Onuki9e935a32015-11-06 14:24:24 -08002304 // No need to wrap it within a lock -- worst case, we'll just post the same message
2305 // twice.
Bookatz75f0a072019-08-05 14:12:16 -07002306 if (!mHandler.hasMessages(WRITE_USER_MSG, userData)) {
2307 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, userData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002308 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
2309 }
2310 }
2311
Amith Yamasani12747872015-12-07 14:19:49 -08002312 private void writeUserLP(UserData userData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002313 if (DBG) {
Amith Yamasani12747872015-12-07 14:19:49 -08002314 debug("writeUserLP " + userData);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002315 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002316 FileOutputStream fos = null;
Amith Yamasani12747872015-12-07 14:19:49 -08002317 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userData.info.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002318 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07002319 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002320 final BufferedOutputStream bos = new BufferedOutputStream(fos);
Kenny Guy02c89902016-11-15 19:36:38 +00002321 writeUserLP(userData, bos);
Amith Yamasani2a003292012-08-14 18:25:45 -07002322 userFile.finishWrite(fos);
2323 } catch (Exception ioe) {
Jeff Sharkeycd575992016-03-29 14:12:49 -06002324 Slog.e(LOG_TAG, "Error writing user info " + userData.info.id, ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -07002325 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002326 }
2327 }
2328
2329 /*
Kenny Guy02c89902016-11-15 19:36:38 +00002330 * Writes the user file in this format:
2331 *
2332 * <user flags="20039023" id="0">
2333 * <name>Primary</name>
2334 * </user>
2335 */
2336 @VisibleForTesting
2337 void writeUserLP(UserData userData, OutputStream os)
2338 throws IOException, XmlPullParserException {
2339 // XmlSerializer serializer = XmlUtils.serializerInstance();
2340 final XmlSerializer serializer = new FastXmlSerializer();
2341 serializer.setOutput(os, StandardCharsets.UTF_8.name());
2342 serializer.startDocument(null, true);
2343 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2344
2345 final UserInfo userInfo = userData.info;
2346 serializer.startTag(null, TAG_USER);
2347 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
2348 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
2349 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
2350 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
2351 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
2352 Long.toString(userInfo.lastLoggedInTime));
2353 if (userInfo.lastLoggedInFingerprint != null) {
2354 serializer.attribute(null, ATTR_LAST_LOGGED_IN_FINGERPRINT,
2355 userInfo.lastLoggedInFingerprint);
2356 }
2357 if (userInfo.iconPath != null) {
2358 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
2359 }
2360 if (userInfo.partial) {
2361 serializer.attribute(null, ATTR_PARTIAL, "true");
2362 }
2363 if (userInfo.guestToRemove) {
2364 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
2365 }
2366 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
2367 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
2368 Integer.toString(userInfo.profileGroupId));
2369 }
2370 serializer.attribute(null, ATTR_PROFILE_BADGE,
2371 Integer.toString(userInfo.profileBadge));
2372 if (userInfo.restrictedProfileParentId != UserInfo.NO_PROFILE_GROUP_ID) {
2373 serializer.attribute(null, ATTR_RESTRICTED_PROFILE_PARENT_ID,
2374 Integer.toString(userInfo.restrictedProfileParentId));
2375 }
2376 // Write seed data
2377 if (userData.persistSeedData) {
2378 if (userData.seedAccountName != null) {
2379 serializer.attribute(null, ATTR_SEED_ACCOUNT_NAME, userData.seedAccountName);
2380 }
2381 if (userData.seedAccountType != null) {
2382 serializer.attribute(null, ATTR_SEED_ACCOUNT_TYPE, userData.seedAccountType);
2383 }
2384 }
2385 if (userInfo.name != null) {
2386 serializer.startTag(null, TAG_NAME);
2387 serializer.text(userInfo.name);
2388 serializer.endTag(null, TAG_NAME);
2389 }
2390 synchronized (mRestrictionsLock) {
2391 UserRestrictionsUtils.writeRestrictions(serializer,
2392 mBaseUserRestrictions.get(userInfo.id), TAG_RESTRICTIONS);
2393 UserRestrictionsUtils.writeRestrictions(serializer,
2394 mDevicePolicyLocalUserRestrictions.get(userInfo.id),
2395 TAG_DEVICE_POLICY_RESTRICTIONS);
Pavel Grafov6a40f092016-10-25 15:46:51 +01002396 UserRestrictionsUtils.writeRestrictions(serializer,
2397 mDevicePolicyGlobalUserRestrictions.get(userInfo.id),
2398 TAG_DEVICE_POLICY_GLOBAL_RESTRICTIONS);
Kenny Guy02c89902016-11-15 19:36:38 +00002399 }
2400
2401 if (userData.account != null) {
2402 serializer.startTag(null, TAG_ACCOUNT);
2403 serializer.text(userData.account);
2404 serializer.endTag(null, TAG_ACCOUNT);
2405 }
2406
2407 if (userData.persistSeedData && userData.seedAccountOptions != null) {
2408 serializer.startTag(null, TAG_SEED_ACCOUNT_OPTIONS);
2409 userData.seedAccountOptions.saveToXml(serializer);
2410 serializer.endTag(null, TAG_SEED_ACCOUNT_OPTIONS);
2411 }
2412
arangelov9b632d72018-12-07 23:21:22 +00002413 if (userData.getLastRequestQuietModeEnabledMillis() != 0L) {
2414 serializer.startTag(/* namespace */ null, TAG_LAST_REQUEST_QUIET_MODE_ENABLED_CALL);
2415 serializer.text(String.valueOf(userData.getLastRequestQuietModeEnabledMillis()));
2416 serializer.endTag(/* namespace */ null, TAG_LAST_REQUEST_QUIET_MODE_ENABLED_CALL);
2417 }
2418
Kenny Guy02c89902016-11-15 19:36:38 +00002419 serializer.endTag(null, TAG_USER);
2420
2421 serializer.endDocument();
2422 }
2423
2424 /*
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002425 * Writes the user list file in this format:
2426 *
Amith Yamasani2a003292012-08-14 18:25:45 -07002427 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002428 * <user id="0"></user>
2429 * <user id="2"></user>
2430 * </users>
2431 */
Andreas Gampe2e8c7672018-07-20 13:01:08 -07002432 @GuardedBy({"mRestrictionsLock", "mPackagesLock"})
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002433 private void writeUserListLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002434 if (DBG) {
2435 debug("writeUserList");
2436 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002437 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07002438 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002439 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07002440 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002441 final BufferedOutputStream bos = new BufferedOutputStream(fos);
2442
2443 // XmlSerializer serializer = XmlUtils.serializerInstance();
2444 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002445 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002446 serializer.startDocument(null, true);
2447 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2448
2449 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -07002450 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -07002451 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002452
Adam Lesinskieddeb492014-09-08 17:50:03 -07002453 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002454 synchronized (mGuestRestrictions) {
2455 UserRestrictionsUtils
2456 .writeRestrictions(serializer, mGuestRestrictions, TAG_RESTRICTIONS);
2457 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05302458 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Pavel Grafov6a40f092016-10-25 15:46:51 +01002459 serializer.startTag(null, TAG_DEVICE_OWNER_USER_ID);
2460 serializer.attribute(null, ATTR_ID, Integer.toString(mDeviceOwnerUserId));
2461 serializer.endTag(null, TAG_DEVICE_OWNER_USER_ID);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002462 int[] userIdsToWrite;
2463 synchronized (mUsersLock) {
2464 userIdsToWrite = new int[mUsers.size()];
2465 for (int i = 0; i < userIdsToWrite.length; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002466 UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002467 userIdsToWrite[i] = user.id;
2468 }
2469 }
2470 for (int id : userIdsToWrite) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002471 serializer.startTag(null, TAG_USER);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002472 serializer.attribute(null, ATTR_ID, Integer.toString(id));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002473 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002474 }
2475
2476 serializer.endTag(null, TAG_USERS);
2477
2478 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07002479 userListFile.finishWrite(fos);
2480 } catch (Exception e) {
2481 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -07002482 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002483 }
2484 }
2485
Amith Yamasani12747872015-12-07 14:19:49 -08002486 private UserData readUserLP(int id) {
Kenny Guy02c89902016-11-15 19:36:38 +00002487 FileInputStream fis = null;
2488 try {
2489 AtomicFile userFile =
2490 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
2491 fis = userFile.openRead();
2492 return readUserLP(id, fis);
2493 } catch (IOException ioe) {
2494 Slog.e(LOG_TAG, "Error reading user list");
2495 } catch (XmlPullParserException pe) {
2496 Slog.e(LOG_TAG, "Error reading user list");
2497 } finally {
2498 IoUtils.closeQuietly(fis);
2499 }
2500 return null;
2501 }
2502
2503 @VisibleForTesting
2504 UserData readUserLP(int id, InputStream is) throws IOException,
2505 XmlPullParserException {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002506 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -07002507 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002508 String name = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -08002509 String account = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002510 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -07002511 long creationTime = 0L;
2512 long lastLoggedInTime = 0L;
arangelov9b632d72018-12-07 23:21:22 +00002513 long lastRequestQuietModeEnabledTimestamp = 0L;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002514 String lastLoggedInFingerprint = null;
Kenny Guy2a764942014-04-02 13:29:20 +01002515 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Kenny Guy02c89902016-11-15 19:36:38 +00002516 int profileBadge = 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002517 int restrictedProfileParentId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002518 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -07002519 boolean guestToRemove = false;
Amith Yamasani12747872015-12-07 14:19:49 -08002520 boolean persistSeedData = false;
2521 String seedAccountName = null;
2522 String seedAccountType = null;
2523 PersistableBundle seedAccountOptions = null;
Pavel Grafov6a40f092016-10-25 15:46:51 +01002524 Bundle baseRestrictions = null;
2525 Bundle localRestrictions = null;
2526 Bundle globalRestrictions = null;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002527
Kenny Guy02c89902016-11-15 19:36:38 +00002528 XmlPullParser parser = Xml.newPullParser();
2529 parser.setInput(is, StandardCharsets.UTF_8.name());
2530 int type;
2531 while ((type = parser.next()) != XmlPullParser.START_TAG
2532 && type != XmlPullParser.END_DOCUMENT) {
2533 // Skip
2534 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002535
Kenny Guy02c89902016-11-15 19:36:38 +00002536 if (type != XmlPullParser.START_TAG) {
2537 Slog.e(LOG_TAG, "Unable to read user " + id);
2538 return null;
2539 }
2540
2541 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
2542 int storedId = readIntAttribute(parser, ATTR_ID, -1);
2543 if (storedId != id) {
2544 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002545 return null;
2546 }
Kenny Guy02c89902016-11-15 19:36:38 +00002547 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
2548 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
2549 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
2550 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
2551 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
2552 lastLoggedInFingerprint = parser.getAttributeValue(null,
2553 ATTR_LAST_LOGGED_IN_FINGERPRINT);
2554 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
2555 UserInfo.NO_PROFILE_GROUP_ID);
2556 profileBadge = readIntAttribute(parser, ATTR_PROFILE_BADGE, 0);
2557 restrictedProfileParentId = readIntAttribute(parser,
2558 ATTR_RESTRICTED_PROFILE_PARENT_ID, UserInfo.NO_PROFILE_GROUP_ID);
2559 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
2560 if ("true".equals(valueString)) {
2561 partial = true;
2562 }
2563 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
2564 if ("true".equals(valueString)) {
2565 guestToRemove = true;
2566 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002567
Kenny Guy02c89902016-11-15 19:36:38 +00002568 seedAccountName = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_NAME);
2569 seedAccountType = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_TYPE);
2570 if (seedAccountName != null || seedAccountType != null) {
2571 persistSeedData = true;
2572 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002573
Kenny Guy02c89902016-11-15 19:36:38 +00002574 int outerDepth = parser.getDepth();
2575 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2576 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2577 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2578 continue;
2579 }
2580 String tag = parser.getName();
2581 if (TAG_NAME.equals(tag)) {
2582 type = parser.next();
2583 if (type == XmlPullParser.TEXT) {
2584 name = parser.getText();
2585 }
2586 } else if (TAG_RESTRICTIONS.equals(tag)) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01002587 baseRestrictions = UserRestrictionsUtils.readRestrictions(parser);
Kenny Guy02c89902016-11-15 19:36:38 +00002588 } else if (TAG_DEVICE_POLICY_RESTRICTIONS.equals(tag)) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01002589 localRestrictions = UserRestrictionsUtils.readRestrictions(parser);
2590 } else if (TAG_DEVICE_POLICY_GLOBAL_RESTRICTIONS.equals(tag)) {
2591 globalRestrictions = UserRestrictionsUtils.readRestrictions(parser);
Kenny Guy02c89902016-11-15 19:36:38 +00002592 } else if (TAG_ACCOUNT.equals(tag)) {
2593 type = parser.next();
2594 if (type == XmlPullParser.TEXT) {
2595 account = parser.getText();
2596 }
2597 } else if (TAG_SEED_ACCOUNT_OPTIONS.equals(tag)) {
2598 seedAccountOptions = PersistableBundle.restoreFromXml(parser);
Amith Yamasani12747872015-12-07 14:19:49 -08002599 persistSeedData = true;
arangelov9b632d72018-12-07 23:21:22 +00002600 } else if (TAG_LAST_REQUEST_QUIET_MODE_ENABLED_CALL.equals(tag)) {
2601 type = parser.next();
2602 if (type == XmlPullParser.TEXT) {
2603 lastRequestQuietModeEnabledTimestamp = Long.parseLong(parser.getText());
2604 }
Amith Yamasani12747872015-12-07 14:19:49 -08002605 }
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08002606 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002607 }
Kenny Guy02c89902016-11-15 19:36:38 +00002608
2609 // Create the UserInfo object that gets passed around
2610 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
2611 userInfo.serialNumber = serialNumber;
2612 userInfo.creationTime = creationTime;
2613 userInfo.lastLoggedInTime = lastLoggedInTime;
2614 userInfo.lastLoggedInFingerprint = lastLoggedInFingerprint;
2615 userInfo.partial = partial;
2616 userInfo.guestToRemove = guestToRemove;
2617 userInfo.profileGroupId = profileGroupId;
2618 userInfo.profileBadge = profileBadge;
2619 userInfo.restrictedProfileParentId = restrictedProfileParentId;
2620
2621 // Create the UserData object that's internal to this class
2622 UserData userData = new UserData();
2623 userData.info = userInfo;
2624 userData.account = account;
2625 userData.seedAccountName = seedAccountName;
2626 userData.seedAccountType = seedAccountType;
2627 userData.persistSeedData = persistSeedData;
2628 userData.seedAccountOptions = seedAccountOptions;
arangelov9b632d72018-12-07 23:21:22 +00002629 userData.setLastRequestQuietModeEnabledMillis(lastRequestQuietModeEnabledTimestamp);
Kenny Guy02c89902016-11-15 19:36:38 +00002630
2631 synchronized (mRestrictionsLock) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01002632 if (baseRestrictions != null) {
2633 mBaseUserRestrictions.put(id, baseRestrictions);
2634 }
2635 if (localRestrictions != null) {
2636 mDevicePolicyLocalUserRestrictions.put(id, localRestrictions);
2637 }
2638 if (globalRestrictions != null) {
2639 mDevicePolicyGlobalUserRestrictions.put(id, globalRestrictions);
2640 }
Kenny Guy02c89902016-11-15 19:36:38 +00002641 }
2642 return userData;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002643 }
2644
Amith Yamasani920ace02012-09-20 22:15:37 -07002645 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
2646 String valueString = parser.getAttributeValue(null, attr);
2647 if (valueString == null) return defaultValue;
2648 try {
2649 return Integer.parseInt(valueString);
2650 } catch (NumberFormatException nfe) {
2651 return defaultValue;
2652 }
2653 }
2654
2655 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
2656 String valueString = parser.getAttributeValue(null, attr);
2657 if (valueString == null) return defaultValue;
2658 try {
2659 return Long.parseLong(valueString);
2660 } catch (NumberFormatException nfe) {
2661 return defaultValue;
2662 }
2663 }
2664
Amith Yamasanib82add22013-07-09 11:24:44 -07002665 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002666 * Removes the app restrictions file for a specific package and user id, if it exists.
2667 */
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07002668 private static void cleanAppRestrictionsForPackageLAr(String pkg, int userId) {
2669 File dir = Environment.getUserSystemDirectory(userId);
2670 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
2671 if (resFile.exists()) {
2672 resFile.delete();
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002673 }
2674 }
2675
Kenny Guya52dc3e2014-02-11 15:33:14 +00002676 @Override
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002677 public UserInfo createProfileForUser(String name, int flags, int userId,
2678 String[] disallowedPackages) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002679 checkManageOrCreateUsersPermission(flags);
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002680 return createUserInternal(name, flags, userId, disallowedPackages);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002681 }
2682
Amith Yamasani258848d2012-08-10 17:06:33 -07002683 @Override
Tony Mak6dc428f2016-10-10 15:48:27 +01002684 public UserInfo createProfileForUserEvenWhenDisallowed(String name, int flags, int userId,
2685 String[] disallowedPackages) {
2686 checkManageOrCreateUsersPermission(flags);
2687 return createUserInternalUnchecked(name, flags, userId, disallowedPackages);
2688 }
2689
2690 @Override
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00002691 public boolean removeUserEvenWhenDisallowed(@UserIdInt int userHandle) {
2692 checkManageOrCreateUsersPermission("Only the system can remove users");
2693 return removeUserUnchecked(userHandle);
2694 }
2695
2696 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07002697 public UserInfo createUser(String name, int flags) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002698 checkManageOrCreateUsersPermission(flags);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00002699 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002700 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07002701
Jessica Hummelbe81c802014-04-22 15:49:22 +01002702 private UserInfo createUserInternal(String name, int flags, int parentId) {
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002703 return createUserInternal(name, flags, parentId, null);
2704 }
2705
2706 private UserInfo createUserInternal(String name, int flags, int parentId,
2707 String[] disallowedPackages) {
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002708 String restriction = ((flags & UserInfo.FLAG_MANAGED_PROFILE) != 0)
2709 ? UserManager.DISALLOW_ADD_MANAGED_PROFILE
2710 : UserManager.DISALLOW_ADD_USER;
2711 if (hasUserRestriction(restriction, UserHandle.getCallingUserId())) {
2712 Log.w(LOG_TAG, "Cannot add user. " + restriction + " is enabled.");
Julia Reynolds75175022014-06-26 16:35:00 -04002713 return null;
2714 }
Tony Mak6dc428f2016-10-10 15:48:27 +01002715 return createUserInternalUnchecked(name, flags, parentId, disallowedPackages);
2716 }
2717
2718 private UserInfo createUserInternalUnchecked(String name, int flags, int parentId,
2719 String[] disallowedPackages) {
Suprabh Shuklac5e057c2016-08-08 16:22:44 -07002720 DeviceStorageMonitorInternal dsm = LocalServices
2721 .getService(DeviceStorageMonitorInternal.class);
2722 if (dsm.isMemoryLow()) {
2723 Log.w(LOG_TAG, "Cannot add user. Not enough space on disk.");
2724 return null;
2725 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07002726 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Nicolas Prevot12678a92015-05-13 12:15:03 -07002727 final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002728 final boolean isRestricted = (flags & UserInfo.FLAG_RESTRICTED) != 0;
Amith Yamasani52c21e32016-05-31 09:12:20 -07002729 final boolean isDemo = (flags & UserInfo.FLAG_DEMO) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002730 final long ident = Binder.clearCallingIdentity();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002731 UserInfo userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08002732 UserData userData;
Amith Yamasanibb054c92015-07-09 14:16:27 -07002733 final int userId;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002734 try {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002735 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002736 UserData parent = null;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002737 if (parentId != UserHandle.USER_NULL) {
2738 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002739 parent = getUserDataLU(parentId);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00002740 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002741 if (parent == null) return null;
2742 }
2743 if (isManagedProfile && !canAddMoreManagedProfiles(parentId, false)) {
2744 Log.e(LOG_TAG, "Cannot add more managed profiles for user " + parentId);
2745 return null;
2746 }
Amith Yamasani52c21e32016-05-31 09:12:20 -07002747 if (!isGuest && !isManagedProfile && !isDemo && isUserLimitReached()) {
2748 // If we're not adding a guest/demo user or a managed profile and the limit has
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002749 // been reached, cannot add a user.
jovanaka6763a32018-12-03 17:23:20 -08002750 Log.e(LOG_TAG, "Cannot add user. Maximum user limit is reached.");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002751 return null;
2752 }
2753 // If we're adding a guest and there already exists one, bail.
2754 if (isGuest && findCurrentGuestUser() != null) {
jovanaka6763a32018-12-03 17:23:20 -08002755 Log.e(LOG_TAG, "Cannot add guest user. Guest user already exists.");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002756 return null;
2757 }
2758 // In legacy mode, restricted profile's parent can only be the owner user
2759 if (isRestricted && !UserManager.isSplitSystemUser()
2760 && (parentId != UserHandle.USER_SYSTEM)) {
2761 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
2762 return null;
2763 }
2764 if (isRestricted && UserManager.isSplitSystemUser()) {
2765 if (parent == null) {
2766 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be "
2767 + "specified");
Nicolas Prevot12678a92015-05-13 12:15:03 -07002768 return null;
2769 }
Amith Yamasani12747872015-12-07 14:19:49 -08002770 if (!parent.info.canHaveProfile()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002771 Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be "
2772 + "created for the specified parent user id " + parentId);
Amith Yamasani95ab7842014-08-11 17:09:26 -07002773 return null;
2774 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002775 }
Ying Zhengcbe643a2019-07-03 18:11:25 +00002776 // In split system user mode, we assign the first human user the primary flag.
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002777 // And if there is no device owner, we also assign the admin flag to primary user.
Ying Zhengcbe643a2019-07-03 18:11:25 +00002778 if (UserManager.isSplitSystemUser()
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002779 && !isGuest && !isManagedProfile && getPrimaryUser() == null) {
2780 flags |= UserInfo.FLAG_PRIMARY;
Makoto Onukie7927da2015-11-25 10:05:17 -08002781 synchronized (mUsersLock) {
2782 if (!mIsDeviceManaged) {
2783 flags |= UserInfo.FLAG_ADMIN;
2784 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07002785 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002786 }
Bookatz75f0a072019-08-05 14:12:16 -07002787 if (!isManagedProfile) {
2788 // New users cannot be system, and it's not a profile, so per-force it's FULL.
2789 flags |= UserInfo.FLAG_FULL;
2790 }
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002791
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002792 userId = getNextAvailableId();
2793 Environment.getUserSystemDirectory(userId).mkdirs();
Lenka Trochtova02fee152015-12-22 14:26:18 +01002794 boolean ephemeralGuests = Resources.getSystem()
2795 .getBoolean(com.android.internal.R.bool.config_guestUserEphemeral);
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002796
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002797 synchronized (mUsersLock) {
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002798 // Add ephemeral flag to guests/users if required. Also inherit it from parent.
2799 if ((isGuest && ephemeralGuests) || mForceEphemeralUsers
2800 || (parent != null && parent.info.isEphemeral())) {
2801 flags |= UserInfo.FLAG_EPHEMERAL;
2802 }
2803
2804 userInfo = new UserInfo(userId, name, null, flags);
2805 userInfo.serialNumber = mNextSerialNumber++;
2806 long now = System.currentTimeMillis();
2807 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
2808 userInfo.partial = true;
Fyodor Kupolov83c24242016-03-31 13:30:42 -07002809 userInfo.lastLoggedInFingerprint = Build.FINGERPRINT;
Kenny Guy02c89902016-11-15 19:36:38 +00002810 if (isManagedProfile && parentId != UserHandle.USER_NULL) {
2811 userInfo.profileBadge = getFreeProfileBadgeLU(parentId);
2812 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002813 userData = new UserData();
2814 userData.info = userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08002815 mUsers.put(userId, userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002816 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06002817 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002818 writeUserListLP();
2819 if (parent != null) {
2820 if (isManagedProfile) {
Amith Yamasani12747872015-12-07 14:19:49 -08002821 if (parent.info.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
2822 parent.info.profileGroupId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002823 writeUserLP(parent);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002824 }
Amith Yamasani12747872015-12-07 14:19:49 -08002825 userInfo.profileGroupId = parent.info.profileGroupId;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002826 } else if (isRestricted) {
Amith Yamasani12747872015-12-07 14:19:49 -08002827 if (parent.info.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) {
2828 parent.info.restrictedProfileParentId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002829 writeUserLP(parent);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002830 }
Amith Yamasani12747872015-12-07 14:19:49 -08002831 userInfo.restrictedProfileParentId = parent.info.restrictedProfileParentId;
Makoto Onuki068c54a2015-10-13 14:34:03 -07002832 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002833 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07002834 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002835 final StorageManager storage = mContext.getSystemService(StorageManager.class);
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002836 storage.createUserKey(userId, userInfo.serialNumber, userInfo.isEphemeral());
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -08002837 mUserDataPreparer.prepareUserData(userId, userInfo.serialNumber,
Jeff Sharkey47f71082016-02-01 17:03:54 -07002838 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002839 mPm.createNewUser(userId, disallowedPackages);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002840 userInfo.partial = false;
2841 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002842 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002843 }
2844 updateUserIds();
2845 Bundle restrictions = new Bundle();
Fyodor Kupolove04462c2015-11-30 15:02:53 -08002846 if (isGuest) {
2847 synchronized (mGuestRestrictions) {
2848 restrictions.putAll(mGuestRestrictions);
2849 }
2850 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002851 synchronized (mRestrictionsLock) {
2852 mBaseUserRestrictions.append(userId, restrictions);
2853 }
Fyodor Kupolov5fd967d2016-07-12 14:46:19 -07002854 mPm.onNewUserCreated(userId);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002855 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
2856 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
2857 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
2858 android.Manifest.permission.MANAGE_USERS);
Christine Franks88220562017-05-24 11:11:21 -07002859 MetricsLogger.count(mContext, isGuest ? TRON_GUEST_CREATED
2860 : (isDemo ? TRON_DEMO_CREATED : TRON_USER_CREATED), 1);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002861 } finally {
2862 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07002863 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002864 return userInfo;
2865 }
2866
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002867 @VisibleForTesting
2868 UserData putUserInfo(UserInfo userInfo) {
2869 final UserData userData = new UserData();
2870 userData.info = userInfo;
2871 synchronized (mUsers) {
2872 mUsers.put(userInfo.id, userData);
2873 }
2874 return userData;
2875 }
2876
2877 @VisibleForTesting
2878 void removeUserInfo(int userId) {
2879 synchronized (mUsers) {
2880 mUsers.remove(userId);
2881 }
2882 }
2883
Amith Yamasani0b285492011-04-14 17:35:23 -07002884 /**
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002885 * @hide
2886 */
Amith Yamasani12747872015-12-07 14:19:49 -08002887 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002888 public UserInfo createRestrictedProfile(String name, int parentUserId) {
Sudheer Shanka53d41472016-06-16 09:11:08 -07002889 checkManageOrCreateUsersPermission("setupRestrictedProfile");
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002890 final UserInfo user = createProfileForUser(
2891 name, UserInfo.FLAG_RESTRICTED, parentUserId, null);
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002892 if (user == null) {
2893 return null;
2894 }
Fyodor Kupolov9e912ba2016-02-09 18:29:43 -08002895 long identity = Binder.clearCallingIdentity();
2896 try {
2897 setUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, true, user.id);
2898 // Change the setting before applying the DISALLOW_SHARE_LOCATION restriction, otherwise
2899 // the putIntForUser() will fail.
2900 android.provider.Settings.Secure.putIntForUser(mContext.getContentResolver(),
2901 android.provider.Settings.Secure.LOCATION_MODE,
2902 android.provider.Settings.Secure.LOCATION_MODE_OFF, user.id);
2903 setUserRestriction(UserManager.DISALLOW_SHARE_LOCATION, true, user.id);
2904 } finally {
2905 Binder.restoreCallingIdentity(identity);
2906 }
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002907 return user;
2908 }
2909
2910 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07002911 * Find the current guest user. If the Guest user is partial,
2912 * then do not include it in the results as it is about to die.
Adam Lesinskieddeb492014-09-08 17:50:03 -07002913 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002914 private UserInfo findCurrentGuestUser() {
2915 synchronized (mUsersLock) {
2916 final int size = mUsers.size();
2917 for (int i = 0; i < size; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002918 final UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002919 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
2920 return user;
2921 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002922 }
2923 }
2924 return null;
2925 }
2926
2927 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07002928 * Mark this guest user for deletion to allow us to create another guest
2929 * and switch to that user before actually removing this guest.
2930 * @param userHandle the userid of the current guest
2931 * @return whether the user could be marked for deletion
2932 */
Amith Yamasani12747872015-12-07 14:19:49 -08002933 @Override
Amith Yamasani1df14732014-08-29 21:37:27 -07002934 public boolean markGuestForDeletion(int userHandle) {
2935 checkManageUsersPermission("Only the system can remove users");
2936 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
2937 UserManager.DISALLOW_REMOVE_USER, false)) {
2938 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
2939 return false;
2940 }
2941
2942 long ident = Binder.clearCallingIdentity();
2943 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002944 final UserData userData;
Amith Yamasani1df14732014-08-29 21:37:27 -07002945 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002946 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002947 userData = mUsers.get(userHandle);
2948 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002949 return false;
2950 }
Amith Yamasani1df14732014-08-29 21:37:27 -07002951 }
Amith Yamasani12747872015-12-07 14:19:49 -08002952 if (!userData.info.isGuest()) {
Amith Yamasani1df14732014-08-29 21:37:27 -07002953 return false;
2954 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002955 // We set this to a guest user that is to be removed. This is a temporary state
2956 // where we are allowed to add new Guest users, even if this one is still not
2957 // removed. This user will still show up in getUserInfo() calls.
2958 // If we don't get around to removing this Guest user, it will be purged on next
2959 // startup.
Amith Yamasani12747872015-12-07 14:19:49 -08002960 userData.info.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07002961 // Mark it as disabled, so that it isn't returned any more when
2962 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002963 userData.info.flags |= UserInfo.FLAG_DISABLED;
2964 writeUserLP(userData);
Amith Yamasani1df14732014-08-29 21:37:27 -07002965 }
2966 } finally {
2967 Binder.restoreCallingIdentity(ident);
2968 }
2969 return true;
2970 }
2971
2972 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002973 * Removes a user and all data directories created for that user. This method should be called
2974 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07002975 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07002976 */
Amith Yamasani12747872015-12-07 14:19:49 -08002977 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -07002978 public boolean removeUser(int userHandle) {
Fyodor Kupolov4593e422016-10-27 11:00:29 -07002979 Slog.i(LOG_TAG, "removeUser u" + userHandle);
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002980 checkManageOrCreateUsersPermission("Only the system can remove users");
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002981
2982 final boolean isManagedProfile;
2983 synchronized (mUsersLock) {
2984 UserInfo userInfo = getUserInfoLU(userHandle);
2985 isManagedProfile = userInfo != null && userInfo.isManagedProfile();
2986 }
2987 String restriction = isManagedProfile
2988 ? UserManager.DISALLOW_REMOVE_MANAGED_PROFILE : UserManager.DISALLOW_REMOVE_USER;
2989 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(restriction, false)) {
2990 Log.w(LOG_TAG, "Cannot remove user. " + restriction + " is enabled.");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04002991 return false;
2992 }
Nicolas Prevotdf1b87d2016-10-25 13:57:08 +01002993 return removeUserUnchecked(userHandle);
2994 }
Julia Reynolds4ac5f852014-06-23 17:38:51 -04002995
Nicolas Prevotdf1b87d2016-10-25 13:57:08 +01002996 private boolean removeUserUnchecked(int userHandle) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002997 long ident = Binder.clearCallingIdentity();
2998 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002999 final UserData userData;
Fyodor Kupolov0df68cd2015-10-01 13:54:22 -07003000 int currentUser = ActivityManager.getCurrentUser();
3001 if (currentUser == userHandle) {
jovanaka6763a32018-12-03 17:23:20 -08003002 Log.w(LOG_TAG, "Current user cannot be removed.");
Fyodor Kupolov0df68cd2015-10-01 13:54:22 -07003003 return false;
3004 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01003005 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003006 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08003007 userData = mUsers.get(userHandle);
jovanaka6763a32018-12-03 17:23:20 -08003008 if (userHandle == UserHandle.USER_SYSTEM) {
3009 Log.e(LOG_TAG, "System user cannot be removed.");
3010 return false;
3011 }
3012
3013 if (userData == null) {
3014 Log.e(LOG_TAG, String.format(
3015 "Cannot remove user %d, invalid user id provided.", userHandle));
3016 return false;
3017 }
3018
3019 if (mRemovingUserIds.get(userHandle)) {
3020 Log.e(LOG_TAG, String.format(
3021 "User %d is already scheduled for removal.", userHandle));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003022 return false;
3023 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08003024
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003025 addRemovingUserIdLocked(userHandle);
Fyodor Kupolov82402752015-10-28 14:54:51 -07003026 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08003027
Kenny Guyee58b4f2014-05-23 15:19:53 +01003028 // Set this to a partially created user, so that the user will be purged
3029 // on next startup, in case the runtime stops now before stopping and
3030 // removing the user completely.
Amith Yamasani12747872015-12-07 14:19:49 -08003031 userData.info.partial = true;
Kenny Guyee58b4f2014-05-23 15:19:53 +01003032 // Mark it as disabled, so that it isn't returned any more when
3033 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08003034 userData.info.flags |= UserInfo.FLAG_DISABLED;
3035 writeUserLP(userData);
Kenny Guyee58b4f2014-05-23 15:19:53 +01003036 }
Fyodor Kupolov6c96f7f2017-06-28 18:22:59 -07003037 try {
3038 mAppOpsService.removeUser(userHandle);
3039 } catch (RemoteException e) {
jovanaka6763a32018-12-03 17:23:20 -08003040 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user.", e);
Fyodor Kupolov6c96f7f2017-06-28 18:22:59 -07003041 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01003042
Amith Yamasani12747872015-12-07 14:19:49 -08003043 if (userData.info.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
3044 && userData.info.isManagedProfile()) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01003045 // Send broadcast to notify system that the user removed was a
3046 // managed user.
Amith Yamasani12747872015-12-07 14:19:49 -08003047 sendProfileRemovedBroadcast(userData.info.profileGroupId, userData.info.id);
Kenny Guyee58b4f2014-05-23 15:19:53 +01003048 }
3049
3050 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
3051 int res;
3052 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003053 res = ActivityManager.getService().stopUser(userHandle, /* force= */ true,
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07003054 new IStopUserCallback.Stub() {
Kenny Guyee58b4f2014-05-23 15:19:53 +01003055 @Override
3056 public void userStopped(int userId) {
3057 finishRemoveUser(userId);
3058 }
3059 @Override
3060 public void userStopAborted(int userId) {
3061 }
3062 });
3063 } catch (RemoteException e) {
jovanaka6763a32018-12-03 17:23:20 -08003064 Log.w(LOG_TAG, "Failed to stop user during removal.", e);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003065 return false;
3066 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01003067 return res == ActivityManager.USER_OP_SUCCESS;
3068 } finally {
3069 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003070 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003071 }
3072
Andreas Gampea36dc622018-02-05 17:19:22 -08003073 @GuardedBy("mUsersLock")
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003074 @VisibleForTesting
3075 void addRemovingUserIdLocked(int userId) {
3076 // We remember deleted user IDs to prevent them from being
3077 // reused during the current boot; they can still be reused
3078 // after a reboot or recycling of userIds.
3079 mRemovingUserIds.put(userId, true);
3080 mRecentlyRemovedIds.add(userId);
3081 // Keep LRU queue of recently removed IDs for recycling
3082 if (mRecentlyRemovedIds.size() > MAX_RECENTLY_REMOVED_IDS_SIZE) {
3083 mRecentlyRemovedIds.removeFirst();
3084 }
3085 }
3086
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07003087 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07003088 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07003089 // Let other services shutdown any activity and clean up their state before completely
3090 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07003091 long ident = Binder.clearCallingIdentity();
3092 try {
3093 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
3094 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07003095 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
3096 android.Manifest.permission.MANAGE_USERS,
3097
3098 new BroadcastReceiver() {
3099 @Override
3100 public void onReceive(Context context, Intent intent) {
3101 if (DBG) {
3102 Slog.i(LOG_TAG,
3103 "USER_REMOVED broadcast sent, cleaning up user data "
3104 + userHandle);
3105 }
3106 new Thread() {
Amith Yamasani12747872015-12-07 14:19:49 -08003107 @Override
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07003108 public void run() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003109 // Clean up any ActivityTaskManager state
3110 LocalServices.getService(ActivityTaskManagerInternal.class)
3111 .onUserStopped(userHandle);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003112 removeUserState(userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07003113 }
3114 }.start();
3115 }
3116 },
3117
3118 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07003119 } finally {
3120 Binder.restoreCallingIdentity(ident);
3121 }
Amith Yamasani2a003292012-08-14 18:25:45 -07003122 }
3123
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003124 private void removeUserState(final int userHandle) {
Paul Crowley91293792016-03-25 15:23:07 -07003125 try {
3126 mContext.getSystemService(StorageManager.class).destroyUserKey(userHandle);
3127 } catch (IllegalStateException e) {
3128 // This may be simply because the user was partially created.
3129 Slog.i(LOG_TAG,
3130 "Destroying key for user " + userHandle + " failed, continuing anyway", e);
3131 }
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06003132
Amith Yamasanid04aaa32016-06-13 12:09:36 -07003133 // Cleanup gatekeeper secure user id
3134 try {
3135 final IGateKeeperService gk = GateKeeper.getService();
3136 if (gk != null) {
3137 gk.clearSecureUserId(userHandle);
3138 }
3139 } catch (Exception ex) {
3140 Slog.w(LOG_TAG, "unable to clear GK secure user id");
3141 }
3142
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003143 // Cleanup package manager settings
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003144 mPm.cleanUpUser(this, userHandle);
Amith Yamasanid04aaa32016-06-13 12:09:36 -07003145
3146 // Clean up all data before removing metadata
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -08003147 mUserDataPreparer.destroyUserData(userHandle,
Amith Yamasanid04aaa32016-06-13 12:09:36 -07003148 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
3149
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003150 // Remove this user from the list
Fyodor Kupolov82402752015-10-28 14:54:51 -07003151 synchronized (mUsersLock) {
3152 mUsers.remove(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08003153 mIsUserManaged.delete(userHandle);
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003154 }
3155 synchronized (mUserStates) {
3156 mUserStates.delete(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08003157 }
3158 synchronized (mRestrictionsLock) {
3159 mBaseUserRestrictions.remove(userHandle);
3160 mAppliedUserRestrictions.remove(userHandle);
3161 mCachedEffectiveUserRestrictions.remove(userHandle);
3162 mDevicePolicyLocalUserRestrictions.remove(userHandle);
Pavel Grafov6a40f092016-10-25 15:46:51 +01003163 if (mDevicePolicyGlobalUserRestrictions.get(userHandle) != null) {
3164 mDevicePolicyGlobalUserRestrictions.remove(userHandle);
3165 applyUserRestrictionsForAllUsersLR();
3166 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07003167 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003168 // Update the user list
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003169 synchronized (mPackagesLock) {
3170 writeUserListLP();
3171 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06003172 // Remove user file
3173 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
3174 userFile.delete();
Fyodor Kupolov82402752015-10-28 14:54:51 -07003175 updateUserIds();
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003176 if (RELEASE_DELETED_USER_ID) {
3177 synchronized (mUsers) {
3178 mRemovingUserIds.delete(userHandle);
3179 }
3180 }
Amith Yamasani61f57372012-08-31 12:12:28 -07003181 }
3182
Kenny Guyf8d3a232014-05-15 16:09:52 +01003183 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01003184 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01003185 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
3186 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01003187 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
Jeff Sharkeyaf6ec292015-12-17 11:19:00 -07003188 managedProfileIntent.putExtra(Intent.EXTRA_USER_HANDLE, removedUserId);
Kenny Guyf8d3a232014-05-15 16:09:52 +01003189 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01003190 }
3191
Amith Yamasani2a003292012-08-14 18:25:45 -07003192 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07003193 public Bundle getApplicationRestrictions(String packageName) {
3194 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
3195 }
3196
3197 @Override
3198 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003199 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07003200 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07003201 checkSystemOrRoot("get application restrictions for other user/app " + packageName);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003202 }
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003203 synchronized (mAppRestrictionsLock) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003204 // Read the restrictions from XML
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003205 return readApplicationRestrictionsLAr(packageName, userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003206 }
3207 }
3208
3209 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07003210 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003211 int userId) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00003212 checkSystemOrRoot("set application restrictions");
Fyodor Kupolov0d88d542016-04-19 11:37:22 -07003213 if (restrictions != null) {
3214 restrictions.setDefusable(true);
3215 }
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003216 synchronized (mAppRestrictionsLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01003217 if (restrictions == null || restrictions.isEmpty()) {
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003218 cleanAppRestrictionsForPackageLAr(packageName, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01003219 } else {
3220 // Write the restrictions to XML
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003221 writeApplicationRestrictionsLAr(packageName, restrictions, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01003222 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003223 }
Robin Lee66e5d962014-04-09 16:44:21 +01003224
Fyodor Kupolovd2846122016-02-11 18:06:34 -08003225 // Notify package of changes via an intent - only sent to explicitly registered receivers.
3226 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
3227 changeIntent.setPackage(packageName);
3228 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3229 mContext.sendBroadcastAsUser(changeIntent, UserHandle.of(userId));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003230 }
3231
3232 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07003233 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003234 try {
3235 return mContext.getPackageManager().getApplicationInfo(packageName,
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07003236 PackageManager.MATCH_ANY_USER).uid;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003237 } catch (NameNotFoundException nnfe) {
3238 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07003239 } finally {
3240 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003241 }
3242 }
3243
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003244 @GuardedBy("mAppRestrictionsLock")
3245 private static Bundle readApplicationRestrictionsLAr(String packageName, int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003246 AtomicFile restrictionsFile =
3247 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
3248 packageToRestrictionsFileName(packageName)));
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003249 return readApplicationRestrictionsLAr(restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003250 }
3251
3252 @VisibleForTesting
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003253 @GuardedBy("mAppRestrictionsLock")
3254 static Bundle readApplicationRestrictionsLAr(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07003255 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003256 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07003257 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07003258 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07003259 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003260
3261 FileInputStream fis = null;
3262 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003263 fis = restrictionsFile.openRead();
3264 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01003265 parser.setInput(fis, StandardCharsets.UTF_8.name());
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003266 XmlUtils.nextElement(parser);
3267 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003268 Slog.e(LOG_TAG, "Unable to read restrictions file "
3269 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07003270 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003271 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003272 while (parser.next() != XmlPullParser.END_DOCUMENT) {
3273 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003274 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003275 } catch (IOException|XmlPullParserException e) {
3276 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003277 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003278 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003279 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07003280 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003281 }
3282
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003283 private static void readEntry(Bundle restrictions, ArrayList<String> values,
3284 XmlPullParser parser) throws XmlPullParserException, IOException {
3285 int type = parser.getEventType();
3286 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
3287 String key = parser.getAttributeValue(null, ATTR_KEY);
3288 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
3289 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
3290 if (multiple != null) {
3291 values.clear();
3292 int count = Integer.parseInt(multiple);
3293 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
3294 if (type == XmlPullParser.START_TAG
3295 && parser.getName().equals(TAG_VALUE)) {
3296 values.add(parser.nextText().trim());
3297 count--;
3298 }
3299 }
3300 String [] valueStrings = new String[values.size()];
3301 values.toArray(valueStrings);
3302 restrictions.putStringArray(key, valueStrings);
3303 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
3304 restrictions.putBundle(key, readBundleEntry(parser, values));
3305 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
3306 final int outerDepth = parser.getDepth();
3307 ArrayList<Bundle> bundleList = new ArrayList<>();
3308 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
3309 Bundle childBundle = readBundleEntry(parser, values);
3310 bundleList.add(childBundle);
3311 }
3312 restrictions.putParcelableArray(key,
3313 bundleList.toArray(new Bundle[bundleList.size()]));
3314 } else {
3315 String value = parser.nextText().trim();
3316 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
3317 restrictions.putBoolean(key, Boolean.parseBoolean(value));
3318 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
3319 restrictions.putInt(key, Integer.parseInt(value));
3320 } else {
3321 restrictions.putString(key, value);
3322 }
3323 }
3324 }
3325 }
3326
3327 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
3328 throws IOException, XmlPullParserException {
3329 Bundle childBundle = new Bundle();
3330 final int outerDepth = parser.getDepth();
3331 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
3332 readEntry(childBundle, values, parser);
3333 }
3334 return childBundle;
3335 }
3336
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003337 @GuardedBy("mAppRestrictionsLock")
3338 private static void writeApplicationRestrictionsLAr(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07003339 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003340 AtomicFile restrictionsFile = new AtomicFile(
3341 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07003342 packageToRestrictionsFileName(packageName)));
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003343 writeApplicationRestrictionsLAr(restrictions, restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003344 }
3345
3346 @VisibleForTesting
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003347 @GuardedBy("mAppRestrictionsLock")
3348 static void writeApplicationRestrictionsLAr(Bundle restrictions, AtomicFile restrictionsFile) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003349 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003350 try {
3351 fos = restrictionsFile.startWrite();
3352 final BufferedOutputStream bos = new BufferedOutputStream(fos);
3353
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003354 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01003355 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003356 serializer.startDocument(null, true);
3357 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
3358
3359 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003360 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003361 serializer.endTag(null, TAG_RESTRICTIONS);
3362
3363 serializer.endDocument();
3364 restrictionsFile.finishWrite(fos);
3365 } catch (Exception e) {
3366 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003367 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
3368 }
3369 }
3370
3371 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
3372 throws IOException {
3373 for (String key : restrictions.keySet()) {
3374 Object value = restrictions.get(key);
3375 serializer.startTag(null, TAG_ENTRY);
3376 serializer.attribute(null, ATTR_KEY, key);
3377
3378 if (value instanceof Boolean) {
3379 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
3380 serializer.text(value.toString());
3381 } else if (value instanceof Integer) {
3382 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
3383 serializer.text(value.toString());
3384 } else if (value == null || value instanceof String) {
3385 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
3386 serializer.text(value != null ? (String) value : "");
3387 } else if (value instanceof Bundle) {
3388 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
3389 writeBundle((Bundle) value, serializer);
3390 } else if (value instanceof Parcelable[]) {
3391 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
3392 Parcelable[] array = (Parcelable[]) value;
3393 for (Parcelable parcelable : array) {
3394 if (!(parcelable instanceof Bundle)) {
3395 throw new IllegalArgumentException("bundle-array can only hold Bundles");
3396 }
3397 serializer.startTag(null, TAG_ENTRY);
3398 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
3399 writeBundle((Bundle) parcelable, serializer);
3400 serializer.endTag(null, TAG_ENTRY);
3401 }
3402 } else {
3403 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
3404 String[] values = (String[]) value;
3405 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
3406 for (String choice : values) {
3407 serializer.startTag(null, TAG_VALUE);
3408 serializer.text(choice != null ? choice : "");
3409 serializer.endTag(null, TAG_VALUE);
3410 }
3411 }
3412 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003413 }
3414 }
3415
3416 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07003417 public int getUserSerialNumber(int userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003418 synchronized (mUsersLock) {
Pavel Grafov9c295d42019-03-26 19:42:08 +00003419 final UserInfo userInfo = getUserInfoLU(userHandle);
3420 return userInfo != null ? userInfo.serialNumber : -1;
Amith Yamasani2a003292012-08-14 18:25:45 -07003421 }
3422 }
3423
3424 @Override
Fyodor Kupolov605b12a2017-05-10 15:58:09 -07003425 public boolean isUserNameSet(int userHandle) {
3426 synchronized (mUsersLock) {
Pavel Grafov9c295d42019-03-26 19:42:08 +00003427 final UserInfo userInfo = getUserInfoLU(userHandle);
Fyodor Kupolov605b12a2017-05-10 15:58:09 -07003428 return userInfo != null && userInfo.name != null;
3429 }
3430 }
3431
3432 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07003433 public int getUserHandle(int userSerialNumber) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003434 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07003435 for (int userId : mUserIds) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003436 UserInfo info = getUserInfoLU(userId);
Kenny Guy945f8832015-02-10 15:17:26 +00003437 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07003438 }
3439 // Not found
3440 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07003441 }
3442 }
3443
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003444 @Override
3445 public long getUserCreationTime(int userHandle) {
3446 int callingUserId = UserHandle.getCallingUserId();
3447 UserInfo userInfo = null;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003448 synchronized (mUsersLock) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003449 if (callingUserId == userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003450 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003451 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003452 UserInfo parent = getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003453 if (parent != null && parent.id == callingUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003454 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003455 }
3456 }
3457 }
3458 if (userInfo == null) {
3459 throw new SecurityException("userHandle can only be the calling user or a managed "
3460 + "profile associated with this user");
3461 }
3462 return userInfo.creationTime;
3463 }
3464
Amith Yamasani0b285492011-04-14 17:35:23 -07003465 /**
3466 * Caches the list of user ids in an array, adjusting the array size when necessary.
3467 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07003468 private void updateUserIds() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003469 int num = 0;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003470 synchronized (mUsersLock) {
3471 final int userSize = mUsers.size();
3472 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003473 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003474 num++;
3475 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003476 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07003477 final int[] newUsers = new int[num];
3478 int n = 0;
3479 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003480 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003481 newUsers[n++] = mUsers.keyAt(i);
3482 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003483 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07003484 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07003485 }
3486 }
3487
3488 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003489 * Called right before a user is started. This gives us a chance to prepare
3490 * app storage and apply any user restrictions.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003491 */
3492 public void onBeforeStartUser(int userId) {
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003493 UserInfo userInfo = getUserInfo(userId);
3494 if (userInfo == null) {
3495 return;
3496 }
Felipe Leme3aad1be2019-05-31 11:43:12 -07003497 TimingsTraceAndSlog t = new TimingsTraceAndSlog();
3498 t.traceBegin("onBeforeStartUser-" + userId);
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003499 final int userSerial = userInfo.serialNumber;
3500 // Migrate only if build fingerprints mismatch
3501 boolean migrateAppsData = !Build.FINGERPRINT.equals(userInfo.lastLoggedInFingerprint);
Felipe Leme3aad1be2019-05-31 11:43:12 -07003502 t.traceBegin("prepareUserData");
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -08003503 mUserDataPreparer.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_DE);
Felipe Leme3aad1be2019-05-31 11:43:12 -07003504 t.traceEnd();
3505 t.traceBegin("reconcileAppsData");
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003506 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_DE, migrateAppsData);
Felipe Leme3aad1be2019-05-31 11:43:12 -07003507 t.traceEnd();
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003508
3509 if (userId != UserHandle.USER_SYSTEM) {
Felipe Leme3aad1be2019-05-31 11:43:12 -07003510 t.traceBegin("applyUserRestrictions");
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003511 synchronized (mRestrictionsLock) {
3512 applyUserRestrictionsLR(userId);
3513 }
Felipe Leme3aad1be2019-05-31 11:43:12 -07003514 t.traceEnd();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003515 }
Felipe Leme3aad1be2019-05-31 11:43:12 -07003516 t.traceEnd(); // onBeforeStartUser
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003517 }
3518
3519 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003520 * Called right before a user is unlocked. This gives us a chance to prepare
3521 * app storage.
3522 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003523 public void onBeforeUnlockUser(@UserIdInt int userId) {
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003524 UserInfo userInfo = getUserInfo(userId);
3525 if (userInfo == null) {
3526 return;
3527 }
3528 final int userSerial = userInfo.serialNumber;
3529 // Migrate only if build fingerprints mismatch
3530 boolean migrateAppsData = !Build.FINGERPRINT.equals(userInfo.lastLoggedInFingerprint);
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -08003531 mUserDataPreparer.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_CE);
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003532 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_CE, migrateAppsData);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003533 }
3534
3535 /**
Fyodor Kupolov50979d12017-01-27 17:36:32 -08003536 * Examine all users present on given mounted volume, and destroy data
3537 * belonging to users that are no longer valid, or whose user ID has been
3538 * recycled.
3539 */
3540 void reconcileUsers(String volumeUuid) {
3541 mUserDataPreparer.reconcileUsers(volumeUuid, getUsers(true /* excludeDying */));
3542 }
3543
3544 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07003545 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasanieb437d42016-04-29 09:31:25 -07003546 * This is called with ActivityManagerService lock held.
Amith Yamasani920ace02012-09-20 22:15:37 -07003547 * @param userId the user that was just foregrounded
3548 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003549 public void onUserLoggedIn(@UserIdInt int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -08003550 UserData userData = getUserDataNoChecks(userId);
3551 if (userData == null || userData.info.partial) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003552 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
3553 return;
3554 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003555
3556 final long now = System.currentTimeMillis();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003557 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani12747872015-12-07 14:19:49 -08003558 userData.info.lastLoggedInTime = now;
Amith Yamasani920ace02012-09-20 22:15:37 -07003559 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003560 userData.info.lastLoggedInFingerprint = Build.FINGERPRINT;
3561 scheduleWriteUser(userData);
Amith Yamasani920ace02012-09-20 22:15:37 -07003562 }
3563
3564 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07003565 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani0b285492011-04-14 17:35:23 -07003566 */
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003567 @VisibleForTesting
3568 int getNextAvailableId() {
3569 int nextId;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003570 synchronized (mUsersLock) {
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003571 nextId = scanNextAvailableIdLocked();
3572 if (nextId >= 0) {
3573 return nextId;
3574 }
3575 // All ids up to MAX_USER_ID were used. Remove all mRemovingUserIds,
3576 // except most recently removed
3577 if (mRemovingUserIds.size() > 0) {
3578 Slog.i(LOG_TAG, "All available IDs are used. Recycling LRU ids.");
3579 mRemovingUserIds.clear();
3580 for (Integer recentlyRemovedId : mRecentlyRemovedIds) {
3581 mRemovingUserIds.put(recentlyRemovedId, true);
Amith Yamasani195263742012-08-21 15:40:12 -07003582 }
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003583 nextId = scanNextAvailableIdLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003584 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003585 }
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003586 if (nextId < 0) {
3587 throw new IllegalStateException("No user id available!");
3588 }
3589 return nextId;
3590 }
3591
Andreas Gampea36dc622018-02-05 17:19:22 -08003592 @GuardedBy("mUsersLock")
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003593 private int scanNextAvailableIdLocked() {
3594 for (int i = MIN_USER_ID; i < MAX_USER_ID; i++) {
3595 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
3596 return i;
3597 }
3598 }
3599 return -1;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003600 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003601
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003602 private static String packageToRestrictionsFileName(String packageName) {
Amith Yamasanifc95e702013-09-26 13:20:17 -07003603 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
3604 }
3605
Amith Yamasani920ace02012-09-20 22:15:37 -07003606 @Override
Amith Yamasani12747872015-12-07 14:19:49 -08003607 public void setSeedAccountData(int userId, String accountName, String accountType,
3608 PersistableBundle accountOptions, boolean persist) {
3609 checkManageUsersPermission("Require MANAGE_USERS permission to set user seed data");
3610 synchronized (mPackagesLock) {
3611 final UserData userData;
3612 synchronized (mUsersLock) {
3613 userData = getUserDataLU(userId);
3614 if (userData == null) {
3615 Slog.e(LOG_TAG, "No such user for settings seed data u=" + userId);
3616 return;
3617 }
3618 userData.seedAccountName = accountName;
3619 userData.seedAccountType = accountType;
3620 userData.seedAccountOptions = accountOptions;
3621 userData.persistSeedData = persist;
3622 }
3623 if (persist) {
3624 writeUserLP(userData);
3625 }
3626 }
3627 }
3628
3629 @Override
3630 public String getSeedAccountName() throws RemoteException {
3631 checkManageUsersPermission("Cannot get seed account information");
3632 synchronized (mUsersLock) {
3633 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3634 return userData.seedAccountName;
3635 }
3636 }
3637
3638 @Override
3639 public String getSeedAccountType() throws RemoteException {
3640 checkManageUsersPermission("Cannot get seed account information");
3641 synchronized (mUsersLock) {
3642 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3643 return userData.seedAccountType;
3644 }
3645 }
3646
3647 @Override
3648 public PersistableBundle getSeedAccountOptions() throws RemoteException {
3649 checkManageUsersPermission("Cannot get seed account information");
3650 synchronized (mUsersLock) {
3651 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3652 return userData.seedAccountOptions;
3653 }
3654 }
3655
3656 @Override
3657 public void clearSeedAccountData() throws RemoteException {
3658 checkManageUsersPermission("Cannot clear seed account information");
3659 synchronized (mPackagesLock) {
3660 UserData userData;
3661 synchronized (mUsersLock) {
3662 userData = getUserDataLU(UserHandle.getCallingUserId());
3663 if (userData == null) return;
3664 userData.clearSeedAccountData();
3665 }
3666 writeUserLP(userData);
3667 }
3668 }
3669
3670 @Override
3671 public boolean someUserHasSeedAccount(String accountName, String accountType)
3672 throws RemoteException {
3673 checkManageUsersPermission("Cannot check seed account information");
3674 synchronized (mUsersLock) {
3675 final int userSize = mUsers.size();
3676 for (int i = 0; i < userSize; i++) {
3677 final UserData data = mUsers.valueAt(i);
3678 if (data.info.isInitialized()) continue;
3679 if (data.seedAccountName == null || !data.seedAccountName.equals(accountName)) {
3680 continue;
3681 }
3682 if (data.seedAccountType == null || !data.seedAccountType.equals(accountType)) {
3683 continue;
3684 }
3685 return true;
3686 }
3687 }
3688 return false;
3689 }
3690
3691 @Override
Todd Kennedy60459ab2015-10-30 11:32:16 -07003692 public void onShellCommand(FileDescriptor in, FileDescriptor out,
Dianne Hackborn354736e2016-08-22 17:00:05 -07003693 FileDescriptor err, String[] args, ShellCallback callback,
3694 ResultReceiver resultReceiver) {
3695 (new Shell()).exec(this, in, out, err, args, callback, resultReceiver);
Todd Kennedy60459ab2015-10-30 11:32:16 -07003696 }
3697
3698 int onShellCommand(Shell shell, String cmd) {
3699 if (cmd == null) {
3700 return shell.handleDefaultCommands(cmd);
3701 }
3702
3703 final PrintWriter pw = shell.getOutPrintWriter();
3704 try {
3705 switch(cmd) {
3706 case "list":
3707 return runList(pw);
Hui Yu8ba65972018-04-16 18:45:48 -07003708 default:
3709 return shell.handleDefaultCommands(cmd);
Todd Kennedy60459ab2015-10-30 11:32:16 -07003710 }
3711 } catch (RemoteException e) {
3712 pw.println("Remote exception: " + e);
3713 }
3714 return -1;
3715 }
3716
3717 private int runList(PrintWriter pw) throws RemoteException {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003718 final IActivityManager am = ActivityManager.getService();
Todd Kennedy60459ab2015-10-30 11:32:16 -07003719 final List<UserInfo> users = getUsers(false);
3720 if (users == null) {
3721 pw.println("Error: couldn't get users");
3722 return 1;
3723 } else {
3724 pw.println("Users:");
3725 for (int i = 0; i < users.size(); i++) {
Jeff Sharkeye17ac152015-11-06 22:40:29 -08003726 String running = am.isUserRunning(users.get(i).id, 0) ? " running" : "";
Todd Kennedy60459ab2015-10-30 11:32:16 -07003727 pw.println("\t" + users.get(i).toString() + running);
3728 }
3729 return 0;
3730 }
3731 }
3732
3733 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -07003734 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06003735 if (!DumpUtils.checkDumpPermission(mContext, LOG_TAG, pw)) return;
Amith Yamasani920ace02012-09-20 22:15:37 -07003736
3737 long now = System.currentTimeMillis();
Makoto Onuki73dded22017-12-20 13:14:48 +09003738 final long nowRealtime = SystemClock.elapsedRealtime();
Felipe Lemed7b88382019-06-12 17:40:53 -07003739
3740 final int currentUser = LocalServices.getService(ActivityManagerInternal.class)
3741 .getCurrentUserId();
3742 pw.print("Current user: "); pw.println(currentUser);
3743
Amith Yamasani920ace02012-09-20 22:15:37 -07003744 StringBuilder sb = new StringBuilder();
3745 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003746 synchronized (mUsersLock) {
3747 pw.println("Users:");
3748 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003749 UserData userData = mUsers.valueAt(i);
3750 if (userData == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003751 continue;
3752 }
Amith Yamasani12747872015-12-07 14:19:49 -08003753 UserInfo userInfo = userData.info;
3754 final int userId = userInfo.id;
3755 pw.print(" "); pw.print(userInfo);
3756 pw.print(" serialNo="); pw.print(userInfo.serialNumber);
Felipe Lemed7b88382019-06-12 17:40:53 -07003757 pw.print(" isPrimary="); pw.print(userInfo.isPrimary());
Makoto Onukie7927da2015-11-25 10:05:17 -08003758 if (mRemovingUserIds.get(userId)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003759 pw.print(" <removing> ");
3760 }
Amith Yamasani12747872015-12-07 14:19:49 -08003761 if (userInfo.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003762 pw.print(" <partial>");
3763 }
3764 pw.println();
Makoto Onuki88aef752017-03-29 16:52:03 -07003765 pw.print(" State: ");
3766 final int state;
3767 synchronized (mUserStates) {
3768 state = mUserStates.get(userId, -1);
3769 }
3770 pw.println(UserState.stateToString(state));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003771 pw.print(" Created: ");
Makoto Onuki73dded22017-12-20 13:14:48 +09003772 dumpTimeAgo(pw, sb, now, userInfo.creationTime);
3773
Fyodor Kupolov82402752015-10-28 14:54:51 -07003774 pw.print(" Last logged in: ");
Makoto Onuki73dded22017-12-20 13:14:48 +09003775 dumpTimeAgo(pw, sb, now, userInfo.lastLoggedInTime);
3776
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003777 pw.print(" Last logged in fingerprint: ");
3778 pw.println(userInfo.lastLoggedInFingerprint);
Makoto Onuki73dded22017-12-20 13:14:48 +09003779
3780 pw.print(" Start time: ");
3781 dumpTimeAgo(pw, sb, nowRealtime, userData.startRealtime);
3782
3783 pw.print(" Unlock time: ");
3784 dumpTimeAgo(pw, sb, nowRealtime, userData.unlockRealtime);
3785
Makoto Onukie7927da2015-11-25 10:05:17 -08003786 pw.print(" Has profile owner: ");
3787 pw.println(mIsUserManaged.get(userId));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003788 pw.println(" Restrictions:");
3789 synchronized (mRestrictionsLock) {
3790 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003791 pw, " ", mBaseUserRestrictions.get(userInfo.id));
Pavel Grafov6a40f092016-10-25 15:46:51 +01003792 pw.println(" Device policy global restrictions:");
3793 UserRestrictionsUtils.dumpRestrictions(
3794 pw, " ", mDevicePolicyGlobalUserRestrictions.get(userInfo.id));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003795 pw.println(" Device policy local restrictions:");
3796 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003797 pw, " ", mDevicePolicyLocalUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003798 pw.println(" Effective restrictions:");
3799 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003800 pw, " ", mCachedEffectiveUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003801 }
Amith Yamasani12747872015-12-07 14:19:49 -08003802
3803 if (userData.account != null) {
3804 pw.print(" Account name: " + userData.account);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08003805 pw.println();
3806 }
Amith Yamasani12747872015-12-07 14:19:49 -08003807
3808 if (userData.seedAccountName != null) {
3809 pw.print(" Seed account name: " + userData.seedAccountName);
3810 pw.println();
3811 if (userData.seedAccountType != null) {
3812 pw.print(" account type: " + userData.seedAccountType);
3813 pw.println();
3814 }
3815 if (userData.seedAccountOptions != null) {
3816 pw.print(" account options exist");
3817 pw.println();
3818 }
3819 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003820 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003821 }
Amith Yamasani12747872015-12-07 14:19:49 -08003822 pw.println();
Pavel Grafov6a40f092016-10-25 15:46:51 +01003823 pw.println(" Device owner id:" + mDeviceOwnerUserId);
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01003824 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003825 pw.println(" Guest restrictions:");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003826 synchronized (mGuestRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003827 UserRestrictionsUtils.dumpRestrictions(pw, " ", mGuestRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003828 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003829 synchronized (mUsersLock) {
3830 pw.println();
3831 pw.println(" Device managed: " + mIsDeviceManaged);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003832 if (mRemovingUserIds.size() > 0) {
3833 pw.println();
3834 pw.println(" Recently removed userIds: " + mRecentlyRemovedIds);
3835 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003836 }
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003837 synchronized (mUserStates) {
3838 pw.println(" Started users state: " + mUserStates);
3839 }
Felipe Lemed7b88382019-06-12 17:40:53 -07003840 } // synchronized (mPackagesLock)
3841
3842 // Dump some capabilities
3843 pw.println();
3844 pw.println(" Max users: " + UserManager.getMaxSupportedUsers());
3845 pw.println(" Supports switchable users: " + UserManager.supportsMultipleUsers());
3846 pw.println(" All guests ephemeral: " + Resources.getSystem().getBoolean(
3847 com.android.internal.R.bool.config_guestUserEphemeral));
3848 pw.println(" Is split-system user: " + UserManager.isSplitSystemUser());
Amith Yamasani920ace02012-09-20 22:15:37 -07003849 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08003850
Makoto Onuki73dded22017-12-20 13:14:48 +09003851 private static void dumpTimeAgo(PrintWriter pw, StringBuilder sb, long nowTime, long time) {
3852 if (time == 0) {
3853 pw.println("<unknown>");
3854 } else {
3855 sb.setLength(0);
3856 TimeUtils.formatDuration(nowTime - time, sb);
3857 sb.append(" ago");
3858 pw.println(sb);
3859 }
3860 }
3861
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08003862 final class MainHandler extends Handler {
3863
3864 @Override
3865 public void handleMessage(Message msg) {
3866 switch (msg.what) {
3867 case WRITE_USER_MSG:
3868 removeMessages(WRITE_USER_MSG, msg.obj);
3869 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08003870 int userId = ((UserData) msg.obj).info.id;
3871 UserData userData = getUserDataNoChecks(userId);
3872 if (userData != null) {
3873 writeUserLP(userData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08003874 }
3875 }
3876 }
3877 }
3878 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07003879
3880 /**
3881 * @param userId
3882 * @return whether the user has been initialized yet
3883 */
Todd Kennedy0eb97382017-10-03 16:57:22 -07003884 boolean isUserInitialized(int userId) {
3885 return mLocalService.isUserInitialized(userId);
Amith Yamasanibb054c92015-07-09 14:16:27 -07003886 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003887
3888 private class LocalService extends UserManagerInternal {
Makoto Onuki068c54a2015-10-13 14:34:03 -07003889 @Override
Pavel Grafov6a40f092016-10-25 15:46:51 +01003890 public void setDevicePolicyUserRestrictions(int userId, @Nullable Bundle restrictions,
3891 boolean isDeviceOwner, int cameraRestrictionScope) {
3892 UserManagerService.this.setDevicePolicyUserRestrictionsInner(userId, restrictions,
3893 isDeviceOwner, cameraRestrictionScope);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003894 }
3895
3896 @Override
3897 public Bundle getBaseUserRestrictions(int userId) {
3898 synchronized (mRestrictionsLock) {
3899 return mBaseUserRestrictions.get(userId);
3900 }
3901 }
3902
3903 @Override
3904 public void setBaseUserRestrictionsByDpmsForMigration(
3905 int userId, Bundle baseRestrictions) {
3906 synchronized (mRestrictionsLock) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01003907 if (updateRestrictionsIfNeededLR(
3908 userId, new Bundle(baseRestrictions), mBaseUserRestrictions)) {
3909 invalidateEffectiveUserRestrictionsLR(userId);
3910 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003911 }
3912
Amith Yamasani12747872015-12-07 14:19:49 -08003913 final UserData userData = getUserDataNoChecks(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003914 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08003915 if (userData != null) {
3916 writeUserLP(userData);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003917 } else {
3918 Slog.w(LOG_TAG, "UserInfo not found for " + userId);
3919 }
3920 }
3921 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08003922
3923 @Override
3924 public boolean getUserRestriction(int userId, String key) {
3925 return getUserRestrictions(userId).getBoolean(key);
3926 }
3927
3928 @Override
3929 public void addUserRestrictionsListener(UserRestrictionsListener listener) {
3930 synchronized (mUserRestrictionsListeners) {
3931 mUserRestrictionsListeners.add(listener);
3932 }
3933 }
3934
3935 @Override
3936 public void removeUserRestrictionsListener(UserRestrictionsListener listener) {
3937 synchronized (mUserRestrictionsListeners) {
3938 mUserRestrictionsListeners.remove(listener);
3939 }
3940 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003941
3942 @Override
3943 public void setDeviceManaged(boolean isManaged) {
3944 synchronized (mUsersLock) {
3945 mIsDeviceManaged = isManaged;
3946 }
3947 }
3948
3949 @Override
3950 public void setUserManaged(int userId, boolean isManaged) {
3951 synchronized (mUsersLock) {
3952 mIsUserManaged.put(userId, isManaged);
3953 }
3954 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01003955
3956 @Override
3957 public void setUserIcon(int userId, Bitmap bitmap) {
3958 long ident = Binder.clearCallingIdentity();
3959 try {
3960 synchronized (mPackagesLock) {
3961 UserData userData = getUserDataNoChecks(userId);
3962 if (userData == null || userData.info.partial) {
3963 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
3964 return;
3965 }
3966 writeBitmapLP(userData.info, bitmap);
3967 writeUserLP(userData);
3968 }
3969 sendUserInfoChangedBroadcast(userId);
3970 } finally {
3971 Binder.restoreCallingIdentity(ident);
3972 }
3973 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01003974
3975 @Override
3976 public void setForceEphemeralUsers(boolean forceEphemeralUsers) {
3977 synchronized (mUsersLock) {
3978 mForceEphemeralUsers = forceEphemeralUsers;
3979 }
3980 }
3981
3982 @Override
3983 public void removeAllUsers() {
3984 if (UserHandle.USER_SYSTEM == ActivityManager.getCurrentUser()) {
3985 // Remove the non-system users straight away.
3986 removeNonSystemUsers();
3987 } else {
3988 // Switch to the system user first and then remove the other users.
3989 BroadcastReceiver userSwitchedReceiver = new BroadcastReceiver() {
3990 @Override
3991 public void onReceive(Context context, Intent intent) {
3992 int userId =
3993 intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3994 if (userId != UserHandle.USER_SYSTEM) {
3995 return;
3996 }
3997 mContext.unregisterReceiver(this);
3998 removeNonSystemUsers();
3999 }
4000 };
4001 IntentFilter userSwitchedFilter = new IntentFilter();
4002 userSwitchedFilter.addAction(Intent.ACTION_USER_SWITCHED);
4003 mContext.registerReceiver(
4004 userSwitchedReceiver, userSwitchedFilter, null, mHandler);
4005
4006 // Switch to the system user.
4007 ActivityManager am =
4008 (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
4009 am.switchUser(UserHandle.USER_SYSTEM);
4010 }
4011 }
phweisse9c44062016-02-10 12:57:38 +01004012
4013 @Override
Lenka Trochtova1ddda472016-02-12 10:42:12 +01004014 public void onEphemeralUserStop(int userId) {
4015 synchronized (mUsersLock) {
4016 UserInfo userInfo = getUserInfoLU(userId);
4017 if (userInfo != null && userInfo.isEphemeral()) {
4018 // Do not allow switching back to the ephemeral user again as the user is going
4019 // to be deleted.
4020 userInfo.flags |= UserInfo.FLAG_DISABLED;
4021 if (userInfo.isGuest()) {
4022 // Indicate that the guest will be deleted after it stops.
4023 userInfo.guestToRemove = true;
4024 }
4025 }
4026 }
4027 }
4028
4029 @Override
Alex Chaub6a9f942017-11-07 11:28:56 +08004030 public UserInfo createUserEvenWhenDisallowed(String name, int flags,
4031 String[] disallowedPackages) {
4032 UserInfo user = createUserInternalUnchecked(name, flags, UserHandle.USER_NULL,
4033 disallowedPackages);
phweisse9c44062016-02-10 12:57:38 +01004034 // Keep this in sync with UserManager.createUser
Christine Franks97a54802017-08-09 10:06:43 -07004035 if (user != null && !user.isAdmin() && !user.isDemo()) {
phweisse9c44062016-02-10 12:57:38 +01004036 setUserRestriction(UserManager.DISALLOW_SMS, true, user.id);
4037 setUserRestriction(UserManager.DISALLOW_OUTGOING_CALLS, true, user.id);
4038 }
4039 return user;
4040 }
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07004041
4042 @Override
Nicolas Prevotdf1b87d2016-10-25 13:57:08 +01004043 public boolean removeUserEvenWhenDisallowed(int userId) {
4044 return removeUserUnchecked(userId);
4045 }
4046
4047 @Override
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00004048 public boolean isUserRunning(int userId) {
4049 synchronized (mUserStates) {
4050 return mUserStates.get(userId, -1) >= 0;
4051 }
4052 }
4053
4054 @Override
4055 public void setUserState(int userId, int userState) {
4056 synchronized (mUserStates) {
4057 mUserStates.put(userId, userState);
4058 }
4059 }
4060
4061 @Override
4062 public void removeUserState(int userId) {
4063 synchronized (mUserStates) {
4064 mUserStates.delete(userId);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07004065 }
4066 }
4067
4068 @Override
Michael Wachenschwanz3f2b6552017-05-15 13:53:09 -07004069 public int[] getUserIds() {
4070 return UserManagerService.this.getUserIds();
4071 }
4072
4073 @Override
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07004074 public boolean isUserUnlockingOrUnlocked(int userId) {
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07004075 int state;
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00004076 synchronized (mUserStates) {
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07004077 state = mUserStates.get(userId, -1);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07004078 }
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07004079 // Special case, in the stopping/shutdown state user key can still be unlocked
4080 if (state == UserState.STATE_STOPPING || state == UserState.STATE_SHUTDOWN) {
4081 return StorageManager.isUserKeyUnlocked(userId);
4082 }
4083 return (state == UserState.STATE_RUNNING_UNLOCKING)
4084 || (state == UserState.STATE_RUNNING_UNLOCKED);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07004085 }
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08004086
4087 @Override
4088 public boolean isUserUnlocked(int userId) {
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07004089 int state;
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08004090 synchronized (mUserStates) {
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07004091 state = mUserStates.get(userId, -1);
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08004092 }
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07004093 // Special case, in the stopping/shutdown state user key can still be unlocked
4094 if (state == UserState.STATE_STOPPING || state == UserState.STATE_SHUTDOWN) {
4095 return StorageManager.isUserKeyUnlocked(userId);
4096 }
4097 return state == UserState.STATE_RUNNING_UNLOCKED;
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08004098 }
Todd Kennedy0eb97382017-10-03 16:57:22 -07004099
4100 @Override
4101 public boolean isUserInitialized(int userId) {
4102 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
4103 }
4104
4105 @Override
4106 public boolean exists(int userId) {
4107 return getUserInfoNoChecks(userId) != null;
4108 }
Sunny Goyal145c8f82018-02-15 14:27:09 -08004109
4110 @Override
4111 public boolean isProfileAccessible(int callingUserId, int targetUserId, String debugMsg,
4112 boolean throwSecurityException) {
4113 if (targetUserId == callingUserId) {
4114 return true;
4115 }
4116 synchronized (mUsersLock) {
4117 UserInfo callingUserInfo = getUserInfoLU(callingUserId);
4118 if (callingUserInfo == null || callingUserInfo.isManagedProfile()) {
4119 if (throwSecurityException) {
4120 throw new SecurityException(
4121 debugMsg + " for another profile "
4122 + targetUserId + " from " + callingUserId);
4123 }
4124 }
4125
4126 UserInfo targetUserInfo = getUserInfoLU(targetUserId);
4127 if (targetUserInfo == null || !targetUserInfo.isEnabled()) {
4128 // Do not throw any exception here as this could happen due to race conditions
4129 // between the system updating its state and the client getting notified.
4130 if (throwSecurityException) {
4131 Slog.w(LOG_TAG, debugMsg + " for disabled profile "
4132 + targetUserId + " from " + callingUserId);
4133 }
4134 return false;
4135 }
4136
4137 if (targetUserInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID ||
4138 targetUserInfo.profileGroupId != callingUserInfo.profileGroupId) {
4139 if (throwSecurityException) {
4140 throw new SecurityException(
4141 debugMsg + " for unrelated profile " + targetUserId);
4142 }
4143 return false;
4144 }
4145 }
4146 return true;
4147 }
4148
4149 @Override
4150 public int getProfileParentId(int userId) {
4151 synchronized (mUsersLock) {
4152 UserInfo profileParent = getProfileParentLU(userId);
4153 if (profileParent == null) {
4154 return userId;
4155 }
4156 return profileParent.id;
4157 }
4158 }
yuemingw1d13eae2018-01-30 17:27:54 +00004159
4160 @Override
4161 public boolean isSettingRestrictedForUser(String setting, @UserIdInt int userId,
4162 String value, int callingUid) {
4163 return UserRestrictionsUtils.isSettingRestrictedForUser(mContext, setting, userId,
4164 value, callingUid);
4165 }
Patrick Baumann2f2fd712019-07-31 15:18:53 -07004166
4167 @Override
4168 public boolean hasUserRestriction(String restrictionKey, int userId) {
4169 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
4170 return false;
4171 }
4172 Bundle restrictions = getEffectiveUserRestrictions(userId);
4173 return restrictions != null && restrictions.getBoolean(restrictionKey);
4174 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01004175 }
4176
4177 /* Remove all the users except of the system one. */
4178 private void removeNonSystemUsers() {
4179 ArrayList<UserInfo> usersToRemove = new ArrayList<>();
4180 synchronized (mUsersLock) {
4181 final int userSize = mUsers.size();
4182 for (int i = 0; i < userSize; i++) {
4183 UserInfo ui = mUsers.valueAt(i).info;
4184 if (ui.id != UserHandle.USER_SYSTEM) {
4185 usersToRemove.add(ui);
4186 }
4187 }
4188 }
4189 for (UserInfo ui: usersToRemove) {
4190 removeUser(ui.id);
4191 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07004192 }
Todd Kennedy60459ab2015-10-30 11:32:16 -07004193
4194 private class Shell extends ShellCommand {
4195 @Override
4196 public int onCommand(String cmd) {
4197 return onShellCommand(this, cmd);
4198 }
4199
4200 @Override
4201 public void onHelp() {
4202 final PrintWriter pw = getOutPrintWriter();
4203 pw.println("User manager (user) commands:");
4204 pw.println(" help");
4205 pw.println(" Print this help text.");
4206 pw.println("");
4207 pw.println(" list");
4208 pw.println(" Prints all users on the system.");
4209 }
4210 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08004211
4212 private static void debug(String message) {
4213 Log.d(LOG_TAG, message +
4214 (DBG_WITH_STACKTRACE ? " called at\n" + Debug.getCallers(10, " ") : ""));
4215 }
Kenny Guy02c89902016-11-15 19:36:38 +00004216
4217 @VisibleForTesting
4218 static int getMaxManagedProfiles() {
4219 // Allow overriding max managed profiles on debuggable builds for testing
4220 // of multiple profiles.
4221 if (!Build.IS_DEBUGGABLE) {
4222 return MAX_MANAGED_PROFILES;
4223 } else {
4224 return SystemProperties.getInt("persist.sys.max_profiles",
4225 MAX_MANAGED_PROFILES);
4226 }
4227 }
4228
Andreas Gampe2e8c7672018-07-20 13:01:08 -07004229 @GuardedBy("mUsersLock")
Kenny Guy02c89902016-11-15 19:36:38 +00004230 @VisibleForTesting
4231 int getFreeProfileBadgeLU(int parentUserId) {
4232 int maxManagedProfiles = getMaxManagedProfiles();
4233 boolean[] usedBadges = new boolean[maxManagedProfiles];
4234 final int userSize = mUsers.size();
4235 for (int i = 0; i < userSize; i++) {
4236 UserInfo ui = mUsers.valueAt(i).info;
4237 // Check which badge indexes are already used by this profile group.
4238 if (ui.isManagedProfile()
4239 && ui.profileGroupId == parentUserId
4240 && !mRemovingUserIds.get(ui.id)
4241 && ui.profileBadge < maxManagedProfiles) {
4242 usedBadges[ui.profileBadge] = true;
4243 }
4244 }
4245 for (int i = 0; i < maxManagedProfiles; i++) {
4246 if (!usedBadges[i]) {
4247 return i;
4248 }
4249 }
4250 return 0;
4251 }
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07004252
4253 /**
4254 * Checks if the given user has a managed profile associated with it.
4255 * @param userId The parent user
4256 * @return
4257 */
4258 boolean hasManagedProfile(int userId) {
4259 synchronized (mUsersLock) {
4260 UserInfo userInfo = getUserInfoLU(userId);
4261 final int userSize = mUsers.size();
4262 for (int i = 0; i < userSize; i++) {
4263 UserInfo profile = mUsers.valueAt(i).info;
4264 if (userId != profile.id && isProfileOf(userInfo, profile)) {
4265 return true;
4266 }
4267 }
4268 return false;
4269 }
4270 }
Tony Makd390ae92017-12-28 13:23:10 +00004271
4272 /**
4273 * Check if the calling package name matches with the calling UID, throw
4274 * {@link SecurityException} if not.
4275 */
4276 private void verifyCallingPackage(String callingPackage, int callingUid) {
4277 int packageUid = mPm.getPackageUid(callingPackage, 0, UserHandle.getUserId(callingUid));
4278 if (packageUid != callingUid) {
4279 throw new SecurityException("Specified package " + callingPackage
4280 + " does not match the calling uid " + callingUid);
4281 }
4282 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07004283}