blob: 22eb1b497cf421f026aaef37d5c4ae2bb8c57410 [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;
Felipe Lemec1ca4412019-09-11 09:23:26 -070044import android.content.pm.UserInfo.UserInfoFlag;
Lenka Trochtova02fee152015-12-22 14:26:18 +010045import android.content.res.Resources;
Amith Yamasanie928d7d2012-09-17 21:46:51 -070046import android.graphics.Bitmap;
Amith Yamasani258848d2012-08-10 17:06:33 -070047import android.os.Binder;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -060048import android.os.Build;
Amith Yamasanie4cf7342012-12-17 11:12:09 -080049import android.os.Bundle;
Makoto Onuki1a2cd742015-11-16 13:51:27 -080050import android.os.Debug;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070051import android.os.Environment;
52import android.os.FileUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080053import android.os.Handler;
Svet Ganov9cea80cd2016-02-16 11:47:00 -080054import android.os.IBinder;
Tony Mak64fd8c02017-12-01 19:11:59 +000055import android.os.IProgressListener;
Amith Yamasani258848d2012-08-10 17:06:33 -070056import android.os.IUserManager;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -080057import android.os.Message;
Adrian Roos1bdff912015-02-17 15:51:35 +010058import android.os.ParcelFileDescriptor;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070059import android.os.Parcelable;
Amith Yamasani12747872015-12-07 14:19:49 -080060import android.os.PersistableBundle;
Amith Yamasani258848d2012-08-10 17:06:33 -070061import android.os.Process;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070062import android.os.RemoteException;
Todd Kennedy60459ab2015-10-30 11:32:16 -070063import android.os.ResultReceiver;
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +010064import android.os.SELinux;
Jason Monk62062992014-05-06 09:55:28 -040065import android.os.ServiceManager;
Dianne Hackborn354736e2016-08-22 17:00:05 -070066import android.os.ShellCallback;
Todd Kennedy60459ab2015-10-30 11:32:16 -070067import android.os.ShellCommand;
Makoto Onuki73dded22017-12-20 13:14:48 +090068import android.os.SystemClock;
Kenny Guy02c89902016-11-15 19:36:38 +000069import android.os.SystemProperties;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070070import android.os.UserHandle;
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070071import android.os.UserManager;
Pavel Grafov6a40f092016-10-25 15:46:51 +010072import android.os.UserManager.EnforcingUser;
Makoto Onuki068c54a2015-10-13 14:34:03 -070073import android.os.UserManagerInternal;
Makoto Onukid45a4a22015-11-02 17:17:38 -080074import android.os.UserManagerInternal.UserRestrictionsListener;
Paul Crowley85e4e812015-05-19 12:42:00 +010075import android.os.storage.StorageManager;
Amith Yamasanid04aaa32016-06-13 12:09:36 -070076import android.security.GateKeeper;
77import android.service.gatekeeper.IGateKeeperService;
arangelov9b632d72018-12-07 23:21:22 +000078import android.stats.devicepolicy.DevicePolicyEnums;
Bookatz75f0a072019-08-05 14:12:16 -070079import android.util.ArraySet;
Amith Yamasani2a003292012-08-14 18:25:45 -070080import android.util.AtomicFile;
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -070081import android.util.IntArray;
Amith Yamasani655d0e22013-06-12 14:19:10 -070082import android.util.Log;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070083import android.util.Slog;
84import android.util.SparseArray;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080085import android.util.SparseBooleanArray;
Amith Yamasaniea1b9d72016-05-27 15:57:38 +000086import android.util.SparseIntArray;
Amith Yamasani920ace02012-09-20 22:15:37 -070087import android.util.TimeUtils;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070088import android.util.Xml;
89
Makoto Onuki068c54a2015-10-13 14:34:03 -070090import com.android.internal.annotations.GuardedBy;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070091import com.android.internal.annotations.VisibleForTesting;
Jason Monk62062992014-05-06 09:55:28 -040092import com.android.internal.app.IAppOpsService;
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -080093import com.android.internal.logging.MetricsLogger;
Fyodor Kupolova68a2862018-01-30 18:22:00 -080094import com.android.internal.os.BackgroundThread;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -060095import com.android.internal.util.DumpUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080096import com.android.internal.util.FastXmlSerializer;
Makoto Onuki068c54a2015-10-13 14:34:03 -070097import com.android.internal.util.Preconditions;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070098import com.android.internal.util.XmlUtils;
Clara Bayarri10ad84a2015-12-01 17:38:05 +000099import com.android.internal.widget.LockPatternUtils;
Amith Yamasani515d4062015-09-28 11:30:06 -0700100import com.android.server.LocalServices;
Jeff Sharkey5f3e9342017-03-13 14:53:11 -0600101import com.android.server.LockGuard;
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700102import com.android.server.SystemService;
Amith Yamasaniea1b9d72016-05-27 15:57:38 +0000103import com.android.server.am.UserState;
Suprabh Shuklac5e057c2016-08-08 16:22:44 -0700104import com.android.server.storage.DeviceStorageMonitorInternal;
Felipe Leme3aad1be2019-05-31 11:43:12 -0700105import com.android.server.utils.TimingsTraceAndSlog;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700106import com.android.server.wm.ActivityTaskManagerInternal;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800107
arangelov9b632d72018-12-07 23:21:22 +0000108import libcore.io.IoUtils;
109
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800110import org.xmlpull.v1.XmlPullParser;
111import org.xmlpull.v1.XmlPullParserException;
112import org.xmlpull.v1.XmlSerializer;
113
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700114import java.io.BufferedOutputStream;
115import java.io.File;
Amith Yamasani920ace02012-09-20 22:15:37 -0700116import java.io.FileDescriptor;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700117import java.io.FileInputStream;
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700118import java.io.FileNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700119import java.io.FileOutputStream;
Tony Mak64fd8c02017-12-01 19:11:59 +0000120import java.io.IOException;
Kenny Guy02c89902016-11-15 19:36:38 +0000121import java.io.InputStream;
122import java.io.OutputStream;
Amith Yamasani920ace02012-09-20 22:15:37 -0700123import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100124import java.nio.charset.StandardCharsets;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700125import java.util.ArrayList;
Pavel Grafov6a40f092016-10-25 15:46:51 +0100126import java.util.Collections;
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700127import java.util.LinkedList;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700128import java.util.List;
Narayan Kamath607223f2018-02-19 14:09:02 +0000129import java.util.Objects;
Bookatz75f0a072019-08-05 14:12:16 -0700130import java.util.Set;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700131
Makoto Onuki068c54a2015-10-13 14:34:03 -0700132/**
133 * Service for {@link UserManager}.
134 *
135 * Method naming convention:
Fyodor Kupolov82402752015-10-28 14:54:51 -0700136 * <ul>
Fyodor Kupolovd31cee92017-09-05 16:31:08 -0700137 * <li> Methods suffixed with "LAr" should be called within the {@link #mAppRestrictionsLock} lock.
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800138 * <li> Methods suffixed with "LP" should be called within the {@link #mPackagesLock} lock.
Fyodor Kupolov82402752015-10-28 14:54:51 -0700139 * <li> Methods suffixed with "LR" should be called within the {@link #mRestrictionsLock} lock.
140 * <li> Methods suffixed with "LU" should be called within the {@link #mUsersLock} lock.
141 * </ul>
Makoto Onuki068c54a2015-10-13 14:34:03 -0700142 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700143public class UserManagerService extends IUserManager.Stub {
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700144
Amith Yamasani2a003292012-08-14 18:25:45 -0700145 private static final String LOG_TAG = "UserManagerService";
Makoto Onuki81c61ea2016-01-22 11:22:26 -0800146 static final boolean DBG = false; // DO NOT SUBMIT WITH TRUE
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800147 private static final boolean DBG_WITH_STACKTRACE = false; // DO NOT SUBMIT WITH TRUE
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700148 // Can be used for manual testing of id recycling
149 private static final boolean RELEASE_DELETED_USER_ID = false; // DO NOT SUBMIT WITH TRUE
Amith Yamasani16389312012-10-17 21:20:14 -0700150
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700151 private static final String TAG_NAME = "name";
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800152 private static final String TAG_ACCOUNT = "account";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700153 private static final String ATTR_FLAGS = "flags";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700154 private static final String ATTR_ICON_PATH = "icon";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700155 private static final String ATTR_ID = "id";
Amith Yamasani920ace02012-09-20 22:15:37 -0700156 private static final String ATTR_CREATION_TIME = "created";
157 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -0600158 private static final String ATTR_LAST_LOGGED_IN_FINGERPRINT = "lastLoggedInFingerprint";
Amith Yamasani2a003292012-08-14 18:25:45 -0700159 private static final String ATTR_SERIAL_NO = "serialNumber";
160 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700161 private static final String ATTR_PARTIAL = "partial";
Felipe Lemec1ca4412019-09-11 09:23:26 -0700162 private static final String ATTR_PRE_CREATED = "preCreated";
Adam Lesinskieddeb492014-09-08 17:50:03 -0700163 private static final String ATTR_GUEST_TO_REMOVE = "guestToRemove";
Amith Yamasani6f34b412012-10-22 18:19:27 -0700164 private static final String ATTR_USER_VERSION = "version";
Kenny Guy2a764942014-04-02 13:29:20 +0100165 private static final String ATTR_PROFILE_GROUP_ID = "profileGroupId";
Kenny Guy02c89902016-11-15 19:36:38 +0000166 private static final String ATTR_PROFILE_BADGE = "profileBadge";
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700167 private static final String ATTR_RESTRICTED_PROFILE_PARENT_ID = "restrictedProfileParentId";
Amith Yamasani12747872015-12-07 14:19:49 -0800168 private static final String ATTR_SEED_ACCOUNT_NAME = "seedAccountName";
169 private static final String ATTR_SEED_ACCOUNT_TYPE = "seedAccountType";
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530170 private static final String TAG_GUEST_RESTRICTIONS = "guestRestrictions";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700171 private static final String TAG_USERS = "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700172 private static final String TAG_USER = "user";
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800173 private static final String TAG_RESTRICTIONS = "restrictions";
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800174 private static final String TAG_DEVICE_POLICY_RESTRICTIONS = "device_policy_restrictions";
Pavel Grafov6a40f092016-10-25 15:46:51 +0100175 private static final String TAG_DEVICE_POLICY_GLOBAL_RESTRICTIONS =
176 "device_policy_global_restrictions";
177 /** Legacy name for device owner id tag. */
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +0100178 private static final String TAG_GLOBAL_RESTRICTION_OWNER_ID = "globalRestrictionOwnerUserId";
Pavel Grafov6a40f092016-10-25 15:46:51 +0100179 private static final String TAG_DEVICE_OWNER_USER_ID = "deviceOwnerUserId";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800180 private static final String TAG_ENTRY = "entry";
181 private static final String TAG_VALUE = "value";
Amith Yamasani12747872015-12-07 14:19:49 -0800182 private static final String TAG_SEED_ACCOUNT_OPTIONS = "seedAccountOptions";
arangelov9b632d72018-12-07 23:21:22 +0000183 private static final String TAG_LAST_REQUEST_QUIET_MODE_ENABLED_CALL =
184 "lastRequestQuietModeEnabledCall";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800185 private static final String ATTR_KEY = "key";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700186 private static final String ATTR_VALUE_TYPE = "type";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800187 private static final String ATTR_MULTIPLE = "m";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700188
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700189 private static final String ATTR_TYPE_STRING_ARRAY = "sa";
190 private static final String ATTR_TYPE_STRING = "s";
191 private static final String ATTR_TYPE_BOOLEAN = "b";
Amith Yamasani5b5aa402014-06-01 20:10:14 -0700192 private static final String ATTR_TYPE_INTEGER = "i";
Fyodor Kupolov262f9952015-03-23 18:55:11 -0700193 private static final String ATTR_TYPE_BUNDLE = "B";
194 private static final String ATTR_TYPE_BUNDLE_ARRAY = "BA";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700195
Amith Yamasani0b285492011-04-14 17:35:23 -0700196 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700197 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700198 private static final String USER_PHOTO_FILENAME = "photo.png";
Adrian Roos1bdff912015-02-17 15:51:35 +0100199 private static final String USER_PHOTO_FILENAME_TMP = USER_PHOTO_FILENAME + ".tmp";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700200
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800201 private static final String RESTRICTIONS_FILE_PREFIX = "res_";
Amith Yamasanifc95e702013-09-26 13:20:17 -0700202 private static final String XML_SUFFIX = ".xml";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800203
Sudheer Shankaf5cea032016-06-08 17:13:24 -0700204 private static final int ALLOWED_FLAGS_FOR_CREATE_USERS_PERMISSION =
205 UserInfo.FLAG_MANAGED_PROFILE
206 | UserInfo.FLAG_EPHEMERAL
207 | UserInfo.FLAG_RESTRICTED
Sudheer Shanka234d1af2016-08-26 15:42:53 -0700208 | UserInfo.FLAG_GUEST
209 | UserInfo.FLAG_DEMO;
Sudheer Shankaf5cea032016-06-08 17:13:24 -0700210
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700211 @VisibleForTesting
Makoto Onukiacf38582019-10-04 11:53:42 -0700212 static final int MIN_USER_ID = UserHandle.MIN_SECONDARY_USER_ID;
213
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700214 // We need to keep process uid within Integer.MAX_VALUE.
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700215 @VisibleForTesting
216 static final int MAX_USER_ID = Integer.MAX_VALUE / UserHandle.PER_USER_RANGE;
217
218 // Max size of the queue of recently removed users
219 @VisibleForTesting
220 static final int MAX_RECENTLY_REMOVED_IDS_SIZE = 100;
Amith Yamasani634cf312012-10-04 17:34:21 -0700221
Bookatz75f0a072019-08-05 14:12:16 -0700222 private static final int USER_VERSION = 8;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700223
Amith Yamasani920ace02012-09-20 22:15:37 -0700224 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
225
Nicolas Prevotb8186812015-08-06 15:00:03 +0100226 // Maximum number of managed profiles permitted per user is 1. This cannot be increased
Amith Yamasani95ab7842014-08-11 17:09:26 -0700227 // without first making sure that the rest of the framework is prepared for it.
Kenny Guy02c89902016-11-15 19:36:38 +0000228 @VisibleForTesting
229 static final int MAX_MANAGED_PROFILES = 1;
Amith Yamasani95ab7842014-08-11 17:09:26 -0700230
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800231 static final int WRITE_USER_MSG = 1;
232 static final int WRITE_USER_DELAY = 2*1000; // 2 seconds
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530233
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -0800234 // Tron counters
235 private static final String TRON_GUEST_CREATED = "users_guest_created";
236 private static final String TRON_USER_CREATED = "users_user_created";
Christine Franks88220562017-05-24 11:11:21 -0700237 private static final String TRON_DEMO_CREATED = "users_demo_created";
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -0800238
Dianne Hackborn4428e172012-08-24 17:43:05 -0700239 private final Context mContext;
240 private final PackageManagerService mPm;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700241 private final Object mPackagesLock;
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800242 private final UserDataPreparer mUserDataPreparer;
Fyodor Kupolov82402752015-10-28 14:54:51 -0700243 // Short-term lock for internal state, when interaction/sync with PM is not required
Jeff Sharkey5f3e9342017-03-13 14:53:11 -0600244 private final Object mUsersLock = LockGuard.installNewLock(LockGuard.INDEX_USER);
Fyodor Kupolov82402752015-10-28 14:54:51 -0700245 private final Object mRestrictionsLock = new Object();
Fyodor Kupolovd31cee92017-09-05 16:31:08 -0700246 // Used for serializing access to app restriction files
247 private final Object mAppRestrictionsLock = new Object();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700248
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800249 private final Handler mHandler;
250
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700251 private final File mUsersDir;
252 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700253
Svet Ganov9cea80cd2016-02-16 11:47:00 -0800254 private static final IBinder mUserRestriconToken = new Binder();
255
Bookatz04d7ae52019-08-05 14:07:12 -0700256 /** Installs system packages based on user-type. */
257 private final UserSystemPackageInstaller mSystemPackageInstaller;
258
Makoto Onuki068c54a2015-10-13 14:34:03 -0700259 /**
Makoto Onuki73dded22017-12-20 13:14:48 +0900260 * Internal non-parcelable wrapper for UserInfo that is not exposed to other system apps.
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800261 */
Kenny Guy02c89902016-11-15 19:36:38 +0000262 @VisibleForTesting
263 static class UserData {
Amith Yamasani12747872015-12-07 14:19:49 -0800264 // Basic user information and properties
265 UserInfo info;
266 // Account name used when there is a strong association between a user and an account
267 String account;
268 // Account information for seeding into a newly created user. This could also be
269 // used for login validation for an existing user, for updating their credentials.
270 // In the latter case, data may not need to be persisted as it is only valid for the
271 // current login session.
272 String seedAccountName;
273 String seedAccountType;
274 PersistableBundle seedAccountOptions;
275 // Whether to perist the seed account information to be available after a boot
276 boolean persistSeedData;
277
Makoto Onuki73dded22017-12-20 13:14:48 +0900278 /** Elapsed realtime since boot when the user started. */
279 long startRealtime;
280
281 /** Elapsed realtime since boot when the user was unlocked. */
282 long unlockRealtime;
283
arangelov9b632d72018-12-07 23:21:22 +0000284 private long mLastRequestQuietModeEnabledMillis;
285
286 void setLastRequestQuietModeEnabledMillis(long millis) {
287 mLastRequestQuietModeEnabledMillis = millis;
288 }
289
290 long getLastRequestQuietModeEnabledMillis() {
291 return mLastRequestQuietModeEnabledMillis;
292 }
293
Amith Yamasani12747872015-12-07 14:19:49 -0800294 void clearSeedAccountData() {
295 seedAccountName = null;
296 seedAccountType = null;
297 seedAccountOptions = null;
298 persistSeedData = false;
299 }
300 }
301
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800302 @GuardedBy("mUsersLock")
Amith Yamasani12747872015-12-07 14:19:49 -0800303 private final SparseArray<UserData> mUsers = new SparseArray<>();
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800304
305 /**
Makoto Onuki068c54a2015-10-13 14:34:03 -0700306 * User restrictions set via UserManager. This doesn't include restrictions set by
Pavel Grafov6a40f092016-10-25 15:46:51 +0100307 * device owner / profile owners. Only non-empty restriction bundles are stored.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700308 *
309 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
310 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
311 * maybe shared between {@link #mBaseUserRestrictions} and
312 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
313 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700314 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700315 */
316 @GuardedBy("mRestrictionsLock")
317 private final SparseArray<Bundle> mBaseUserRestrictions = new SparseArray<>();
318
319 /**
320 * Cached user restrictions that are in effect -- i.e. {@link #mBaseUserRestrictions} combined
321 * with device / profile owner restrictions. We'll initialize it lazily; use
322 * {@link #getEffectiveUserRestrictions} to access it.
323 *
324 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
325 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
326 * maybe shared between {@link #mBaseUserRestrictions} and
327 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
328 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700329 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700330 */
331 @GuardedBy("mRestrictionsLock")
332 private final SparseArray<Bundle> mCachedEffectiveUserRestrictions = new SparseArray<>();
333
Makoto Onuki4f160732015-10-27 17:15:38 -0700334 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800335 * User restrictions that have already been applied in
336 * {@link #updateUserRestrictionsInternalLR(Bundle, int)}. We use it to detect restrictions
337 * that have changed since the last
338 * {@link #updateUserRestrictionsInternalLR(Bundle, int)} call.
Makoto Onuki4f160732015-10-27 17:15:38 -0700339 */
340 @GuardedBy("mRestrictionsLock")
341 private final SparseArray<Bundle> mAppliedUserRestrictions = new SparseArray<>();
342
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800343 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800344 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
Pavel Grafov6a40f092016-10-25 15:46:51 +0100345 * that should be applied to all users, including guests. Only non-empty restriction bundles are
346 * stored.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800347 */
348 @GuardedBy("mRestrictionsLock")
Pavel Grafov6a40f092016-10-25 15:46:51 +0100349 private final SparseArray<Bundle> mDevicePolicyGlobalUserRestrictions = new SparseArray<>();
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800350
351 /**
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +0100352 * Id of the user that set global restrictions.
353 */
354 @GuardedBy("mRestrictionsLock")
Pavel Grafov6a40f092016-10-25 15:46:51 +0100355 private int mDeviceOwnerUserId = UserHandle.USER_NULL;
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +0100356
357 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800358 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
Pavel Grafov6a40f092016-10-25 15:46:51 +0100359 * for each user. Only non-empty restriction bundles are stored.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800360 */
361 @GuardedBy("mRestrictionsLock")
362 private final SparseArray<Bundle> mDevicePolicyLocalUserRestrictions = new SparseArray<>();
363
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800364 @GuardedBy("mGuestRestrictions")
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530365 private final Bundle mGuestRestrictions = new Bundle();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800366
367 /**
368 * Set of user IDs being actively removed. Removed IDs linger in this set
369 * for several seconds to work around a VFS caching issue.
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700370 * Use {@link #addRemovingUserIdLocked(int)} to add elements to this array
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800371 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700372 @GuardedBy("mUsersLock")
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800373 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700374
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700375 /**
376 * Queue of recently removed userIds. Used for recycling of userIds
377 */
378 @GuardedBy("mUsersLock")
379 private final LinkedList<Integer> mRecentlyRemovedIds = new LinkedList<>();
380
Fyodor Kupolov82402752015-10-28 14:54:51 -0700381 @GuardedBy("mUsersLock")
Amith Yamasani0b285492011-04-14 17:35:23 -0700382 private int[] mUserIds;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800383 @GuardedBy("mPackagesLock")
Amith Yamasani2a003292012-08-14 18:25:45 -0700384 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700385 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700386
Jason Monk62062992014-05-06 09:55:28 -0400387 private IAppOpsService mAppOpsService;
388
Makoto Onuki068c54a2015-10-13 14:34:03 -0700389 private final LocalService mLocalService;
390
Makoto Onukie7927da2015-11-25 10:05:17 -0800391 @GuardedBy("mUsersLock")
392 private boolean mIsDeviceManaged;
393
394 @GuardedBy("mUsersLock")
395 private final SparseBooleanArray mIsUserManaged = new SparseBooleanArray();
396
Makoto Onukid45a4a22015-11-02 17:17:38 -0800397 @GuardedBy("mUserRestrictionsListeners")
398 private final ArrayList<UserRestrictionsListener> mUserRestrictionsListeners =
399 new ArrayList<>();
400
Clara Bayarria1771112015-12-18 16:29:18 +0000401 private final LockPatternUtils mLockPatternUtils;
402
Ricky Waib1dd80b2016-06-07 18:00:55 +0100403 private final String ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK =
404 "com.android.server.pm.DISABLE_QUIET_MODE_AFTER_UNLOCK";
405
406 private final BroadcastReceiver mDisableQuietModeCallback = new BroadcastReceiver() {
407 @Override
408 public void onReceive(Context context, Intent intent) {
Tony Mak64fd8c02017-12-01 19:11:59 +0000409 if (!ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK.equals(intent.getAction())) {
410 return;
Ricky Waib1dd80b2016-06-07 18:00:55 +0100411 }
Tony Mak64fd8c02017-12-01 19:11:59 +0000412 final IntentSender target = intent.getParcelableExtra(Intent.EXTRA_INTENT);
Bookatzf56f2582019-09-04 16:06:41 -0700413 final int userId = intent.getIntExtra(Intent.EXTRA_USER_ID, UserHandle.USER_NULL);
Fyodor Kupolova68a2862018-01-30 18:22:00 -0800414 // Call setQuietModeEnabled on bg thread to avoid ANR
arangelov9b632d72018-12-07 23:21:22 +0000415 BackgroundThread.getHandler().post(() ->
Bookatzf56f2582019-09-04 16:06:41 -0700416 setQuietModeEnabled(userId, false, target, /* callingPackage */ null));
Ricky Waib1dd80b2016-06-07 18:00:55 +0100417 }
418 };
419
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +0100420 /**
Tony Mak64fd8c02017-12-01 19:11:59 +0000421 * Start an {@link IntentSender} when user is unlocked after disabling quiet mode.
422 *
Tony Makbece85d2018-01-12 12:10:17 +0000423 * @see {@link #requestQuietModeEnabled(String, boolean, int, IntentSender)}
Tony Mak64fd8c02017-12-01 19:11:59 +0000424 */
425 private class DisableQuietModeUserUnlockedCallback extends IProgressListener.Stub {
426 private final IntentSender mTarget;
427
428 public DisableQuietModeUserUnlockedCallback(IntentSender target) {
429 Preconditions.checkNotNull(target);
430 mTarget = target;
431 }
432
433 @Override
434 public void onStarted(int id, Bundle extras) {}
435
436 @Override
437 public void onProgress(int id, int progress, Bundle extras) {}
438
439 @Override
440 public void onFinished(int id, Bundle extras) {
441 try {
442 mContext.startIntentSender(mTarget, null, 0, 0, 0);
443 } catch (IntentSender.SendIntentException e) {
444 Slog.e(LOG_TAG, "Failed to start the target in the callback", e);
445 }
446 }
447 }
448
449 /**
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +0100450 * Whether all users should be created ephemeral.
451 */
452 @GuardedBy("mUsersLock")
453 private boolean mForceEphemeralUsers;
454
Amith Yamasaniea1b9d72016-05-27 15:57:38 +0000455 @GuardedBy("mUserStates")
456 private final SparseIntArray mUserStates = new SparseIntArray();
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -0700457
Amith Yamasani258848d2012-08-10 17:06:33 -0700458 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700459
Dianne Hackborn4428e172012-08-24 17:43:05 -0700460 public static UserManagerService getInstance() {
461 synchronized (UserManagerService.class) {
462 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700463 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700464 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700465
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700466 public static class LifeCycle extends SystemService {
467
468 private UserManagerService mUms;
469
470 /**
471 * @param context
472 */
473 public LifeCycle(Context context) {
474 super(context);
475 }
476
477 @Override
478 public void onStart() {
479 mUms = UserManagerService.getInstance();
480 publishBinderService(Context.USER_SERVICE, mUms);
481 }
482
483 @Override
484 public void onBootPhase(int phase) {
485 if (phase == SystemService.PHASE_ACTIVITY_MANAGER_READY) {
486 mUms.cleanupPartialUsers();
487 }
488 }
Makoto Onuki73dded22017-12-20 13:14:48 +0900489
490 @Override
Bookatzf56f2582019-09-04 16:06:41 -0700491 public void onStartUser(@UserIdInt int userId) {
Makoto Onuki73dded22017-12-20 13:14:48 +0900492 synchronized (mUms.mUsersLock) {
Bookatzf56f2582019-09-04 16:06:41 -0700493 final UserData user = mUms.getUserDataLU(userId);
Makoto Onuki73dded22017-12-20 13:14:48 +0900494 if (user != null) {
495 user.startRealtime = SystemClock.elapsedRealtime();
496 }
497 }
498 }
499
500 @Override
Bookatzf56f2582019-09-04 16:06:41 -0700501 public void onUnlockUser(@UserIdInt int userId) {
Makoto Onuki73dded22017-12-20 13:14:48 +0900502 synchronized (mUms.mUsersLock) {
Bookatzf56f2582019-09-04 16:06:41 -0700503 final UserData user = mUms.getUserDataLU(userId);
Makoto Onuki73dded22017-12-20 13:14:48 +0900504 if (user != null) {
505 user.unlockRealtime = SystemClock.elapsedRealtime();
506 }
507 }
508 }
509
510 @Override
Bookatzf56f2582019-09-04 16:06:41 -0700511 public void onStopUser(@UserIdInt int userId) {
Makoto Onuki73dded22017-12-20 13:14:48 +0900512 synchronized (mUms.mUsersLock) {
Bookatzf56f2582019-09-04 16:06:41 -0700513 final UserData user = mUms.getUserDataLU(userId);
Makoto Onuki73dded22017-12-20 13:14:48 +0900514 if (user != null) {
515 user.startRealtime = 0;
516 user.unlockRealtime = 0;
517 }
518 }
519 }
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700520 }
521
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700522 // TODO b/28848102 Add support for test dependencies injection
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800523 @VisibleForTesting
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700524 UserManagerService(Context context) {
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800525 this(context, null, null, new Object(), context.getCacheDir());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700526 }
527
Dianne Hackborn4428e172012-08-24 17:43:05 -0700528 /**
529 * Called by package manager to create the service. This is closely
530 * associated with the package manager, and the given lock is the
531 * package manager's own lock.
532 */
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800533 UserManagerService(Context context, PackageManagerService pm, UserDataPreparer userDataPreparer,
534 Object packagesLock) {
535 this(context, pm, userDataPreparer, packagesLock, Environment.getDataDirectory());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700536 }
537
Dianne Hackborn4428e172012-08-24 17:43:05 -0700538 private UserManagerService(Context context, PackageManagerService pm,
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800539 UserDataPreparer userDataPreparer, Object packagesLock, File dataDir) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700540 mContext = context;
541 mPm = pm;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700542 mPackagesLock = packagesLock;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800543 mHandler = new MainHandler();
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800544 mUserDataPreparer = userDataPreparer;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800545 synchronized (mPackagesLock) {
546 mUsersDir = new File(dataDir, USER_INFO_DIR);
547 mUsersDir.mkdirs();
548 // Make zeroth user directory, for services to migrate their files to that location
549 File userZeroDir = new File(mUsersDir, String.valueOf(UserHandle.USER_SYSTEM));
550 userZeroDir.mkdirs();
551 FileUtils.setPermissions(mUsersDir.toString(),
552 FileUtils.S_IRWXU | FileUtils.S_IRWXG | FileUtils.S_IROTH | FileUtils.S_IXOTH,
553 -1, -1);
554 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
555 initDefaultGuestRestrictions();
556 readUserListLP();
557 sInstance = this;
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700558 }
Bookatz04d7ae52019-08-05 14:07:12 -0700559 mSystemPackageInstaller = new UserSystemPackageInstaller(this);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700560 mLocalService = new LocalService();
561 LocalServices.addService(UserManagerInternal.class, mLocalService);
Clara Bayarria1771112015-12-18 16:29:18 +0000562 mLockPatternUtils = new LockPatternUtils(mContext);
Amith Yamasaniea1b9d72016-05-27 15:57:38 +0000563 mUserStates.put(UserHandle.USER_SYSTEM, UserState.STATE_BOOTING);
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700564 }
565
566 void systemReady() {
Jason Monk62062992014-05-06 09:55:28 -0400567 mAppOpsService = IAppOpsService.Stub.asInterface(
568 ServiceManager.getService(Context.APP_OPS_SERVICE));
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800569
570 synchronized (mRestrictionsLock) {
571 applyUserRestrictionsLR(UserHandle.USER_SYSTEM);
Jason Monk62062992014-05-06 09:55:28 -0400572 }
Samuel Tand9453b82016-03-14 15:57:02 -0700573
574 UserInfo currentGuestUser = findCurrentGuestUser();
575 if (currentGuestUser != null && !hasUserRestriction(
576 UserManager.DISALLOW_CONFIG_WIFI, currentGuestUser.id)) {
577 // If a guest user currently exists, apply the DISALLOW_CONFIG_WIFI option
578 // to it, in case this guest was created in a previous version where this
579 // user restriction was not a default guest restriction.
580 setUserRestriction(UserManager.DISALLOW_CONFIG_WIFI, true, currentGuestUser.id);
581 }
Amith Yamasanieb437d42016-04-29 09:31:25 -0700582
Ricky Waib1dd80b2016-06-07 18:00:55 +0100583 mContext.registerReceiver(mDisableQuietModeCallback,
584 new IntentFilter(ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK),
585 null, mHandler);
Amith Yamasani258848d2012-08-10 17:06:33 -0700586 }
587
Patrick Baumann6ae7afc2019-07-30 13:11:28 -0700588 /**
589 * This method retrieves the {@link UserManagerInternal} only for the purpose of
590 * PackageManagerService construction.
591 */
592 UserManagerInternal getInternalForInjectorOnly() {
593 return mLocalService;
594 }
595
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700596 void cleanupPartialUsers() {
597 // Prune out any partially created, partially removed and ephemeral users.
598 ArrayList<UserInfo> partials = new ArrayList<>();
599 synchronized (mUsersLock) {
600 final int userSize = mUsers.size();
601 for (int i = 0; i < userSize; i++) {
602 UserInfo ui = mUsers.valueAt(i).info;
Felipe Lemec1ca4412019-09-11 09:23:26 -0700603 if ((ui.partial || ui.guestToRemove || (ui.isEphemeral() && !ui.preCreated))
604 && i != 0) {
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700605 partials.add(ui);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700606 addRemovingUserIdLocked(ui.id);
Amith Yamasaniae261892016-06-27 10:40:09 -0700607 ui.partial = true;
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700608 }
609 }
610 }
611 final int partialsSize = partials.size();
612 for (int i = 0; i < partialsSize; i++) {
613 UserInfo ui = partials.get(i);
614 Slog.w(LOG_TAG, "Removing partially created user " + ui.id
615 + " (name=" + ui.name + ")");
616 removeUserState(ui.id);
617 }
618 }
619
Amith Yamasani258848d2012-08-10 17:06:33 -0700620 @Override
Bookatzf56f2582019-09-04 16:06:41 -0700621 public String getUserAccount(@UserIdInt int userId) {
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800622 checkManageUserAndAcrossUsersFullPermission("get user account");
623 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800624 return mUsers.get(userId).account;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800625 }
626 }
627
628 @Override
Bookatzf56f2582019-09-04 16:06:41 -0700629 public void setUserAccount(@UserIdInt int userId, String accountName) {
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800630 checkManageUserAndAcrossUsersFullPermission("set user account");
Amith Yamasani12747872015-12-07 14:19:49 -0800631 UserData userToUpdate = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800632 synchronized (mPackagesLock) {
633 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800634 final UserData userData = mUsers.get(userId);
635 if (userData == null) {
636 Slog.e(LOG_TAG, "User not found for setting user account: u" + userId);
637 return;
638 }
639 String currentAccount = userData.account;
Narayan Kamath607223f2018-02-19 14:09:02 +0000640 if (!Objects.equals(currentAccount, accountName)) {
Amith Yamasani12747872015-12-07 14:19:49 -0800641 userData.account = accountName;
642 userToUpdate = userData;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800643 }
644 }
645
646 if (userToUpdate != null) {
647 writeUserLP(userToUpdate);
648 }
649 }
650 }
651
652 @Override
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700653 public UserInfo getPrimaryUser() {
654 checkManageUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700655 synchronized (mUsersLock) {
Amith Yamasani515d4062015-09-28 11:30:06 -0700656 final int userSize = mUsers.size();
657 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800658 UserInfo ui = mUsers.valueAt(i).info;
Xiaohui Chend3e9e182015-11-18 13:37:32 -0800659 if (ui.isPrimary() && !mRemovingUserIds.get(ui.id)) {
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700660 return ui;
661 }
662 }
663 }
664 return null;
665 }
666
Xiaohui Chen594f2082015-08-18 11:04:20 -0700667 public @NonNull List<UserInfo> getUsers(boolean excludeDying) {
Felipe Lemec1ca4412019-09-11 09:23:26 -0700668 return getUsers(/*excludePartial= */ true, excludeDying, /* excludePreCreated= */ true);
669 }
670
Felipe Leme09a7f2d2019-10-02 16:27:46 -0700671 @Override
672 public @NonNull List<UserInfo> getUsers(boolean excludePartial, boolean excludeDying,
Felipe Lemec1ca4412019-09-11 09:23:26 -0700673 boolean excludePreCreated) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -0700674 checkManageOrCreateUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700675 synchronized (mUsersLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700676 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasani515d4062015-09-28 11:30:06 -0700677 final int userSize = mUsers.size();
678 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800679 UserInfo ui = mUsers.valueAt(i).info;
Felipe Lemec1ca4412019-09-11 09:23:26 -0700680 if ((excludePartial && ui.partial)
681 || (excludeDying && mRemovingUserIds.get(ui.id))
682 || (excludePreCreated && ui.preCreated)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700683 continue;
684 }
Felipe Lemec1ca4412019-09-11 09:23:26 -0700685 users.add(userWithName(ui));
Amith Yamasani13593602012-03-22 16:16:17 -0700686 }
687 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700688 }
Amith Yamasani13593602012-03-22 16:16:17 -0700689 }
690
Amith Yamasani258848d2012-08-10 17:06:33 -0700691 @Override
Bookatzf56f2582019-09-04 16:06:41 -0700692 public List<UserInfo> getProfiles(@UserIdInt int userId, boolean enabledOnly) {
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700693 boolean returnFullInfo = true;
Amith Yamasani4f582632014-02-19 14:31:52 -0800694 if (userId != UserHandle.getCallingUserId()) {
Sudheer Shanka74680912016-07-29 11:03:37 -0700695 checkManageOrCreateUsersPermission("getting profiles related to user " + userId);
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700696 } else {
697 returnFullInfo = hasManageUsersPermission();
Amith Yamasani4f582632014-02-19 14:31:52 -0800698 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700699 final long ident = Binder.clearCallingIdentity();
700 try {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700701 synchronized (mUsersLock) {
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700702 return getProfilesLU(userId, enabledOnly, returnFullInfo);
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100703 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700704 } finally {
705 Binder.restoreCallingIdentity(ident);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000706 }
707 }
708
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700709 @Override
Bookatzf56f2582019-09-04 16:06:41 -0700710 public int[] getProfileIds(@UserIdInt int userId, boolean enabledOnly) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700711 if (userId != UserHandle.getCallingUserId()) {
bohu12d23a12016-09-26 16:20:07 -0700712 checkManageOrCreateUsersPermission("getting profiles related to user " + userId);
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700713 }
714 final long ident = Binder.clearCallingIdentity();
715 try {
716 synchronized (mUsersLock) {
717 return getProfileIdsLU(userId, enabledOnly).toArray();
718 }
719 } finally {
720 Binder.restoreCallingIdentity(ident);
721 }
722 }
723
Amith Yamasanibe465322014-04-24 13:45:17 -0700724 /** Assume permissions already checked and caller's identity cleared */
Andreas Gampe2e8c7672018-07-20 13:01:08 -0700725 @GuardedBy("mUsersLock")
Bookatzf56f2582019-09-04 16:06:41 -0700726 private List<UserInfo> getProfilesLU(@UserIdInt int userId, boolean enabledOnly,
727 boolean fullInfo) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700728 IntArray profileIds = getProfileIdsLU(userId, enabledOnly);
729 ArrayList<UserInfo> users = new ArrayList<>(profileIds.size());
730 for (int i = 0; i < profileIds.size(); i++) {
731 int profileId = profileIds.get(i);
732 UserInfo userInfo = mUsers.get(profileId).info;
733 // If full info is not required - clear PII data to prevent 3P apps from reading it
734 if (!fullInfo) {
735 userInfo = new UserInfo(userInfo);
736 userInfo.name = null;
737 userInfo.iconPath = null;
738 } else {
739 userInfo = userWithName(userInfo);
740 }
741 users.add(userInfo);
742 }
743 return users;
744 }
745
746 /**
747 * Assume permissions already checked and caller's identity cleared
748 */
Andreas Gampe2e8c7672018-07-20 13:01:08 -0700749 @GuardedBy("mUsersLock")
Bookatzf56f2582019-09-04 16:06:41 -0700750 private IntArray getProfileIdsLU(@UserIdInt int userId, boolean enabledOnly) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700751 UserInfo user = getUserInfoLU(userId);
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700752 IntArray result = new IntArray(mUsers.size());
Amith Yamasanidda003f2014-08-28 18:06:51 -0700753 if (user == null) {
754 // Probably a dying user
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700755 return result;
Amith Yamasanidda003f2014-08-28 18:06:51 -0700756 }
Amith Yamasani515d4062015-09-28 11:30:06 -0700757 final int userSize = mUsers.size();
758 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800759 UserInfo profile = mUsers.valueAt(i).info;
Amith Yamasanibe465322014-04-24 13:45:17 -0700760 if (!isProfileOf(user, profile)) {
761 continue;
762 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100763 if (enabledOnly && !profile.isEnabled()) {
764 continue;
Amith Yamasanibe465322014-04-24 13:45:17 -0700765 }
Amith Yamasani70fcf0c2014-07-11 08:40:19 -0700766 if (mRemovingUserIds.get(profile.id)) {
767 continue;
768 }
Tony Mak80189cd2016-04-05 17:21:42 +0100769 if (profile.partial) {
770 continue;
771 }
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700772 result.add(profile.id);
Amith Yamasanibe465322014-04-24 13:45:17 -0700773 }
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700774 return result;
Amith Yamasanibe465322014-04-24 13:45:17 -0700775 }
776
Jessica Hummelbe81c802014-04-22 15:49:22 +0100777 @Override
Bookatzf56f2582019-09-04 16:06:41 -0700778 public int getCredentialOwnerProfile(@UserIdInt int userId) {
Andres Moralesc5548c02015-08-05 10:23:12 -0700779 checkManageUsersPermission("get the credential owner");
Bookatzf56f2582019-09-04 16:06:41 -0700780 if (!mLockPatternUtils.isSeparateProfileChallengeEnabled(userId)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700781 synchronized (mUsersLock) {
Bookatzf56f2582019-09-04 16:06:41 -0700782 UserInfo profileParent = getProfileParentLU(userId);
Andres Moralesc5548c02015-08-05 10:23:12 -0700783 if (profileParent != null) {
784 return profileParent.id;
785 }
786 }
787 }
788
Bookatzf56f2582019-09-04 16:06:41 -0700789 return userId;
Andres Moralesc5548c02015-08-05 10:23:12 -0700790 }
791
792 @Override
Bookatzf56f2582019-09-04 16:06:41 -0700793 public boolean isSameProfileGroup(@UserIdInt int userId, int otherUserId) {
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700794 if (userId == otherUserId) return true;
795 checkManageUsersPermission("check if in the same profile group");
Fyodor Kupolov0fb772e2016-10-13 16:27:34 -0700796 return isSameProfileGroupNoChecks(userId, otherUserId);
797 }
798
Bookatzf56f2582019-09-04 16:06:41 -0700799 private boolean isSameProfileGroupNoChecks(@UserIdInt int userId, int otherUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700800 synchronized (mUsersLock) {
801 UserInfo userInfo = getUserInfoLU(userId);
802 if (userInfo == null || userInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
803 return false;
804 }
805 UserInfo otherUserInfo = getUserInfoLU(otherUserId);
806 if (otherUserInfo == null
807 || otherUserInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
808 return false;
809 }
810 return userInfo.profileGroupId == otherUserInfo.profileGroupId;
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700811 }
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700812 }
813
814 @Override
Bookatzf56f2582019-09-04 16:06:41 -0700815 public UserInfo getProfileParent(@UserIdInt int userId) {
Jessica Hummelbe81c802014-04-22 15:49:22 +0100816 checkManageUsersPermission("get the profile parent");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700817 synchronized (mUsersLock) {
Bookatzf56f2582019-09-04 16:06:41 -0700818 return getProfileParentLU(userId);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700819 }
820 }
821
Jakub Pawlowski0f1f5b72017-11-15 14:50:43 -0800822 @Override
Bookatzf56f2582019-09-04 16:06:41 -0700823 public int getProfileParentId(@UserIdInt int userId) {
Jakub Pawlowski0f1f5b72017-11-15 14:50:43 -0800824 checkManageUsersPermission("get the profile parent");
Bookatzf56f2582019-09-04 16:06:41 -0700825 return mLocalService.getProfileParentId(userId);
Jakub Pawlowski0f1f5b72017-11-15 14:50:43 -0800826 }
827
Andreas Gampe2e8c7672018-07-20 13:01:08 -0700828 @GuardedBy("mUsersLock")
Bookatzf56f2582019-09-04 16:06:41 -0700829 private UserInfo getProfileParentLU(@UserIdInt int userId) {
830 UserInfo profile = getUserInfoLU(userId);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700831 if (profile == null) {
832 return null;
833 }
834 int parentUserId = profile.profileGroupId;
Bookatzf56f2582019-09-04 16:06:41 -0700835 if (parentUserId == userId || parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700836 return null;
837 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700838 return getUserInfoLU(parentUserId);
Jessica Hummelbe81c802014-04-22 15:49:22 +0100839 }
840 }
841
Fyodor Kupolov82402752015-10-28 14:54:51 -0700842 private static boolean isProfileOf(UserInfo user, UserInfo profile) {
Kenny Guy2a764942014-04-02 13:29:20 +0100843 return user.id == profile.id ||
844 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
845 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000846 }
847
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000848 private void broadcastProfileAvailabilityChanges(UserHandle profileHandle,
Rubin Xuf13c9802016-01-21 18:06:00 +0000849 UserHandle parentHandle, boolean inQuietMode) {
Rubin Xue95057a2016-04-01 16:49:25 +0100850 Intent intent = new Intent();
851 if (inQuietMode) {
852 intent.setAction(Intent.ACTION_MANAGED_PROFILE_UNAVAILABLE);
853 } else {
854 intent.setAction(Intent.ACTION_MANAGED_PROFILE_AVAILABLE);
855 }
Rubin Xuf13c9802016-01-21 18:06:00 +0000856 intent.putExtra(Intent.EXTRA_QUIET_MODE, inQuietMode);
857 intent.putExtra(Intent.EXTRA_USER, profileHandle);
858 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileHandle.getIdentifier());
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000859 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Rubin Xuf13c9802016-01-21 18:06:00 +0000860 mContext.sendBroadcastAsUser(intent, parentHandle);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000861 }
862
863 @Override
Tony Makbece85d2018-01-12 12:10:17 +0000864 public boolean requestQuietModeEnabled(@NonNull String callingPackage, boolean enableQuietMode,
Bookatzf56f2582019-09-04 16:06:41 -0700865 @UserIdInt int userId, @Nullable IntentSender target) {
Tony Make3d1f652017-12-12 11:00:37 +0000866 Preconditions.checkNotNull(callingPackage);
867
Tony Makb7e6fd42017-12-05 19:40:28 +0000868 if (enableQuietMode && target != null) {
869 throw new IllegalArgumentException(
870 "target should only be specified when we are disabling quiet mode.");
871 }
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000872
Tony Makd390ae92017-12-28 13:23:10 +0000873 ensureCanModifyQuietMode(callingPackage, Binder.getCallingUid(), target != null);
Tony Makb7e6fd42017-12-05 19:40:28 +0000874 final long identity = Binder.clearCallingIdentity();
875 try {
arangelov9b632d72018-12-07 23:21:22 +0000876 boolean result = false;
Tony Makb7e6fd42017-12-05 19:40:28 +0000877 if (enableQuietMode) {
arangelov9b632d72018-12-07 23:21:22 +0000878 setQuietModeEnabled(
Bookatzf56f2582019-09-04 16:06:41 -0700879 userId, true /* enableQuietMode */, target, callingPackage);
arangelov9b632d72018-12-07 23:21:22 +0000880 result = true;
Tony Makb7e6fd42017-12-05 19:40:28 +0000881 } else {
882 boolean needToShowConfirmCredential =
Bookatzf56f2582019-09-04 16:06:41 -0700883 mLockPatternUtils.isSecure(userId)
884 && !StorageManager.isUserKeyUnlocked(userId);
Tony Makb7e6fd42017-12-05 19:40:28 +0000885 if (needToShowConfirmCredential) {
Bookatzf56f2582019-09-04 16:06:41 -0700886 showConfirmCredentialToDisableQuietMode(userId, target);
Tony Makb7e6fd42017-12-05 19:40:28 +0000887 } else {
arangelov9b632d72018-12-07 23:21:22 +0000888 setQuietModeEnabled(
Bookatzf56f2582019-09-04 16:06:41 -0700889 userId, false /* enableQuietMode */, target, callingPackage);
arangelov9b632d72018-12-07 23:21:22 +0000890 result = true;
Tony Makb7e6fd42017-12-05 19:40:28 +0000891 }
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000892 }
arangelov9b632d72018-12-07 23:21:22 +0000893 return result;
Tony Makb7e6fd42017-12-05 19:40:28 +0000894 } finally {
895 Binder.restoreCallingIdentity(identity);
896 }
897 }
898
Tony Make3d1f652017-12-12 11:00:37 +0000899 /**
Tony Makd390ae92017-12-28 13:23:10 +0000900 * The caller can modify quiet mode if it meets one of these conditions:
Tony Make3d1f652017-12-12 11:00:37 +0000901 * <ul>
902 * <li>Has system UID or root UID</li>
903 * <li>Has {@link Manifest.permission#MODIFY_QUIET_MODE}</li>
904 * <li>Has {@link Manifest.permission#MANAGE_USERS}</li>
905 * </ul>
Tony Makd390ae92017-12-28 13:23:10 +0000906 * <p>
907 * If caller wants to start an intent after disabling the quiet mode, it must has
908 * {@link Manifest.permission#MANAGE_USERS}.
Tony Make3d1f652017-12-12 11:00:37 +0000909 */
Tony Makd390ae92017-12-28 13:23:10 +0000910 private void ensureCanModifyQuietMode(String callingPackage, int callingUid,
911 boolean startIntent) {
Tony Make3d1f652017-12-12 11:00:37 +0000912 if (hasManageUsersPermission()) {
Tony Makd390ae92017-12-28 13:23:10 +0000913 return;
Tony Make3d1f652017-12-12 11:00:37 +0000914 }
Tony Makd390ae92017-12-28 13:23:10 +0000915 if (startIntent) {
916 throw new SecurityException("MANAGE_USERS permission is required to start intent "
917 + "after disabling quiet mode.");
918 }
jovanakf24ad492018-05-18 12:15:59 -0700919 final boolean hasModifyQuietModePermission = hasPermissionGranted(
920 Manifest.permission.MODIFY_QUIET_MODE, callingUid);
Tony Make3d1f652017-12-12 11:00:37 +0000921 if (hasModifyQuietModePermission) {
Tony Makd390ae92017-12-28 13:23:10 +0000922 return;
Tony Make3d1f652017-12-12 11:00:37 +0000923 }
924
Tony Makd390ae92017-12-28 13:23:10 +0000925 verifyCallingPackage(callingPackage, callingUid);
Tony Make3d1f652017-12-12 11:00:37 +0000926 final ShortcutServiceInternal shortcutInternal =
927 LocalServices.getService(ShortcutServiceInternal.class);
928 if (shortcutInternal != null) {
929 boolean isForegroundLauncher =
930 shortcutInternal.isForegroundDefaultLauncher(callingPackage, callingUid);
931 if (isForegroundLauncher) {
Tony Makd390ae92017-12-28 13:23:10 +0000932 return;
Tony Make3d1f652017-12-12 11:00:37 +0000933 }
934 }
Tony Makd390ae92017-12-28 13:23:10 +0000935 throw new SecurityException("Can't modify quiet mode, caller is neither foreground "
936 + "default launcher nor has MANAGE_USERS/MODIFY_QUIET_MODE permission");
Tony Make3d1f652017-12-12 11:00:37 +0000937 }
938
Bookatzf56f2582019-09-04 16:06:41 -0700939 private void setQuietModeEnabled(@UserIdInt int userId, boolean enableQuietMode,
arangelov9b632d72018-12-07 23:21:22 +0000940 IntentSender target, @Nullable String callingPackage) {
Tony Makb7e6fd42017-12-05 19:40:28 +0000941 final UserInfo profile, parent;
942 final UserData profileUserData;
943 synchronized (mUsersLock) {
Bookatzf56f2582019-09-04 16:06:41 -0700944 profile = getUserInfoLU(userId);
945 parent = getProfileParentLU(userId);
Tony Makb7e6fd42017-12-05 19:40:28 +0000946
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000947 if (profile == null || !profile.isManagedProfile()) {
Bookatzf56f2582019-09-04 16:06:41 -0700948 throw new IllegalArgumentException("User " + userId + " is not a profile");
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000949 }
Tony Makb7e6fd42017-12-05 19:40:28 +0000950 if (profile.isQuietModeEnabled() == enableQuietMode) {
951 Slog.i(LOG_TAG, "Quiet mode is already " + enableQuietMode);
952 return;
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000953 }
Tony Makb7e6fd42017-12-05 19:40:28 +0000954 profile.flags ^= UserInfo.FLAG_QUIET_MODE;
955 profileUserData = getUserDataLU(profile.id);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000956 }
Tony Makb7e6fd42017-12-05 19:40:28 +0000957 synchronized (mPackagesLock) {
958 writeUserLP(profileUserData);
959 }
960 try {
961 if (enableQuietMode) {
Bookatzf56f2582019-09-04 16:06:41 -0700962 ActivityManager.getService().stopUser(userId, /* force */true, null);
Tony Makb7e6fd42017-12-05 19:40:28 +0000963 LocalServices.getService(ActivityManagerInternal.class)
Bookatzf56f2582019-09-04 16:06:41 -0700964 .killForegroundAppsForUser(userId);
Tony Makb7e6fd42017-12-05 19:40:28 +0000965 } else {
966 IProgressListener callback = target != null
967 ? new DisableQuietModeUserUnlockedCallback(target)
968 : null;
969 ActivityManager.getService().startUserInBackgroundWithListener(
Bookatzf56f2582019-09-04 16:06:41 -0700970 userId, callback);
Rubin Xuf13c9802016-01-21 18:06:00 +0000971 }
Bookatzf56f2582019-09-04 16:06:41 -0700972 logQuietModeEnabled(userId, enableQuietMode, callingPackage);
Tony Makb7e6fd42017-12-05 19:40:28 +0000973 } catch (RemoteException e) {
974 // Should not happen, same process.
975 e.rethrowAsRuntimeException();
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000976 }
Tony Makb7e6fd42017-12-05 19:40:28 +0000977 broadcastProfileAvailabilityChanges(profile.getUserHandle(), parent.getUserHandle(),
978 enableQuietMode);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000979 }
980
Bookatzf56f2582019-09-04 16:06:41 -0700981 private void logQuietModeEnabled(@UserIdInt int userId, boolean enableQuietMode,
arangelov9b632d72018-12-07 23:21:22 +0000982 @Nullable String callingPackage) {
983 UserData userData;
984 synchronized (mUsersLock) {
Bookatzf56f2582019-09-04 16:06:41 -0700985 userData = getUserDataLU(userId);
arangelov9b632d72018-12-07 23:21:22 +0000986 }
987 if (userData == null) {
988 return;
989 }
990 final long now = System.currentTimeMillis();
991 final long period = (userData.getLastRequestQuietModeEnabledMillis() != 0L
992 ? now - userData.getLastRequestQuietModeEnabledMillis()
993 : now - userData.info.creationTime);
994 DevicePolicyEventLogger
995 .createEvent(DevicePolicyEnums.REQUEST_QUIET_MODE_ENABLED)
996 .setStrings(callingPackage)
997 .setBoolean(enableQuietMode)
998 .setTimePeriod(period)
999 .write();
1000 userData.setLastRequestQuietModeEnabledMillis(now);
1001 }
1002
Rubin Xu0a29ecd2015-11-04 15:11:48 +00001003 @Override
Bookatzf56f2582019-09-04 16:06:41 -07001004 public boolean isQuietModeEnabled(@UserIdInt int userId) {
Rubin Xu0a29ecd2015-11-04 15:11:48 +00001005 synchronized (mPackagesLock) {
1006 UserInfo info;
1007 synchronized (mUsersLock) {
Bookatzf56f2582019-09-04 16:06:41 -07001008 info = getUserInfoLU(userId);
Rubin Xu0a29ecd2015-11-04 15:11:48 +00001009 }
1010 if (info == null || !info.isManagedProfile()) {
Rubin Xuf13c9802016-01-21 18:06:00 +00001011 return false;
Rubin Xu0a29ecd2015-11-04 15:11:48 +00001012 }
1013 return info.isQuietModeEnabled();
1014 }
1015 }
1016
Tony Makb7e6fd42017-12-05 19:40:28 +00001017 /**
1018 * Show confirm credential screen to unlock user in order to turn off quiet mode.
1019 */
1020 private void showConfirmCredentialToDisableQuietMode(
Bookatzf56f2582019-09-04 16:06:41 -07001021 @UserIdInt int userId, @Nullable IntentSender target) {
Tony Makb7e6fd42017-12-05 19:40:28 +00001022 // otherwise, we show a profile challenge to trigger decryption of the user
1023 final KeyguardManager km = (KeyguardManager) mContext.getSystemService(
1024 Context.KEYGUARD_SERVICE);
Bookatzf56f2582019-09-04 16:06:41 -07001025 // We should use userId not credentialOwnerUserId here, as even if it is unified
Tony Makb7e6fd42017-12-05 19:40:28 +00001026 // lock, confirm screenlock page will know and show personal challenge, and unlock
1027 // work profile when personal challenge is correct
Bookatzf56f2582019-09-04 16:06:41 -07001028 final Intent unlockIntent = km.createConfirmDeviceCredentialIntent(null, null, userId);
Tony Makb7e6fd42017-12-05 19:40:28 +00001029 if (unlockIntent == null) {
1030 return;
Benjamin Franzf02420c2016-04-04 18:52:21 +01001031 }
Tony Makb7e6fd42017-12-05 19:40:28 +00001032 final Intent callBackIntent = new Intent(
1033 ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK);
1034 if (target != null) {
1035 callBackIntent.putExtra(Intent.EXTRA_INTENT, target);
Benjamin Franzf02420c2016-04-04 18:52:21 +01001036 }
Bookatzf56f2582019-09-04 16:06:41 -07001037 callBackIntent.putExtra(Intent.EXTRA_USER_ID, userId);
Tony Makb7e6fd42017-12-05 19:40:28 +00001038 callBackIntent.setPackage(mContext.getPackageName());
1039 callBackIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1040 final PendingIntent pendingIntent = PendingIntent.getBroadcast(
1041 mContext,
1042 0,
1043 callBackIntent,
1044 PendingIntent.FLAG_CANCEL_CURRENT |
1045 PendingIntent.FLAG_ONE_SHOT |
1046 PendingIntent.FLAG_IMMUTABLE);
1047 // After unlocking the challenge, it will disable quiet mode and run the original
1048 // intentSender
1049 unlockIntent.putExtra(Intent.EXTRA_INTENT, pendingIntent.getIntentSender());
1050 unlockIntent.setFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
1051 mContext.startActivity(unlockIntent);
Benjamin Franzf02420c2016-04-04 18:52:21 +01001052 }
1053
1054 @Override
Bookatzf56f2582019-09-04 16:06:41 -07001055 public void setUserEnabled(@UserIdInt int userId) {
Alexandra Gherghinadf35d572014-04-09 13:54:39 +01001056 checkManageUsersPermission("enable user");
1057 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001058 UserInfo info;
1059 synchronized (mUsersLock) {
1060 info = getUserInfoLU(userId);
1061 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +01001062 if (info != null && !info.isEnabled()) {
1063 info.flags ^= UserInfo.FLAG_DISABLED;
Amith Yamasani12747872015-12-07 14:19:49 -08001064 writeUserLP(getUserDataLU(info.id));
Alexandra Gherghinadf35d572014-04-09 13:54:39 +01001065 }
1066 }
1067 }
1068
jovanakf24ad492018-05-18 12:15:59 -07001069 @Override
Bookatzf56f2582019-09-04 16:06:41 -07001070 public void setUserAdmin(@UserIdInt int userId) {
jovanakf24ad492018-05-18 12:15:59 -07001071 checkManageUserAndAcrossUsersFullPermission("set user admin");
1072
1073 synchronized (mPackagesLock) {
1074 UserInfo info;
1075 synchronized (mUsersLock) {
1076 info = getUserInfoLU(userId);
1077 }
1078 if (info == null || info.isAdmin()) {
1079 // Exit if no user found with that id, or the user is already an Admin.
1080 return;
1081 }
1082
1083 info.flags ^= UserInfo.FLAG_ADMIN;
1084 writeUserLP(getUserDataLU(info.id));
1085 }
1086
1087 // Remove non-admin restrictions.
1088 // Keep synchronized with createUserEvenWhenDisallowed.
1089 setUserRestriction(UserManager.DISALLOW_SMS, false, userId);
1090 setUserRestriction(UserManager.DISALLOW_OUTGOING_CALLS, false, userId);
1091 }
1092
Andrew Scull85a63bc2016-10-24 13:47:47 +01001093 /**
1094 * Evicts a user's CE key by stopping and restarting the user.
1095 *
1096 * The key is evicted automatically by the user controller when the user has stopped.
1097 */
1098 @Override
1099 public void evictCredentialEncryptionKey(@UserIdInt int userId) {
1100 checkManageUsersPermission("evict CE key");
1101 final IActivityManager am = ActivityManagerNative.getDefault();
1102 final long identity = Binder.clearCallingIdentity();
1103 try {
1104 am.restartUserInBackground(userId);
1105 } catch (RemoteException re) {
1106 throw re.rethrowAsRuntimeException();
1107 } finally {
1108 Binder.restoreCallingIdentity(identity);
1109 }
1110 }
1111
Alexandra Gherghinadf35d572014-04-09 13:54:39 +01001112 @Override
Bookatzf56f2582019-09-04 16:06:41 -07001113 public UserInfo getUserInfo(@UserIdInt int userId) {
Sudheer Shankaaccaa082016-06-14 16:22:57 -07001114 checkManageOrCreateUsersPermission("query user");
Tony Mak8673b282016-03-21 21:10:59 +00001115 synchronized (mUsersLock) {
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001116 return userWithName(getUserInfoLU(userId));
1117 }
1118 }
1119
1120 /**
1121 * Returns a UserInfo object with the name filled in, for Owner, or the original
1122 * if the name is already set.
1123 */
1124 private UserInfo userWithName(UserInfo orig) {
1125 if (orig != null && orig.name == null && orig.id == UserHandle.USER_SYSTEM) {
1126 UserInfo withName = new UserInfo(orig);
1127 withName.name = getOwnerName();
1128 return withName;
1129 } else {
1130 return orig;
Tony Mak8673b282016-03-21 21:10:59 +00001131 }
1132 }
1133
1134 @Override
Kenny Guy02c89902016-11-15 19:36:38 +00001135 public int getManagedProfileBadge(@UserIdInt int userId) {
Jon Miranda2b340a22019-01-25 14:03:49 -08001136 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "getManagedProfileBadge");
Kenny Guy02c89902016-11-15 19:36:38 +00001137 synchronized (mUsersLock) {
1138 UserInfo userInfo = getUserInfoLU(userId);
1139 return userInfo != null ? userInfo.profileBadge : 0;
1140 }
1141 }
1142
1143 @Override
Bookatzf56f2582019-09-04 16:06:41 -07001144 public boolean isManagedProfile(@UserIdInt int userId) {
Jon Miranda2b340a22019-01-25 14:03:49 -08001145 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isManagedProfile");
Fyodor Kupolov82402752015-10-28 14:54:51 -07001146 synchronized (mUsersLock) {
Amith Yamasani1c41dc82016-06-28 16:13:15 -07001147 UserInfo userInfo = getUserInfoLU(userId);
Tony Mak8673b282016-03-21 21:10:59 +00001148 return userInfo != null && userInfo.isManagedProfile();
Amith Yamasani13593602012-03-22 16:16:17 -07001149 }
1150 }
1151
Amith Yamasani71e6c692013-03-24 17:39:28 -07001152 @Override
Bookatzf56f2582019-09-04 16:06:41 -07001153 public boolean isUserUnlockingOrUnlocked(@UserIdInt int userId) {
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08001154 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isUserUnlockingOrUnlocked");
Fyodor Kupolovc413f702016-10-06 17:11:14 -07001155 return mLocalService.isUserUnlockingOrUnlocked(userId);
1156 }
1157
1158 @Override
Bookatzf56f2582019-09-04 16:06:41 -07001159 public boolean isUserUnlocked(@UserIdInt int userId) {
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08001160 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isUserUnlocked");
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07001161 return mLocalService.isUserUnlocked(userId);
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08001162 }
1163
1164 @Override
Bookatzf56f2582019-09-04 16:06:41 -07001165 public boolean isUserRunning(@UserIdInt int userId) {
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08001166 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isUserRunning");
1167 return mLocalService.isUserRunning(userId);
1168 }
1169
Makoto Onuki73dded22017-12-20 13:14:48 +09001170 @Override
Bookatzcde3d922019-03-08 14:30:00 -08001171 public String getUserName() {
1172 if (!hasManageUsersOrPermission(android.Manifest.permission.GET_ACCOUNTS_PRIVILEGED)) {
1173 throw new SecurityException("You need MANAGE_USERS or GET_ACCOUNTS_PRIVILEGED "
1174 + "permissions to: get user name");
1175 }
1176 final int userId = UserHandle.getUserId(Binder.getCallingUid());
1177 synchronized (mUsersLock) {
1178 UserInfo userInfo = userWithName(getUserInfoLU(userId));
1179 return userInfo == null ? "" : userInfo.name;
1180 }
1181 }
1182
1183 @Override
Makoto Onuki73dded22017-12-20 13:14:48 +09001184 public long getUserStartRealtime() {
1185 final int userId = UserHandle.getUserId(Binder.getCallingUid());
1186 synchronized (mUsersLock) {
1187 final UserData user = getUserDataLU(userId);
1188 if (user != null) {
1189 return user.startRealtime;
1190 }
1191 return 0;
1192 }
1193 }
1194
1195 @Override
1196 public long getUserUnlockRealtime() {
1197 synchronized (mUsersLock) {
1198 final UserData user = getUserDataLU(UserHandle.getUserId(Binder.getCallingUid()));
1199 if (user != null) {
1200 return user.unlockRealtime;
1201 }
1202 return 0;
1203 }
1204 }
1205
Bookatzf56f2582019-09-04 16:06:41 -07001206 private void checkManageOrInteractPermIfCallerInOtherProfileGroup(@UserIdInt int userId,
1207 String name) {
Felipe Lemec1ca4412019-09-11 09:23:26 -07001208 final int callingUserId = UserHandle.getCallingUserId();
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08001209 if (callingUserId == userId || isSameProfileGroupNoChecks(callingUserId, userId) ||
1210 hasManageUsersPermission()) {
1211 return;
1212 }
jovanakf24ad492018-05-18 12:15:59 -07001213 if (!hasPermissionGranted(Manifest.permission.INTERACT_ACROSS_USERS,
1214 Binder.getCallingUid())) {
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08001215 throw new SecurityException("You need INTERACT_ACROSS_USERS or MANAGE_USERS permission "
1216 + "to: check " + name);
1217 }
1218 }
1219
1220 @Override
Bookatzf56f2582019-09-04 16:06:41 -07001221 public boolean isDemoUser(@UserIdInt int userId) {
Felipe Lemec1ca4412019-09-11 09:23:26 -07001222 final int callingUserId = UserHandle.getCallingUserId();
Amith Yamasani1c41dc82016-06-28 16:13:15 -07001223 if (callingUserId != userId && !hasManageUsersPermission()) {
1224 throw new SecurityException("You need MANAGE_USERS permission to query if u=" + userId
1225 + " is a demo user");
1226 }
1227 synchronized (mUsersLock) {
1228 UserInfo userInfo = getUserInfoLU(userId);
1229 return userInfo != null && userInfo.isDemo();
1230 }
1231 }
1232
1233 @Override
Felipe Lemec1ca4412019-09-11 09:23:26 -07001234 public boolean isPreCreated(@UserIdInt int userId) {
1235 final int callingUserId = UserHandle.getCallingUserId();
1236 if (callingUserId != userId && !hasManageUsersPermission()) {
1237 throw new SecurityException("You need MANAGE_USERS permission to query if u=" + userId
1238 + " is pre-created");
1239 }
1240 synchronized (mUsersLock) {
1241 UserInfo userInfo = getUserInfoLU(userId);
1242 return userInfo != null && userInfo.preCreated;
1243 }
1244 }
1245
1246 @Override
Amith Yamasani71e6c692013-03-24 17:39:28 -07001247 public boolean isRestricted() {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001248 synchronized (mUsersLock) {
1249 return getUserInfoLU(UserHandle.getCallingUserId()).isRestricted();
Amith Yamasani71e6c692013-03-24 17:39:28 -07001250 }
1251 }
1252
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001253 @Override
Bookatzf56f2582019-09-04 16:06:41 -07001254 public boolean canHaveRestrictedProfile(@UserIdInt int userId) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001255 checkManageUsersPermission("canHaveRestrictedProfile");
Fyodor Kupolov82402752015-10-28 14:54:51 -07001256 synchronized (mUsersLock) {
1257 final UserInfo userInfo = getUserInfoLU(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001258 if (userInfo == null || !userInfo.canHaveProfile()) {
1259 return false;
1260 }
1261 if (!userInfo.isAdmin()) {
1262 return false;
1263 }
Makoto Onukie7927da2015-11-25 10:05:17 -08001264 // restricted profile can be created if there is no DO set and the admin user has no PO;
1265 return !mIsDeviceManaged && !mIsUserManaged.get(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001266 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001267 }
1268
Fyodor Kupolovca177562017-11-09 17:43:01 -08001269 @Override
1270 public boolean hasRestrictedProfiles() {
1271 checkManageUsersPermission("hasRestrictedProfiles");
1272 final int callingUserId = UserHandle.getCallingUserId();
1273 synchronized (mUsersLock) {
1274 final int userSize = mUsers.size();
1275 for (int i = 0; i < userSize; i++) {
1276 UserInfo profile = mUsers.valueAt(i).info;
1277 if (callingUserId != profile.id
1278 && profile.restrictedProfileParentId == callingUserId) {
1279 return true;
1280 }
1281 }
1282 return false;
1283 }
1284 }
1285
Amith Yamasani195263742012-08-21 15:40:12 -07001286 /*
1287 * Should be locked on mUsers before calling this.
1288 */
Andreas Gampe2e8c7672018-07-20 13:01:08 -07001289 @GuardedBy("mUsersLock")
Bookatzf56f2582019-09-04 16:06:41 -07001290 private UserInfo getUserInfoLU(@UserIdInt int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -08001291 final UserData userData = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -07001292 // If it is partial and not in the process of being removed, return as unknown user.
Amith Yamasani12747872015-12-07 14:19:49 -08001293 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001294 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
1295 return null;
1296 }
Amith Yamasani12747872015-12-07 14:19:49 -08001297 return userData != null ? userData.info : null;
1298 }
1299
Andreas Gampe2e8c7672018-07-20 13:01:08 -07001300 @GuardedBy("mUsersLock")
Bookatzf56f2582019-09-04 16:06:41 -07001301 private UserData getUserDataLU(@UserIdInt int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -08001302 final UserData userData = mUsers.get(userId);
1303 // If it is partial and not in the process of being removed, return as unknown user.
1304 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
1305 return null;
1306 }
1307 return userData;
Amith Yamasani195263742012-08-21 15:40:12 -07001308 }
1309
Fyodor Kupolov82402752015-10-28 14:54:51 -07001310 /**
1311 * Obtains {@link #mUsersLock} and return UserInfo from mUsers.
1312 * <p>No permissions checking or any addition checks are made</p>
1313 */
Bookatzf56f2582019-09-04 16:06:41 -07001314 private UserInfo getUserInfoNoChecks(@UserIdInt int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001315 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001316 final UserData userData = mUsers.get(userId);
1317 return userData != null ? userData.info : null;
1318 }
1319 }
1320
1321 /**
1322 * Obtains {@link #mUsersLock} and return UserData from mUsers.
1323 * <p>No permissions checking or any addition checks are made</p>
1324 */
Bookatzf56f2582019-09-04 16:06:41 -07001325 private UserData getUserDataNoChecks(@UserIdInt int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -08001326 synchronized (mUsersLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001327 return mUsers.get(userId);
1328 }
1329 }
1330
Amith Yamasani236b2b52015-08-18 14:32:14 -07001331 /** Called by PackageManagerService */
Bookatzf56f2582019-09-04 16:06:41 -07001332 public boolean exists(@UserIdInt int userId) {
Todd Kennedy0eb97382017-10-03 16:57:22 -07001333 return mLocalService.exists(userId);
Amith Yamasani13593602012-03-22 16:16:17 -07001334 }
1335
Amith Yamasani258848d2012-08-10 17:06:33 -07001336 @Override
Bookatzf56f2582019-09-04 16:06:41 -07001337 public void setUserName(@UserIdInt int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001338 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001339 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -07001340 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001341 UserData userData = getUserDataNoChecks(userId);
1342 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001343 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
1344 return;
1345 }
Amith Yamasani12747872015-12-07 14:19:49 -08001346 if (name != null && !name.equals(userData.info.name)) {
1347 userData.info.name = name;
1348 writeUserLP(userData);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001349 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -07001350 }
1351 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001352 if (changed) {
Bookatzf9368552019-03-14 11:57:09 -07001353 long ident = Binder.clearCallingIdentity();
1354 try {
1355 sendUserInfoChangedBroadcast(userId);
1356 } finally {
1357 Binder.restoreCallingIdentity(ident);
1358 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001359 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001360 }
1361
Amith Yamasani258848d2012-08-10 17:06:33 -07001362 @Override
Bookatzf56f2582019-09-04 16:06:41 -07001363 public void setUserIcon(@UserIdInt int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001364 checkManageUsersPermission("update users");
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01001365 if (hasUserRestriction(UserManager.DISALLOW_SET_USER_ICON, userId)) {
1366 Log.w(LOG_TAG, "Cannot set user icon. DISALLOW_SET_USER_ICON is enabled.");
1367 return;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001368 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01001369 mLocalService.setUserIcon(userId, bitmap);
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001370 }
1371
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01001372
1373
Bookatzf56f2582019-09-04 16:06:41 -07001374 private void sendUserInfoChangedBroadcast(@UserIdInt int userId) {
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001375 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
1376 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
1377 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -07001378 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001379 }
1380
Amith Yamasani258848d2012-08-10 17:06:33 -07001381 @Override
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001382 public ParcelFileDescriptor getUserIcon(int targetUserId) {
Bookatzcde3d922019-03-08 14:30:00 -08001383 if (!hasManageUsersOrPermission(android.Manifest.permission.GET_ACCOUNTS_PRIVILEGED)) {
1384 throw new SecurityException("You need MANAGE_USERS or GET_ACCOUNTS_PRIVILEGED "
1385 + "permissions to: get user icon");
1386 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001387 String iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001388 synchronized (mPackagesLock) {
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001389 UserInfo targetUserInfo = getUserInfoNoChecks(targetUserId);
1390 if (targetUserInfo == null || targetUserInfo.partial) {
1391 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + targetUserId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001392 return null;
1393 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001394
1395 final int callingUserId = UserHandle.getCallingUserId();
1396 final int callingGroupId = getUserInfoNoChecks(callingUserId).profileGroupId;
1397 final int targetGroupId = targetUserInfo.profileGroupId;
1398 final boolean sameGroup = (callingGroupId != UserInfo.NO_PROFILE_GROUP_ID
1399 && callingGroupId == targetGroupId);
1400 if ((callingUserId != targetUserId) && !sameGroup) {
Nicolas Prevot88cc3462014-05-14 14:51:48 +01001401 checkManageUsersPermission("get the icon of a user who is not related");
1402 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001403
1404 if (targetUserInfo.iconPath == null) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001405 return null;
1406 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001407 iconPath = targetUserInfo.iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001408 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001409
1410 try {
1411 return ParcelFileDescriptor.open(
1412 new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
1413 } catch (FileNotFoundException e) {
1414 Log.e(LOG_TAG, "Couldn't find icon file", e);
1415 }
1416 return null;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001417 }
1418
Bookatzf56f2582019-09-04 16:06:41 -07001419 public void makeInitialized(@UserIdInt int userId) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001420 checkManageUsersPermission("makeInitialized");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001421 boolean scheduleWriteUser = false;
Amith Yamasani12747872015-12-07 14:19:49 -08001422 UserData userData;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001423 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001424 userData = mUsers.get(userId);
1425 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001426 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001427 return;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001428 }
Amith Yamasani12747872015-12-07 14:19:49 -08001429 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1430 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001431 scheduleWriteUser = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001432 }
1433 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001434 if (scheduleWriteUser) {
Amith Yamasani12747872015-12-07 14:19:49 -08001435 scheduleWriteUser(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001436 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001437 }
1438
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001439 /**
1440 * If default guest restrictions haven't been initialized yet, add the basic
1441 * restrictions.
1442 */
1443 private void initDefaultGuestRestrictions() {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001444 synchronized (mGuestRestrictions) {
1445 if (mGuestRestrictions.isEmpty()) {
Samuel Tand9453b82016-03-14 15:57:02 -07001446 mGuestRestrictions.putBoolean(UserManager.DISALLOW_CONFIG_WIFI, true);
Fyodor Kupolove04462c2015-11-30 15:02:53 -08001447 mGuestRestrictions.putBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, true);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001448 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
1449 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
1450 }
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001451 }
1452 }
1453
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001454 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301455 public Bundle getDefaultGuestRestrictions() {
1456 checkManageUsersPermission("getDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001457 synchronized (mGuestRestrictions) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301458 return new Bundle(mGuestRestrictions);
1459 }
1460 }
1461
1462 @Override
1463 public void setDefaultGuestRestrictions(Bundle restrictions) {
1464 checkManageUsersPermission("setDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001465 synchronized (mGuestRestrictions) {
1466 mGuestRestrictions.clear();
1467 mGuestRestrictions.putAll(restrictions);
1468 }
1469 synchronized (mPackagesLock) {
1470 writeUserListLP();
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301471 }
1472 }
1473
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001474 /**
Pavel Grafov6a40f092016-10-25 15:46:51 +01001475 * See {@link UserManagerInternal#setDevicePolicyUserRestrictions}
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001476 */
Bookatzf56f2582019-09-04 16:06:41 -07001477 private void setDevicePolicyUserRestrictionsInner(@UserIdInt int userId,
1478 @Nullable Bundle restrictions, boolean isDeviceOwner, int cameraRestrictionScope) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001479 final Bundle global = new Bundle();
1480 final Bundle local = new Bundle();
1481
1482 // Sort restrictions into local and global ensuring they don't overlap.
1483 UserRestrictionsUtils.sortToGlobalAndLocal(restrictions, isDeviceOwner,
1484 cameraRestrictionScope, global, local);
1485
1486 boolean globalChanged, localChanged;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001487 synchronized (mRestrictionsLock) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001488 // Update global and local restrictions if they were changed.
1489 globalChanged = updateRestrictionsIfNeededLR(
1490 userId, global, mDevicePolicyGlobalUserRestrictions);
1491 localChanged = updateRestrictionsIfNeededLR(
1492 userId, local, mDevicePolicyLocalUserRestrictions);
1493
1494 if (isDeviceOwner) {
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001495 // Remember the global restriction owner userId to be able to make a distinction
1496 // in getUserRestrictionSource on who set local policies.
Pavel Grafov6a40f092016-10-25 15:46:51 +01001497 mDeviceOwnerUserId = userId;
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001498 } else {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001499 if (mDeviceOwnerUserId == userId) {
Zoltan Szatmary-Ban8a5536d2016-05-27 17:56:44 +01001500 // When profile owner sets restrictions it passes null global bundle and we
1501 // reset global restriction owner userId.
1502 // This means this user used to have DO, but now the DO is gone and the user
1503 // instead has PO.
Pavel Grafov6a40f092016-10-25 15:46:51 +01001504 mDeviceOwnerUserId = UserHandle.USER_NULL;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001505 }
1506 }
1507 }
1508 if (DBG) {
1509 Log.d(LOG_TAG, "setDevicePolicyUserRestrictions: userId=" + userId
1510 + " global=" + global + (globalChanged ? " (changed)" : "")
1511 + " local=" + local + (localChanged ? " (changed)" : "")
1512 );
1513 }
1514 // Don't call them within the mRestrictionsLock.
1515 synchronized (mPackagesLock) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001516 if (localChanged || globalChanged) {
Amith Yamasani12747872015-12-07 14:19:49 -08001517 writeUserLP(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001518 }
1519 }
1520
1521 synchronized (mRestrictionsLock) {
1522 if (globalChanged) {
1523 applyUserRestrictionsForAllUsersLR();
1524 } else if (localChanged) {
1525 applyUserRestrictionsLR(userId);
1526 }
1527 }
1528 }
1529
Pavel Grafov6a40f092016-10-25 15:46:51 +01001530 /**
1531 * Updates restriction bundle for a given user in a given restriction array. If new bundle is
1532 * empty, record is removed from the array.
1533 * @return whether restrictions bundle is different from the old one.
1534 */
Bookatzf56f2582019-09-04 16:06:41 -07001535 private boolean updateRestrictionsIfNeededLR(@UserIdInt int userId,
1536 @Nullable Bundle restrictions, SparseArray<Bundle> restrictionsArray) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001537 final boolean changed =
1538 !UserRestrictionsUtils.areEqual(restrictionsArray.get(userId), restrictions);
1539 if (changed) {
1540 if (!UserRestrictionsUtils.isEmpty(restrictions)) {
1541 restrictionsArray.put(userId, restrictions);
1542 } else {
1543 restrictionsArray.delete(userId);
1544 }
1545 }
1546 return changed;
1547 }
1548
Makoto Onuki068c54a2015-10-13 14:34:03 -07001549 @GuardedBy("mRestrictionsLock")
Bookatzf56f2582019-09-04 16:06:41 -07001550 private Bundle computeEffectiveUserRestrictionsLR(@UserIdInt int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001551 final Bundle baseRestrictions =
1552 UserRestrictionsUtils.nonNull(mBaseUserRestrictions.get(userId));
Pavel Grafov6a40f092016-10-25 15:46:51 +01001553 final Bundle global = UserRestrictionsUtils.mergeAll(mDevicePolicyGlobalUserRestrictions);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001554 final Bundle local = mDevicePolicyLocalUserRestrictions.get(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001555
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001556 if (UserRestrictionsUtils.isEmpty(global) && UserRestrictionsUtils.isEmpty(local)) {
1557 // Common case first.
1558 return baseRestrictions;
Makoto Onuki068c54a2015-10-13 14:34:03 -07001559 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001560 final Bundle effective = UserRestrictionsUtils.clone(baseRestrictions);
1561 UserRestrictionsUtils.merge(effective, global);
1562 UserRestrictionsUtils.merge(effective, local);
1563
Makoto Onuki068c54a2015-10-13 14:34:03 -07001564 return effective;
1565 }
1566
1567 @GuardedBy("mRestrictionsLock")
Bookatzf56f2582019-09-04 16:06:41 -07001568 private void invalidateEffectiveUserRestrictionsLR(@UserIdInt int userId) {
Makoto Onuki068c54a2015-10-13 14:34:03 -07001569 if (DBG) {
1570 Log.d(LOG_TAG, "invalidateEffectiveUserRestrictions userId=" + userId);
1571 }
1572 mCachedEffectiveUserRestrictions.remove(userId);
1573 }
1574
Bookatzf56f2582019-09-04 16:06:41 -07001575 private Bundle getEffectiveUserRestrictions(@UserIdInt int userId) {
Makoto Onuki068c54a2015-10-13 14:34:03 -07001576 synchronized (mRestrictionsLock) {
1577 Bundle restrictions = mCachedEffectiveUserRestrictions.get(userId);
1578 if (restrictions == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001579 restrictions = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001580 mCachedEffectiveUserRestrictions.put(userId, restrictions);
1581 }
1582 return restrictions;
Amith Yamasani8cd28b52014-06-08 17:54:27 -07001583 }
1584 }
1585
Makoto Onuki068c54a2015-10-13 14:34:03 -07001586 /** @return a specific user restriction that's in effect currently. */
1587 @Override
Bookatzf56f2582019-09-04 16:06:41 -07001588 public boolean hasUserRestriction(String restrictionKey, @UserIdInt int userId) {
Patrick Baumann2f2fd712019-07-31 15:18:53 -07001589 return mLocalService.hasUserRestriction(restrictionKey, userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001590 }
1591
Makoto Onukiacc50462018-02-14 14:13:49 -08001592 /** @return if any user has the given restriction. */
1593 @Override
1594 public boolean hasUserRestrictionOnAnyUser(String restrictionKey) {
1595 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1596 return false;
1597 }
1598 final List<UserInfo> users = getUsers(/* excludeDying= */ true);
1599 for (int i = 0; i < users.size(); i++) {
1600 final int userId = users.get(i).id;
1601 Bundle restrictions = getEffectiveUserRestrictions(userId);
1602 if (restrictions != null && restrictions.getBoolean(restrictionKey)) {
1603 return true;
1604 }
1605 }
1606 return false;
1607 }
1608
Makoto Onuki068c54a2015-10-13 14:34:03 -07001609 /**
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001610 * @hide
1611 *
1612 * Returns who set a user restriction on a user.
1613 * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
1614 * @param restrictionKey the string key representing the restriction
1615 * @param userId the id of the user for whom to retrieve the restrictions.
1616 * @return The source of user restriction. Any combination of
1617 * {@link UserManager#RESTRICTION_NOT_SET},
1618 * {@link UserManager#RESTRICTION_SOURCE_SYSTEM},
1619 * {@link UserManager#RESTRICTION_SOURCE_DEVICE_OWNER}
1620 * and {@link UserManager#RESTRICTION_SOURCE_PROFILE_OWNER}
1621 */
1622 @Override
Bookatzf56f2582019-09-04 16:06:41 -07001623 public int getUserRestrictionSource(String restrictionKey, @UserIdInt int userId) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001624 List<EnforcingUser> enforcingUsers = getUserRestrictionSources(restrictionKey, userId);
1625 // Get "bitwise or" of restriction sources for all enforcing users.
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001626 int result = UserManager.RESTRICTION_NOT_SET;
Pavel Grafov6a40f092016-10-25 15:46:51 +01001627 for (int i = enforcingUsers.size() - 1; i >= 0; i--) {
1628 result |= enforcingUsers.get(i).getUserRestrictionSource();
1629 }
1630 return result;
1631 }
1632
1633 @Override
1634 public List<EnforcingUser> getUserRestrictionSources(
1635 String restrictionKey, @UserIdInt int userId) {
1636 checkManageUsersPermission("getUserRestrictionSource");
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001637
1638 // Shortcut for the most common case
1639 if (!hasUserRestriction(restrictionKey, userId)) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001640 return Collections.emptyList();
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001641 }
1642
Pavel Grafov6a40f092016-10-25 15:46:51 +01001643 final List<EnforcingUser> result = new ArrayList<>();
1644
1645 // Check if it is base restriction.
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001646 if (hasBaseUserRestriction(restrictionKey, userId)) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001647 result.add(new EnforcingUser(
1648 UserHandle.USER_NULL, UserManager.RESTRICTION_SOURCE_SYSTEM));
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001649 }
1650
Pavel Grafov6a40f092016-10-25 15:46:51 +01001651 synchronized (mRestrictionsLock) {
1652 // Check if it is set by profile owner.
1653 Bundle profileOwnerRestrictions = mDevicePolicyLocalUserRestrictions.get(userId);
1654 if (UserRestrictionsUtils.contains(profileOwnerRestrictions, restrictionKey)) {
1655 result.add(getEnforcingUserLocked(userId));
1656 }
1657
1658 // Iterate over all users who enforce global restrictions.
1659 for (int i = mDevicePolicyGlobalUserRestrictions.size() - 1; i >= 0; i--) {
1660 Bundle globalRestrictions = mDevicePolicyGlobalUserRestrictions.valueAt(i);
1661 int profileUserId = mDevicePolicyGlobalUserRestrictions.keyAt(i);
1662 if (UserRestrictionsUtils.contains(globalRestrictions, restrictionKey)) {
1663 result.add(getEnforcingUserLocked(profileUserId));
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001664 }
1665 }
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001666 }
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001667 return result;
1668 }
1669
Andreas Gampea36dc622018-02-05 17:19:22 -08001670 @GuardedBy("mRestrictionsLock")
Pavel Grafov6a40f092016-10-25 15:46:51 +01001671 private EnforcingUser getEnforcingUserLocked(@UserIdInt int userId) {
1672 int source = mDeviceOwnerUserId == userId ? UserManager.RESTRICTION_SOURCE_DEVICE_OWNER
1673 : UserManager.RESTRICTION_SOURCE_PROFILE_OWNER;
1674 return new EnforcingUser(userId, source);
1675 }
1676
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001677 /**
Makoto Onuki068c54a2015-10-13 14:34:03 -07001678 * @return UserRestrictions that are in effect currently. This always returns a new
1679 * {@link Bundle}.
1680 */
Amith Yamasani8cd28b52014-06-08 17:54:27 -07001681 @Override
Bookatzf56f2582019-09-04 16:06:41 -07001682 public Bundle getUserRestrictions(@UserIdInt int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001683 return UserRestrictionsUtils.clone(getEffectiveUserRestrictions(userId));
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001684 }
1685
1686 @Override
Bookatzf56f2582019-09-04 16:06:41 -07001687 public boolean hasBaseUserRestriction(String restrictionKey, @UserIdInt int userId) {
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +00001688 checkManageUsersPermission("hasBaseUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001689 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1690 return false;
1691 }
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +00001692 synchronized (mRestrictionsLock) {
1693 Bundle bundle = mBaseUserRestrictions.get(userId);
1694 return (bundle != null && bundle.getBoolean(restrictionKey, false));
1695 }
1696 }
1697
1698 @Override
Bookatzf56f2582019-09-04 16:06:41 -07001699 public void setUserRestriction(String key, boolean value, @UserIdInt int userId) {
Fyodor Kupolovd4b26042015-07-27 14:30:59 -07001700 checkManageUsersPermission("setUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001701 if (!UserRestrictionsUtils.isValidRestriction(key)) {
1702 return;
1703 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001704 synchronized (mRestrictionsLock) {
1705 // Note we can't modify Bundles stored in mBaseUserRestrictions directly, so create
1706 // a copy.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001707 final Bundle newRestrictions = UserRestrictionsUtils.clone(
1708 mBaseUserRestrictions.get(userId));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001709 newRestrictions.putBoolean(key, value);
1710
Fyodor Kupolov82402752015-10-28 14:54:51 -07001711 updateUserRestrictionsInternalLR(newRestrictions, userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001712 }
1713 }
1714
Makoto Onuki068c54a2015-10-13 14:34:03 -07001715 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001716 * Optionally updating user restrictions, calculate the effective user restrictions and also
1717 * propagate to other services and system settings.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001718 *
Pavel Grafov6a40f092016-10-25 15:46:51 +01001719 * @param newBaseRestrictions User restrictions to set.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001720 * If null, will not update user restrictions and only does the propagation.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001721 * @param userId target user ID.
1722 */
1723 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001724 private void updateUserRestrictionsInternalLR(
Bookatzf56f2582019-09-04 16:06:41 -07001725 @Nullable Bundle newBaseRestrictions, @UserIdInt int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001726 final Bundle prevAppliedRestrictions = UserRestrictionsUtils.nonNull(
1727 mAppliedUserRestrictions.get(userId));
1728
1729 // Update base restrictions.
Pavel Grafov6a40f092016-10-25 15:46:51 +01001730 if (newBaseRestrictions != null) {
1731 // If newBaseRestrictions == the current one, it's probably a bug.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001732 final Bundle prevBaseRestrictions = mBaseUserRestrictions.get(userId);
1733
Pavel Grafov6a40f092016-10-25 15:46:51 +01001734 Preconditions.checkState(prevBaseRestrictions != newBaseRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001735 Preconditions.checkState(mCachedEffectiveUserRestrictions.get(userId)
Pavel Grafov6a40f092016-10-25 15:46:51 +01001736 != newBaseRestrictions);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001737
Pavel Grafov6a40f092016-10-25 15:46:51 +01001738 if (updateRestrictionsIfNeededLR(userId, newBaseRestrictions, mBaseUserRestrictions)) {
Amith Yamasani12747872015-12-07 14:19:49 -08001739 scheduleWriteUser(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001740 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001741 }
1742
Fyodor Kupolov82402752015-10-28 14:54:51 -07001743 final Bundle effective = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001744
Makoto Onuki759a7632015-10-28 16:43:10 -07001745 mCachedEffectiveUserRestrictions.put(userId, effective);
1746
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001747 // Apply the new restrictions.
Makoto Onuki4f160732015-10-27 17:15:38 -07001748 if (DBG) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001749 debug("Applying user restrictions: userId=" + userId
1750 + " new=" + effective + " prev=" + prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001751 }
1752
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001753 if (mAppOpsService != null) { // We skip it until system-ready.
Fyodor Kupolovec30ca32016-06-16 15:09:29 -07001754 mHandler.post(new Runnable() {
1755 @Override
1756 public void run() {
1757 try {
1758 mAppOpsService.setUserRestrictions(effective, mUserRestriconToken, userId);
1759 } catch (RemoteException e) {
1760 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
1761 }
1762 }
1763 });
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001764 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001765
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001766 propagateUserRestrictionsLR(userId, effective, prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001767
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001768 mAppliedUserRestrictions.put(userId, new Bundle(effective));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001769 }
1770
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001771 private void propagateUserRestrictionsLR(final int userId,
Makoto Onukid45a4a22015-11-02 17:17:38 -08001772 Bundle newRestrictions, Bundle prevRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001773 // Note this method doesn't touch any state, meaning it doesn't require mRestrictionsLock
1774 // actually, but we still need some kind of synchronization otherwise we might end up
1775 // calling listeners out-of-order, thus "LR".
1776
1777 if (UserRestrictionsUtils.areEqual(newRestrictions, prevRestrictions)) {
1778 return;
1779 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08001780
1781 final Bundle newRestrictionsFinal = new Bundle(newRestrictions);
1782 final Bundle prevRestrictionsFinal = new Bundle(prevRestrictions);
1783
1784 mHandler.post(new Runnable() {
1785 @Override
1786 public void run() {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07001787 UserRestrictionsUtils.applyUserRestrictions(
1788 mContext, userId, newRestrictionsFinal, prevRestrictionsFinal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001789
Makoto Onukid45a4a22015-11-02 17:17:38 -08001790 final UserRestrictionsListener[] listeners;
1791 synchronized (mUserRestrictionsListeners) {
1792 listeners = new UserRestrictionsListener[mUserRestrictionsListeners.size()];
1793 mUserRestrictionsListeners.toArray(listeners);
1794 }
1795 for (int i = 0; i < listeners.length; i++) {
1796 listeners[i].onUserRestrictionsChanged(userId,
1797 newRestrictionsFinal, prevRestrictionsFinal);
1798 }
Makoto Onukie72f81b2017-03-16 14:08:19 -07001799
1800 final Intent broadcast = new Intent(UserManager.ACTION_USER_RESTRICTIONS_CHANGED)
1801 .setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
1802 mContext.sendBroadcastAsUser(broadcast, UserHandle.of(userId));
Makoto Onukid45a4a22015-11-02 17:17:38 -08001803 }
1804 });
1805 }
1806
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001807 // Package private for the inner class.
Andreas Gampe2e8c7672018-07-20 13:01:08 -07001808 @GuardedBy("mRestrictionsLock")
Bookatzf56f2582019-09-04 16:06:41 -07001809 void applyUserRestrictionsLR(@UserIdInt int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001810 updateUserRestrictionsInternalLR(null, userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001811 }
1812
1813 @GuardedBy("mRestrictionsLock")
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001814 // Package private for the inner class.
1815 void applyUserRestrictionsForAllUsersLR() {
1816 if (DBG) {
1817 debug("applyUserRestrictionsForAllUsersLR");
1818 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001819 // First, invalidate all cached values.
Makoto Onuki4f160732015-10-27 17:15:38 -07001820 mCachedEffectiveUserRestrictions.clear();
1821
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001822 // We don't want to call into ActivityManagerService while taking a lock, so we'll call
Makoto Onuki068c54a2015-10-13 14:34:03 -07001823 // it on a handler.
1824 final Runnable r = new Runnable() {
1825 @Override
1826 public void run() {
1827 // Then get the list of running users.
1828 final int[] runningUsers;
1829 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001830 runningUsers = ActivityManager.getService().getRunningUserIds();
Makoto Onuki068c54a2015-10-13 14:34:03 -07001831 } catch (RemoteException e) {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001832 Log.w(LOG_TAG, "Unable to access ActivityManagerService");
Makoto Onuki068c54a2015-10-13 14:34:03 -07001833 return;
1834 }
1835 // Then re-calculate the effective restrictions and apply, only for running users.
1836 // It's okay if a new user has started after the getRunningUserIds() call,
1837 // because we'll do the same thing (re-calculate the restrictions and apply)
1838 // when we start a user.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001839 synchronized (mRestrictionsLock) {
1840 for (int i = 0; i < runningUsers.length; i++) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001841 applyUserRestrictionsLR(runningUsers[i]);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001842 }
1843 }
1844 }
1845 };
1846 mHandler.post(r);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001847 }
1848
Amith Yamasani258848d2012-08-10 17:06:33 -07001849 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001850 * Check if we've hit the limit of how many users can be created.
1851 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001852 private boolean isUserLimitReached() {
1853 int count;
1854 synchronized (mUsersLock) {
1855 count = getAliveUsersExcludingGuestsCountLU();
1856 }
1857 return count >= UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001858 }
1859
1860 @Override
Bookatzf56f2582019-09-04 16:06:41 -07001861 public boolean canAddMoreManagedProfiles(@UserIdInt int userId, boolean allowedToRemoveOne) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001862 checkManageUsersPermission("check if more managed profiles can be added.");
1863 if (ActivityManager.isLowRamDeviceStatic()) {
1864 return false;
1865 }
Fyodor Kupolovb6157992015-06-05 15:32:28 -07001866 if (!mContext.getPackageManager().hasSystemFeature(
1867 PackageManager.FEATURE_MANAGED_USERS)) {
1868 return false;
1869 }
Nicolas Prevotb8186812015-08-06 15:00:03 +01001870 // Limit number of managed profiles that can be created
Benjamin Franzc8776152017-01-06 14:16:41 +00001871 final int managedProfilesCount = getProfiles(userId, false).size() - 1;
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001872 final int profilesRemovedCount = managedProfilesCount > 0 && allowedToRemoveOne ? 1 : 0;
Kenny Guy02c89902016-11-15 19:36:38 +00001873 if (managedProfilesCount - profilesRemovedCount >= getMaxManagedProfiles()) {
Nicolas Prevotb8186812015-08-06 15:00:03 +01001874 return false;
1875 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001876 synchronized(mUsersLock) {
1877 UserInfo userInfo = getUserInfoLU(userId);
yuanhao47f9f7c2017-01-18 09:54:45 +08001878 if (userInfo == null || !userInfo.canHaveProfile()) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001879 return false;
1880 }
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001881 int usersCountAfterRemoving = getAliveUsersExcludingGuestsCountLU()
1882 - profilesRemovedCount;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001883 // We allow creating a managed profile in the special case where there is only one user.
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001884 return usersCountAfterRemoving == 1
1885 || usersCountAfterRemoving < UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001886 }
1887 }
1888
Andreas Gampe2e8c7672018-07-20 13:01:08 -07001889 @GuardedBy("mUsersLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001890 private int getAliveUsersExcludingGuestsCountLU() {
Amith Yamasanif584f012014-05-19 17:57:25 -07001891 int aliveUserCount = 0;
1892 final int totalUserCount = mUsers.size();
1893 // Skip over users being removed
1894 for (int i = 0; i < totalUserCount; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001895 UserInfo user = mUsers.valueAt(i).info;
Felipe Lemec1ca4412019-09-11 09:23:26 -07001896 if (!mRemovingUserIds.get(user.id) && !user.isGuest() && !user.preCreated) {
Amith Yamasanif584f012014-05-19 17:57:25 -07001897 aliveUserCount++;
1898 }
1899 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001900 return aliveUserCount;
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001901 }
1902
1903 /**
Amith Yamasani195263742012-08-21 15:40:12 -07001904 * Enforces that only the system UID or root's UID or apps that have the
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001905 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} and
1906 * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL INTERACT_ACROSS_USERS_FULL}
1907 * permissions can make certain calls to the UserManager.
1908 *
1909 * @param message used as message if SecurityException is thrown
1910 * @throws SecurityException if the caller does not have enough privilege.
1911 */
1912 private static final void checkManageUserAndAcrossUsersFullPermission(String message) {
1913 final int uid = Binder.getCallingUid();
jovanakf24ad492018-05-18 12:15:59 -07001914
1915 if (uid == Process.SYSTEM_UID || uid == 0) {
1916 // System UID or root's UID are granted privilege.
1917 return;
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001918 }
jovanakf24ad492018-05-18 12:15:59 -07001919
1920 if (hasPermissionGranted(Manifest.permission.MANAGE_USERS, uid)
1921 && hasPermissionGranted(Manifest.permission.INTERACT_ACROSS_USERS_FULL, uid)) {
1922 // Apps with both permissions are granted privilege.
1923 return;
1924 }
1925
1926 throw new SecurityException(
1927 "You need MANAGE_USERS and INTERACT_ACROSS_USERS_FULL permission to: " + message);
1928 }
1929
1930 private static boolean hasPermissionGranted(String permission, int uid) {
1931 return ActivityManager.checkComponentPermission(
1932 permission, uid, /* owningUid = */-1, /* exported = */ true) ==
1933 PackageManager.PERMISSION_GRANTED;
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001934 }
1935
1936 /**
1937 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001938 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -07001939 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -07001940 *
1941 * @param message used as message if SecurityException is thrown
1942 * @throws SecurityException if the caller is not system or root
Tony Mak4dc008c2016-03-16 10:46:49 +00001943 * @see #hasManageUsersPermission()
Amith Yamasani258848d2012-08-10 17:06:33 -07001944 */
Amith Yamasanibe465322014-04-24 13:45:17 -07001945 private static final void checkManageUsersPermission(String message) {
Tony Mak4dc008c2016-03-16 10:46:49 +00001946 if (!hasManageUsersPermission()) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001947 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
1948 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -04001949 }
1950
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001951 /**
Sudheer Shankaf5cea032016-06-08 17:13:24 -07001952 * Enforces that only the system UID or root's UID or apps that have the
1953 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or
1954 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS}
1955 * can make certain calls to the UserManager.
1956 *
1957 * @param message used as message if SecurityException is thrown
1958 * @throws SecurityException if the caller is not system or root
1959 * @see #hasManageOrCreateUsersPermission()
1960 */
1961 private static final void checkManageOrCreateUsersPermission(String message) {
1962 if (!hasManageOrCreateUsersPermission()) {
1963 throw new SecurityException(
1964 "You either need MANAGE_USERS or CREATE_USERS permission to: " + message);
1965 }
1966 }
1967
1968 /**
1969 * Similar to {@link #checkManageOrCreateUsersPermission(String)} but when the caller is tries
1970 * to create user/profiles other than what is allowed for
1971 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS} permission, then it will only
1972 * allow callers with {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} permission.
1973 */
1974 private static final void checkManageOrCreateUsersPermission(int creationFlags) {
1975 if ((creationFlags & ~ALLOWED_FLAGS_FOR_CREATE_USERS_PERMISSION) == 0) {
1976 if (!hasManageOrCreateUsersPermission()) {
1977 throw new SecurityException("You either need MANAGE_USERS or CREATE_USERS "
1978 + "permission to create an user with flags: " + creationFlags);
1979 }
1980 } else if (!hasManageUsersPermission()) {
1981 throw new SecurityException("You need MANAGE_USERS permission to create an user "
1982 + " with flags: " + creationFlags);
1983 }
1984 }
1985
1986 /**
Tony Mak4dc008c2016-03-16 10:46:49 +00001987 * @return whether the calling UID is system UID or root's UID or the calling app has the
1988 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}.
1989 */
1990 private static final boolean hasManageUsersPermission() {
1991 final int callingUid = Binder.getCallingUid();
1992 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
1993 || callingUid == Process.ROOT_UID
jovanakf24ad492018-05-18 12:15:59 -07001994 || hasPermissionGranted(android.Manifest.permission.MANAGE_USERS, callingUid);
Tony Mak4dc008c2016-03-16 10:46:49 +00001995 }
1996
1997 /**
Sudheer Shankaf5cea032016-06-08 17:13:24 -07001998 * @return whether the calling UID is system UID or root's UID or the calling app has the
Bookatzcde3d922019-03-08 14:30:00 -08001999 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or the provided permission.
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002000 */
Bookatzcde3d922019-03-08 14:30:00 -08002001 private static final boolean hasManageUsersOrPermission(String alternativePermission) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002002 final int callingUid = Binder.getCallingUid();
2003 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
2004 || callingUid == Process.ROOT_UID
jovanakf24ad492018-05-18 12:15:59 -07002005 || hasPermissionGranted(android.Manifest.permission.MANAGE_USERS, callingUid)
Bookatzcde3d922019-03-08 14:30:00 -08002006 || hasPermissionGranted(alternativePermission, callingUid);
2007 }
2008
2009 /**
2010 * @return whether the calling UID is system UID or root's UID or the calling app has the
2011 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or
2012 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS}.
2013 */
2014 private static final boolean hasManageOrCreateUsersPermission() {
2015 return hasManageUsersOrPermission(android.Manifest.permission.CREATE_USERS);
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002016 }
2017
2018 /**
Esteban Talavera5b9f1672015-12-11 15:22:34 +00002019 * Enforces that only the system UID or root's UID (on any user) can make certain calls to the
2020 * UserManager.
2021 *
2022 * @param message used as message if SecurityException is thrown
2023 * @throws SecurityException if the caller is not system or root
2024 */
2025 private static void checkSystemOrRoot(String message) {
2026 final int uid = Binder.getCallingUid();
2027 if (!UserHandle.isSameApp(uid, Process.SYSTEM_UID) && uid != Process.ROOT_UID) {
2028 throw new SecurityException("Only system may: " + message);
2029 }
2030 }
2031
Fyodor Kupolov82402752015-10-28 14:54:51 -07002032 private void writeBitmapLP(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002033 try {
2034 File dir = new File(mUsersDir, Integer.toString(info.id));
2035 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +01002036 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002037 if (!dir.exists()) {
2038 dir.mkdir();
2039 FileUtils.setPermissions(
2040 dir.getPath(),
2041 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
2042 -1, -1);
2043 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07002044 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +01002045 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01002046 && tmp.renameTo(file) && SELinux.restorecon(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -07002047 info.iconPath = file.getAbsolutePath();
2048 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07002049 try {
2050 os.close();
2051 } catch (IOException ioe) {
2052 // What the ... !
2053 }
Adrian Roos1bdff912015-02-17 15:51:35 +01002054 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002055 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002056 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002057 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002058 }
2059
Amith Yamasani0b285492011-04-14 17:35:23 -07002060 /**
2061 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
2062 * cache it elsewhere.
2063 * @return the array of user ids.
2064 */
Dianne Hackborn1676c852012-09-10 14:52:30 -07002065 public int[] getUserIds() {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002066 synchronized (mUsersLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07002067 return mUserIds;
2068 }
Amith Yamasani0b285492011-04-14 17:35:23 -07002069 }
2070
Andreas Gampe2e8c7672018-07-20 13:01:08 -07002071 @GuardedBy({"mRestrictionsLock", "mPackagesLock"})
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002072 private void readUserListLP() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002073 if (!mUserListFile.exists()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002074 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002075 return;
2076 }
2077 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07002078 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002079 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07002080 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002081 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002082 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002083 int type;
2084 while ((type = parser.next()) != XmlPullParser.START_TAG
2085 && type != XmlPullParser.END_DOCUMENT) {
Amith Yamasani12747872015-12-07 14:19:49 -08002086 // Skip
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002087 }
2088
2089 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07002090 Slog.e(LOG_TAG, "Unable to read user list");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002091 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002092 return;
2093 }
2094
Amith Yamasani2a003292012-08-14 18:25:45 -07002095 mNextSerialNumber = -1;
2096 if (parser.getName().equals(TAG_USERS)) {
2097 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
2098 if (lastSerialNumber != null) {
2099 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
2100 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07002101 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
2102 if (versionNumber != null) {
2103 mUserVersion = Integer.parseInt(versionNumber);
2104 }
Amith Yamasani2a003292012-08-14 18:25:45 -07002105 }
2106
Pavel Grafov6a40f092016-10-25 15:46:51 +01002107 // Pre-O global user restriction were stored as a single bundle (as opposed to per-user
2108 // currently), take care of it in case of upgrade.
2109 Bundle oldDevicePolicyGlobalUserRestrictions = null;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002110
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002111 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05302112 if (type == XmlPullParser.START_TAG) {
2113 final String name = parser.getName();
2114 if (name.equals(TAG_USER)) {
2115 String id = parser.getAttributeValue(null, ATTR_ID);
Amith Yamasani6f34b412012-10-22 18:19:27 -07002116
Amith Yamasani12747872015-12-07 14:19:49 -08002117 UserData userData = readUserLP(Integer.parseInt(id));
2118
2119 if (userData != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002120 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002121 mUsers.put(userData.info.id, userData);
2122 if (mNextSerialNumber < 0
2123 || mNextSerialNumber <= userData.info.id) {
2124 mNextSerialNumber = userData.info.id + 1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002125 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05302126 }
Amith Yamasani2a003292012-08-14 18:25:45 -07002127 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05302128 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -08002129 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2130 && type != XmlPullParser.END_TAG) {
2131 if (type == XmlPullParser.START_TAG) {
2132 if (parser.getName().equals(TAG_RESTRICTIONS)) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002133 synchronized (mGuestRestrictions) {
Fyodor Kupoloveafee022017-03-15 17:09:04 -07002134 UserRestrictionsUtils
2135 .readRestrictions(parser, mGuestRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002136 }
Amith Yamasanida0b1682014-11-21 12:58:17 -08002137 }
2138 break;
2139 }
2140 }
Pavel Grafov6a40f092016-10-25 15:46:51 +01002141 } else if (name.equals(TAG_DEVICE_OWNER_USER_ID)
2142 // Legacy name, should only be encountered when upgrading from pre-O.
2143 || name.equals(TAG_GLOBAL_RESTRICTION_OWNER_ID)) {
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01002144 String ownerUserId = parser.getAttributeValue(null, ATTR_ID);
2145 if (ownerUserId != null) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01002146 mDeviceOwnerUserId = Integer.parseInt(ownerUserId);
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01002147 }
Pavel Grafov6a40f092016-10-25 15:46:51 +01002148 } else if (name.equals(TAG_DEVICE_POLICY_RESTRICTIONS)) {
2149 // Should only happen when upgrading from pre-O (version < 7).
2150 oldDevicePolicyGlobalUserRestrictions =
2151 UserRestrictionsUtils.readRestrictions(parser);
Amith Yamasani258848d2012-08-10 17:06:33 -07002152 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002153 }
2154 }
Pavel Grafov6a40f092016-10-25 15:46:51 +01002155
Fyodor Kupolov82402752015-10-28 14:54:51 -07002156 updateUserIds();
Pavel Grafov6a40f092016-10-25 15:46:51 +01002157 upgradeIfNecessaryLP(oldDevicePolicyGlobalUserRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002158 } catch (IOException | XmlPullParserException e) {
2159 fallbackToSingleUserLP();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08002160 } finally {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002161 IoUtils.closeQuietly(fis);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002162 }
2163 }
2164
Amith Yamasani6f34b412012-10-22 18:19:27 -07002165 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -08002166 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Pavel Grafov6a40f092016-10-25 15:46:51 +01002167 * @param oldGlobalUserRestrictions Pre-O global device policy restrictions.
Amith Yamasani6f34b412012-10-22 18:19:27 -07002168 */
Andreas Gampe2e8c7672018-07-20 13:01:08 -07002169 @GuardedBy({"mRestrictionsLock", "mPackagesLock"})
Pavel Grafov6a40f092016-10-25 15:46:51 +01002170 private void upgradeIfNecessaryLP(Bundle oldGlobalUserRestrictions) {
Bookatz75f0a072019-08-05 14:12:16 -07002171 Set<Integer> userIdsToWrite = new ArraySet<>();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002172 final int originalVersion = mUserVersion;
Amith Yamasani6f34b412012-10-22 18:19:27 -07002173 int userVersion = mUserVersion;
2174 if (userVersion < 1) {
2175 // Assign a proper name for the owner, if not initialized correctly before
Amith Yamasani12747872015-12-07 14:19:49 -08002176 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
2177 if ("Primary".equals(userData.info.name)) {
2178 userData.info.name =
2179 mContext.getResources().getString(com.android.internal.R.string.owner_name);
Bookatz75f0a072019-08-05 14:12:16 -07002180 userIdsToWrite.add(userData.info.id);
Amith Yamasani6f34b412012-10-22 18:19:27 -07002181 }
2182 userVersion = 1;
2183 }
2184
Amith Yamasanibc9625052012-11-15 14:39:18 -08002185 if (userVersion < 2) {
2186 // Owner should be marked as initialized
Amith Yamasani12747872015-12-07 14:19:49 -08002187 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
2188 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
2189 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
Bookatz75f0a072019-08-05 14:12:16 -07002190 userIdsToWrite.add(userData.info.id);
Amith Yamasanibc9625052012-11-15 14:39:18 -08002191 }
2192 userVersion = 2;
2193 }
2194
Amith Yamasani350962c2013-08-06 11:18:53 -07002195
Amith Yamasani5e486f52013-08-07 11:06:44 -07002196 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -07002197 userVersion = 4;
2198 }
2199
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07002200 if (userVersion < 5) {
2201 initDefaultGuestRestrictions();
2202 userVersion = 5;
2203 }
2204
Fyodor Kupolov1c363152015-09-02 13:27:21 -07002205 if (userVersion < 6) {
2206 final boolean splitSystemUser = UserManager.isSplitSystemUser();
Fyodor Kupolov82402752015-10-28 14:54:51 -07002207 synchronized (mUsersLock) {
2208 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002209 UserData userData = mUsers.valueAt(i);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002210 // In non-split mode, only user 0 can have restricted profiles
Amith Yamasani12747872015-12-07 14:19:49 -08002211 if (!splitSystemUser && userData.info.isRestricted()
2212 && (userData.info.restrictedProfileParentId
2213 == UserInfo.NO_PROFILE_GROUP_ID)) {
2214 userData.info.restrictedProfileParentId = UserHandle.USER_SYSTEM;
Bookatz75f0a072019-08-05 14:12:16 -07002215 userIdsToWrite.add(userData.info.id);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002216 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07002217 }
2218 }
2219 userVersion = 6;
2220 }
2221
Pavel Grafov6a40f092016-10-25 15:46:51 +01002222 if (userVersion < 7) {
2223 // Previously only one user could enforce global restrictions, now it is per-user.
2224 synchronized (mRestrictionsLock) {
2225 if (!UserRestrictionsUtils.isEmpty(oldGlobalUserRestrictions)
2226 && mDeviceOwnerUserId != UserHandle.USER_NULL) {
2227 mDevicePolicyGlobalUserRestrictions.put(
2228 mDeviceOwnerUserId, oldGlobalUserRestrictions);
2229 }
2230 // ENSURE_VERIFY_APPS is now enforced globally even if put by profile owner, so move
2231 // it from local to global bundle for all users who set it.
2232 UserRestrictionsUtils.moveRestriction(UserManager.ENSURE_VERIFY_APPS,
2233 mDevicePolicyLocalUserRestrictions, mDevicePolicyGlobalUserRestrictions
2234 );
2235 }
2236 userVersion = 7;
2237 }
2238
Bookatz75f0a072019-08-05 14:12:16 -07002239 if (userVersion < 8) {
2240 // Added FLAG_FULL and FLAG_SYSTEM flags.
2241 synchronized (mUsersLock) {
2242 UserData userData = mUsers.get(UserHandle.USER_SYSTEM);
2243 userData.info.flags |= UserInfo.FLAG_SYSTEM;
2244 if (!UserManager.isHeadlessSystemUserMode()) {
2245 userData.info.flags |= UserInfo.FLAG_FULL;
2246 }
2247 userIdsToWrite.add(userData.info.id);
2248
2249 // Mark FULL all non-profile users except USER_SYSTEM.
2250 // Start index at 1 since USER_SYSTEM is the smallest userId and we're skipping it.
2251 for (int i = 1; i < mUsers.size(); i++) {
2252 userData = mUsers.valueAt(i);
2253 if ((userData.info.flags & UserInfo.FLAG_MANAGED_PROFILE) == 0) {
2254 userData.info.flags |= UserInfo.FLAG_FULL;
2255 userIdsToWrite.add(userData.info.id);
2256 }
2257 }
2258 }
2259 userVersion = 8;
2260 }
2261
Amith Yamasani6f34b412012-10-22 18:19:27 -07002262 if (userVersion < USER_VERSION) {
2263 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
2264 + USER_VERSION);
2265 } else {
2266 mUserVersion = userVersion;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002267
2268 if (originalVersion < mUserVersion) {
Bookatz75f0a072019-08-05 14:12:16 -07002269 for (int userId : userIdsToWrite) {
2270 UserData userData = getUserDataNoChecks(userId);
2271 if (userData != null) {
2272 writeUserLP(userData);
2273 }
2274 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002275 writeUserListLP();
2276 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07002277 }
2278 }
2279
Andreas Gampe2e8c7672018-07-20 13:01:08 -07002280 @GuardedBy({"mPackagesLock", "mRestrictionsLock"})
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002281 private void fallbackToSingleUserLP() {
Ying Zheng215116f2019-09-11 12:50:09 -07002282 int flags = UserInfo.FLAG_SYSTEM | UserInfo.FLAG_INITIALIZED | UserInfo.FLAG_ADMIN
2283 | UserInfo.FLAG_PRIMARY;
2284 // In headless system user mode, headless system user is not a full user.
Bookatz75f0a072019-08-05 14:12:16 -07002285 if (!UserManager.isHeadlessSystemUserMode()) {
Ying Zheng215116f2019-09-11 12:50:09 -07002286 flags |= UserInfo.FLAG_FULL;
Bookatz75f0a072019-08-05 14:12:16 -07002287 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -07002288 // Create the system user
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07002289 UserInfo system = new UserInfo(UserHandle.USER_SYSTEM, null, null, flags);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002290 UserData userData = putUserInfo(system);
Amith Yamasani634cf312012-10-04 17:34:21 -07002291 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -04002292 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -08002293
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05002294 Bundle restrictions = new Bundle();
Mahaver Chopra3d9805d2016-07-07 16:25:05 +01002295 try {
2296 final String[] defaultFirstUserRestrictions = mContext.getResources().getStringArray(
2297 com.android.internal.R.array.config_defaultFirstUserRestrictions);
2298 for (String userRestriction : defaultFirstUserRestrictions) {
2299 if (UserRestrictionsUtils.isValidRestriction(userRestriction)) {
2300 restrictions.putBoolean(userRestriction, true);
2301 }
2302 }
2303 } catch (Resources.NotFoundException e) {
2304 Log.e(LOG_TAG, "Couldn't find resource: config_defaultFirstUserRestrictions", e);
2305 }
2306
Pavel Grafov6a40f092016-10-25 15:46:51 +01002307 if (!restrictions.isEmpty()) {
2308 synchronized (mRestrictionsLock) {
2309 mBaseUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions);
2310 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07002311 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08002312
Fyodor Kupolov82402752015-10-28 14:54:51 -07002313 updateUserIds();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07002314 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002315
Amith Yamasani12747872015-12-07 14:19:49 -08002316 writeUserLP(userData);
Jeff Sharkeycd575992016-03-29 14:12:49 -06002317 writeUserListLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002318 }
2319
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07002320 private String getOwnerName() {
2321 return mContext.getResources().getString(com.android.internal.R.string.owner_name);
2322 }
2323
Bookatz75f0a072019-08-05 14:12:16 -07002324 private void scheduleWriteUser(UserData userData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002325 if (DBG) {
2326 debug("scheduleWriteUser");
2327 }
Makoto Onuki9e935a32015-11-06 14:24:24 -08002328 // No need to wrap it within a lock -- worst case, we'll just post the same message
2329 // twice.
Bookatz75f0a072019-08-05 14:12:16 -07002330 if (!mHandler.hasMessages(WRITE_USER_MSG, userData)) {
2331 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, userData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002332 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
2333 }
2334 }
2335
Amith Yamasani12747872015-12-07 14:19:49 -08002336 private void writeUserLP(UserData userData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002337 if (DBG) {
Amith Yamasani12747872015-12-07 14:19:49 -08002338 debug("writeUserLP " + userData);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002339 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002340 FileOutputStream fos = null;
Amith Yamasani12747872015-12-07 14:19:49 -08002341 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userData.info.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002342 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07002343 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002344 final BufferedOutputStream bos = new BufferedOutputStream(fos);
Kenny Guy02c89902016-11-15 19:36:38 +00002345 writeUserLP(userData, bos);
Amith Yamasani2a003292012-08-14 18:25:45 -07002346 userFile.finishWrite(fos);
2347 } catch (Exception ioe) {
Jeff Sharkeycd575992016-03-29 14:12:49 -06002348 Slog.e(LOG_TAG, "Error writing user info " + userData.info.id, ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -07002349 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002350 }
2351 }
2352
2353 /*
Kenny Guy02c89902016-11-15 19:36:38 +00002354 * Writes the user file in this format:
2355 *
2356 * <user flags="20039023" id="0">
2357 * <name>Primary</name>
2358 * </user>
2359 */
2360 @VisibleForTesting
2361 void writeUserLP(UserData userData, OutputStream os)
2362 throws IOException, XmlPullParserException {
2363 // XmlSerializer serializer = XmlUtils.serializerInstance();
2364 final XmlSerializer serializer = new FastXmlSerializer();
2365 serializer.setOutput(os, StandardCharsets.UTF_8.name());
2366 serializer.startDocument(null, true);
2367 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2368
2369 final UserInfo userInfo = userData.info;
2370 serializer.startTag(null, TAG_USER);
2371 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
2372 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
2373 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
2374 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
2375 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
2376 Long.toString(userInfo.lastLoggedInTime));
2377 if (userInfo.lastLoggedInFingerprint != null) {
2378 serializer.attribute(null, ATTR_LAST_LOGGED_IN_FINGERPRINT,
2379 userInfo.lastLoggedInFingerprint);
2380 }
2381 if (userInfo.iconPath != null) {
2382 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
2383 }
2384 if (userInfo.partial) {
2385 serializer.attribute(null, ATTR_PARTIAL, "true");
2386 }
Felipe Lemec1ca4412019-09-11 09:23:26 -07002387 if (userInfo.preCreated) {
2388 serializer.attribute(null, ATTR_PRE_CREATED, "true");
2389 }
Kenny Guy02c89902016-11-15 19:36:38 +00002390 if (userInfo.guestToRemove) {
2391 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
2392 }
2393 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
2394 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
2395 Integer.toString(userInfo.profileGroupId));
2396 }
2397 serializer.attribute(null, ATTR_PROFILE_BADGE,
2398 Integer.toString(userInfo.profileBadge));
2399 if (userInfo.restrictedProfileParentId != UserInfo.NO_PROFILE_GROUP_ID) {
2400 serializer.attribute(null, ATTR_RESTRICTED_PROFILE_PARENT_ID,
2401 Integer.toString(userInfo.restrictedProfileParentId));
2402 }
2403 // Write seed data
2404 if (userData.persistSeedData) {
2405 if (userData.seedAccountName != null) {
2406 serializer.attribute(null, ATTR_SEED_ACCOUNT_NAME, userData.seedAccountName);
2407 }
2408 if (userData.seedAccountType != null) {
2409 serializer.attribute(null, ATTR_SEED_ACCOUNT_TYPE, userData.seedAccountType);
2410 }
2411 }
2412 if (userInfo.name != null) {
2413 serializer.startTag(null, TAG_NAME);
2414 serializer.text(userInfo.name);
2415 serializer.endTag(null, TAG_NAME);
2416 }
2417 synchronized (mRestrictionsLock) {
2418 UserRestrictionsUtils.writeRestrictions(serializer,
2419 mBaseUserRestrictions.get(userInfo.id), TAG_RESTRICTIONS);
2420 UserRestrictionsUtils.writeRestrictions(serializer,
2421 mDevicePolicyLocalUserRestrictions.get(userInfo.id),
2422 TAG_DEVICE_POLICY_RESTRICTIONS);
Pavel Grafov6a40f092016-10-25 15:46:51 +01002423 UserRestrictionsUtils.writeRestrictions(serializer,
2424 mDevicePolicyGlobalUserRestrictions.get(userInfo.id),
2425 TAG_DEVICE_POLICY_GLOBAL_RESTRICTIONS);
Kenny Guy02c89902016-11-15 19:36:38 +00002426 }
2427
2428 if (userData.account != null) {
2429 serializer.startTag(null, TAG_ACCOUNT);
2430 serializer.text(userData.account);
2431 serializer.endTag(null, TAG_ACCOUNT);
2432 }
2433
2434 if (userData.persistSeedData && userData.seedAccountOptions != null) {
2435 serializer.startTag(null, TAG_SEED_ACCOUNT_OPTIONS);
2436 userData.seedAccountOptions.saveToXml(serializer);
2437 serializer.endTag(null, TAG_SEED_ACCOUNT_OPTIONS);
2438 }
2439
arangelov9b632d72018-12-07 23:21:22 +00002440 if (userData.getLastRequestQuietModeEnabledMillis() != 0L) {
2441 serializer.startTag(/* namespace */ null, TAG_LAST_REQUEST_QUIET_MODE_ENABLED_CALL);
2442 serializer.text(String.valueOf(userData.getLastRequestQuietModeEnabledMillis()));
2443 serializer.endTag(/* namespace */ null, TAG_LAST_REQUEST_QUIET_MODE_ENABLED_CALL);
2444 }
2445
Kenny Guy02c89902016-11-15 19:36:38 +00002446 serializer.endTag(null, TAG_USER);
2447
2448 serializer.endDocument();
2449 }
2450
2451 /*
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002452 * Writes the user list file in this format:
2453 *
Amith Yamasani2a003292012-08-14 18:25:45 -07002454 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002455 * <user id="0"></user>
2456 * <user id="2"></user>
2457 * </users>
2458 */
Andreas Gampe2e8c7672018-07-20 13:01:08 -07002459 @GuardedBy({"mRestrictionsLock", "mPackagesLock"})
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002460 private void writeUserListLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002461 if (DBG) {
2462 debug("writeUserList");
2463 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002464 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07002465 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002466 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07002467 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002468 final BufferedOutputStream bos = new BufferedOutputStream(fos);
2469
2470 // XmlSerializer serializer = XmlUtils.serializerInstance();
2471 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002472 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002473 serializer.startDocument(null, true);
2474 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2475
2476 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -07002477 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -07002478 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002479
Adam Lesinskieddeb492014-09-08 17:50:03 -07002480 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002481 synchronized (mGuestRestrictions) {
2482 UserRestrictionsUtils
2483 .writeRestrictions(serializer, mGuestRestrictions, TAG_RESTRICTIONS);
2484 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05302485 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Pavel Grafov6a40f092016-10-25 15:46:51 +01002486 serializer.startTag(null, TAG_DEVICE_OWNER_USER_ID);
2487 serializer.attribute(null, ATTR_ID, Integer.toString(mDeviceOwnerUserId));
2488 serializer.endTag(null, TAG_DEVICE_OWNER_USER_ID);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002489 int[] userIdsToWrite;
2490 synchronized (mUsersLock) {
2491 userIdsToWrite = new int[mUsers.size()];
2492 for (int i = 0; i < userIdsToWrite.length; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002493 UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002494 userIdsToWrite[i] = user.id;
2495 }
2496 }
2497 for (int id : userIdsToWrite) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002498 serializer.startTag(null, TAG_USER);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002499 serializer.attribute(null, ATTR_ID, Integer.toString(id));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002500 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002501 }
2502
2503 serializer.endTag(null, TAG_USERS);
2504
2505 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07002506 userListFile.finishWrite(fos);
2507 } catch (Exception e) {
2508 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -07002509 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002510 }
2511 }
2512
Amith Yamasani12747872015-12-07 14:19:49 -08002513 private UserData readUserLP(int id) {
Kenny Guy02c89902016-11-15 19:36:38 +00002514 FileInputStream fis = null;
2515 try {
2516 AtomicFile userFile =
2517 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
2518 fis = userFile.openRead();
2519 return readUserLP(id, fis);
2520 } catch (IOException ioe) {
2521 Slog.e(LOG_TAG, "Error reading user list");
2522 } catch (XmlPullParserException pe) {
2523 Slog.e(LOG_TAG, "Error reading user list");
2524 } finally {
2525 IoUtils.closeQuietly(fis);
2526 }
2527 return null;
2528 }
2529
2530 @VisibleForTesting
2531 UserData readUserLP(int id, InputStream is) throws IOException,
2532 XmlPullParserException {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002533 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -07002534 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002535 String name = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -08002536 String account = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002537 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -07002538 long creationTime = 0L;
2539 long lastLoggedInTime = 0L;
arangelov9b632d72018-12-07 23:21:22 +00002540 long lastRequestQuietModeEnabledTimestamp = 0L;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002541 String lastLoggedInFingerprint = null;
Kenny Guy2a764942014-04-02 13:29:20 +01002542 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Kenny Guy02c89902016-11-15 19:36:38 +00002543 int profileBadge = 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002544 int restrictedProfileParentId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002545 boolean partial = false;
Felipe Lemec1ca4412019-09-11 09:23:26 -07002546 boolean preCreated = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -07002547 boolean guestToRemove = false;
Amith Yamasani12747872015-12-07 14:19:49 -08002548 boolean persistSeedData = false;
2549 String seedAccountName = null;
2550 String seedAccountType = null;
2551 PersistableBundle seedAccountOptions = null;
Pavel Grafov6a40f092016-10-25 15:46:51 +01002552 Bundle baseRestrictions = null;
2553 Bundle localRestrictions = null;
2554 Bundle globalRestrictions = null;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002555
Kenny Guy02c89902016-11-15 19:36:38 +00002556 XmlPullParser parser = Xml.newPullParser();
2557 parser.setInput(is, StandardCharsets.UTF_8.name());
2558 int type;
2559 while ((type = parser.next()) != XmlPullParser.START_TAG
2560 && type != XmlPullParser.END_DOCUMENT) {
2561 // Skip
2562 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002563
Kenny Guy02c89902016-11-15 19:36:38 +00002564 if (type != XmlPullParser.START_TAG) {
2565 Slog.e(LOG_TAG, "Unable to read user " + id);
2566 return null;
2567 }
2568
2569 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
2570 int storedId = readIntAttribute(parser, ATTR_ID, -1);
2571 if (storedId != id) {
2572 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002573 return null;
2574 }
Kenny Guy02c89902016-11-15 19:36:38 +00002575 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
2576 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
2577 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
2578 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
2579 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
2580 lastLoggedInFingerprint = parser.getAttributeValue(null,
2581 ATTR_LAST_LOGGED_IN_FINGERPRINT);
2582 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
2583 UserInfo.NO_PROFILE_GROUP_ID);
2584 profileBadge = readIntAttribute(parser, ATTR_PROFILE_BADGE, 0);
2585 restrictedProfileParentId = readIntAttribute(parser,
2586 ATTR_RESTRICTED_PROFILE_PARENT_ID, UserInfo.NO_PROFILE_GROUP_ID);
2587 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
2588 if ("true".equals(valueString)) {
2589 partial = true;
2590 }
Felipe Lemec1ca4412019-09-11 09:23:26 -07002591 valueString = parser.getAttributeValue(null, ATTR_PRE_CREATED);
2592 if ("true".equals(valueString)) {
2593 preCreated = true;
2594 }
Kenny Guy02c89902016-11-15 19:36:38 +00002595 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
2596 if ("true".equals(valueString)) {
2597 guestToRemove = true;
2598 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002599
Kenny Guy02c89902016-11-15 19:36:38 +00002600 seedAccountName = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_NAME);
2601 seedAccountType = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_TYPE);
2602 if (seedAccountName != null || seedAccountType != null) {
2603 persistSeedData = true;
2604 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002605
Kenny Guy02c89902016-11-15 19:36:38 +00002606 int outerDepth = parser.getDepth();
2607 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2608 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2609 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2610 continue;
2611 }
2612 String tag = parser.getName();
2613 if (TAG_NAME.equals(tag)) {
2614 type = parser.next();
2615 if (type == XmlPullParser.TEXT) {
2616 name = parser.getText();
2617 }
2618 } else if (TAG_RESTRICTIONS.equals(tag)) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01002619 baseRestrictions = UserRestrictionsUtils.readRestrictions(parser);
Kenny Guy02c89902016-11-15 19:36:38 +00002620 } else if (TAG_DEVICE_POLICY_RESTRICTIONS.equals(tag)) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01002621 localRestrictions = UserRestrictionsUtils.readRestrictions(parser);
2622 } else if (TAG_DEVICE_POLICY_GLOBAL_RESTRICTIONS.equals(tag)) {
2623 globalRestrictions = UserRestrictionsUtils.readRestrictions(parser);
Kenny Guy02c89902016-11-15 19:36:38 +00002624 } else if (TAG_ACCOUNT.equals(tag)) {
2625 type = parser.next();
2626 if (type == XmlPullParser.TEXT) {
2627 account = parser.getText();
2628 }
2629 } else if (TAG_SEED_ACCOUNT_OPTIONS.equals(tag)) {
2630 seedAccountOptions = PersistableBundle.restoreFromXml(parser);
Amith Yamasani12747872015-12-07 14:19:49 -08002631 persistSeedData = true;
arangelov9b632d72018-12-07 23:21:22 +00002632 } else if (TAG_LAST_REQUEST_QUIET_MODE_ENABLED_CALL.equals(tag)) {
2633 type = parser.next();
2634 if (type == XmlPullParser.TEXT) {
2635 lastRequestQuietModeEnabledTimestamp = Long.parseLong(parser.getText());
2636 }
Amith Yamasani12747872015-12-07 14:19:49 -08002637 }
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08002638 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002639 }
Kenny Guy02c89902016-11-15 19:36:38 +00002640
2641 // Create the UserInfo object that gets passed around
2642 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
2643 userInfo.serialNumber = serialNumber;
2644 userInfo.creationTime = creationTime;
2645 userInfo.lastLoggedInTime = lastLoggedInTime;
2646 userInfo.lastLoggedInFingerprint = lastLoggedInFingerprint;
2647 userInfo.partial = partial;
Felipe Lemec1ca4412019-09-11 09:23:26 -07002648 userInfo.preCreated = preCreated;
Kenny Guy02c89902016-11-15 19:36:38 +00002649 userInfo.guestToRemove = guestToRemove;
2650 userInfo.profileGroupId = profileGroupId;
2651 userInfo.profileBadge = profileBadge;
2652 userInfo.restrictedProfileParentId = restrictedProfileParentId;
2653
2654 // Create the UserData object that's internal to this class
2655 UserData userData = new UserData();
2656 userData.info = userInfo;
2657 userData.account = account;
2658 userData.seedAccountName = seedAccountName;
2659 userData.seedAccountType = seedAccountType;
2660 userData.persistSeedData = persistSeedData;
2661 userData.seedAccountOptions = seedAccountOptions;
arangelov9b632d72018-12-07 23:21:22 +00002662 userData.setLastRequestQuietModeEnabledMillis(lastRequestQuietModeEnabledTimestamp);
Kenny Guy02c89902016-11-15 19:36:38 +00002663
2664 synchronized (mRestrictionsLock) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01002665 if (baseRestrictions != null) {
2666 mBaseUserRestrictions.put(id, baseRestrictions);
2667 }
2668 if (localRestrictions != null) {
2669 mDevicePolicyLocalUserRestrictions.put(id, localRestrictions);
2670 }
2671 if (globalRestrictions != null) {
2672 mDevicePolicyGlobalUserRestrictions.put(id, globalRestrictions);
2673 }
Kenny Guy02c89902016-11-15 19:36:38 +00002674 }
2675 return userData;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002676 }
2677
Amith Yamasani920ace02012-09-20 22:15:37 -07002678 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
2679 String valueString = parser.getAttributeValue(null, attr);
2680 if (valueString == null) return defaultValue;
2681 try {
2682 return Integer.parseInt(valueString);
2683 } catch (NumberFormatException nfe) {
2684 return defaultValue;
2685 }
2686 }
2687
2688 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
2689 String valueString = parser.getAttributeValue(null, attr);
2690 if (valueString == null) return defaultValue;
2691 try {
2692 return Long.parseLong(valueString);
2693 } catch (NumberFormatException nfe) {
2694 return defaultValue;
2695 }
2696 }
2697
Amith Yamasanib82add22013-07-09 11:24:44 -07002698 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002699 * Removes the app restrictions file for a specific package and user id, if it exists.
2700 */
Bookatzf56f2582019-09-04 16:06:41 -07002701 private static void cleanAppRestrictionsForPackageLAr(String pkg, @UserIdInt int userId) {
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07002702 File dir = Environment.getUserSystemDirectory(userId);
2703 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
2704 if (resFile.exists()) {
2705 resFile.delete();
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002706 }
2707 }
2708
Kenny Guya52dc3e2014-02-11 15:33:14 +00002709 @Override
Bookatzf56f2582019-09-04 16:06:41 -07002710 public UserInfo createProfileForUser(String name, int flags, @UserIdInt int userId,
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002711 String[] disallowedPackages) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002712 checkManageOrCreateUsersPermission(flags);
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002713 return createUserInternal(name, flags, userId, disallowedPackages);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002714 }
2715
Amith Yamasani258848d2012-08-10 17:06:33 -07002716 @Override
Bookatzf56f2582019-09-04 16:06:41 -07002717 public UserInfo createProfileForUserEvenWhenDisallowed(String name, int flags,
2718 @UserIdInt int userId, String[] disallowedPackages) {
Tony Mak6dc428f2016-10-10 15:48:27 +01002719 checkManageOrCreateUsersPermission(flags);
Felipe Lemec1ca4412019-09-11 09:23:26 -07002720 return createUserInternalUnchecked(name, flags, userId, /* preCreate= */ false,
2721 disallowedPackages);
Tony Mak6dc428f2016-10-10 15:48:27 +01002722 }
2723
2724 @Override
Bookatzf56f2582019-09-04 16:06:41 -07002725 public boolean removeUserEvenWhenDisallowed(@UserIdInt int userId) {
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00002726 checkManageOrCreateUsersPermission("Only the system can remove users");
Bookatzf56f2582019-09-04 16:06:41 -07002727 return removeUserUnchecked(userId);
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00002728 }
2729
2730 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07002731 public UserInfo createUser(String name, int flags) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002732 checkManageOrCreateUsersPermission(flags);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00002733 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002734 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07002735
Felipe Lemec1ca4412019-09-11 09:23:26 -07002736 @Override
2737 public UserInfo preCreateUser(int flags) {
2738 checkManageOrCreateUsersPermission(flags);
2739
2740 Preconditions.checkArgument(!UserInfo.isManagedProfile(flags),
2741 "cannot pre-create managed profiles");
2742
Felipe Leme09a7f2d2019-10-02 16:27:46 -07002743 Slog.i(LOG_TAG, "Pre-creating user with flags " + UserInfo.flagsToString(flags));
2744
Felipe Lemec1ca4412019-09-11 09:23:26 -07002745 return createUserInternalUnchecked(/* name= */ null, flags,
2746 /* parentId= */ UserHandle.USER_NULL, /* preCreate= */ true,
2747 /* disallowedPackages= */ null);
2748 }
2749
2750 private UserInfo createUserInternal(@Nullable String name, @UserInfoFlag int flags,
2751 @UserIdInt int parentId) {
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002752 return createUserInternal(name, flags, parentId, null);
2753 }
2754
Felipe Lemec1ca4412019-09-11 09:23:26 -07002755 private UserInfo createUserInternal(@Nullable String name, @UserInfoFlag int flags,
2756 @UserIdInt int parentId, @Nullable String[] disallowedPackages) {
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002757 String restriction = ((flags & UserInfo.FLAG_MANAGED_PROFILE) != 0)
2758 ? UserManager.DISALLOW_ADD_MANAGED_PROFILE
2759 : UserManager.DISALLOW_ADD_USER;
2760 if (hasUserRestriction(restriction, UserHandle.getCallingUserId())) {
2761 Log.w(LOG_TAG, "Cannot add user. " + restriction + " is enabled.");
Julia Reynolds75175022014-06-26 16:35:00 -04002762 return null;
2763 }
Felipe Lemec1ca4412019-09-11 09:23:26 -07002764 return createUserInternalUnchecked(name, flags, parentId, /* preCreate= */ false,
2765 disallowedPackages);
Tony Mak6dc428f2016-10-10 15:48:27 +01002766 }
2767
Felipe Lemec1ca4412019-09-11 09:23:26 -07002768 private UserInfo createUserInternalUnchecked(@Nullable String name, @UserInfoFlag int flags,
2769 @UserIdInt int parentId, boolean preCreate,
2770 @Nullable String[] disallowedPackages) {
2771 final TimingsTraceAndSlog t = new TimingsTraceAndSlog();
2772 t.traceBegin("createUser-" + flags);
2773 try {
2774 return createUserInternalUncheckedNoTracing(name, flags, parentId, preCreate,
2775 disallowedPackages, t);
2776 } finally {
2777 t.traceEnd();
2778 }
jovanakdd7e4752019-09-04 12:35:45 -07002779 }
2780
Felipe Lemec1ca4412019-09-11 09:23:26 -07002781 private UserInfo createUserInternalUncheckedNoTracing(@Nullable String name,
2782 @UserInfoFlag int flags, @UserIdInt int parentId, boolean preCreate,
2783 @Nullable String[] disallowedPackages, @NonNull TimingsTraceAndSlog t) {
2784
2785 // First try to use a pre-created user (if available).
2786 // NOTE: currently we don't support pre-created managed profiles
2787 if (!preCreate && (parentId < 0 && !UserInfo.isManagedProfile(flags))) {
2788 final UserData preCreatedUserData;
2789 synchronized (mUsersLock) {
2790 preCreatedUserData = getPreCreatedUserLU(flags);
2791 }
2792 if (preCreatedUserData != null) {
2793 final UserInfo preCreatedUser = preCreatedUserData.info;
2794 Log.i(LOG_TAG, "Reusing pre-created user " + preCreatedUser.id + " for flags + "
2795 + UserInfo.flagsToString(flags));
2796 if (DBG) {
2797 Log.d(LOG_TAG, "pre-created user flags: "
2798 + UserInfo.flagsToString(preCreatedUser.flags)
2799 + " new-user flags: " + UserInfo.flagsToString(flags));
2800 }
2801 preCreatedUser.name = name;
2802 preCreatedUser.preCreated = false;
2803 preCreatedUser.creationTime = getCreationTime();
2804
2805 dispatchUserAddedIntent(preCreatedUser);
2806
2807 writeUserLP(preCreatedUserData);
2808 writeUserListLP();
2809
2810 return preCreatedUser;
2811 }
2812 }
2813
Suprabh Shuklac5e057c2016-08-08 16:22:44 -07002814 DeviceStorageMonitorInternal dsm = LocalServices
2815 .getService(DeviceStorageMonitorInternal.class);
2816 if (dsm.isMemoryLow()) {
2817 Log.w(LOG_TAG, "Cannot add user. Not enough space on disk.");
2818 return null;
2819 }
jovanakdd7e4752019-09-04 12:35:45 -07002820
Felipe Lemec1ca4412019-09-11 09:23:26 -07002821 final boolean isGuest = UserInfo.isGuest(flags);
2822 final boolean isManagedProfile = UserInfo.isManagedProfile(flags);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002823 final boolean isRestricted = (flags & UserInfo.FLAG_RESTRICTED) != 0;
Amith Yamasani52c21e32016-05-31 09:12:20 -07002824 final boolean isDemo = (flags & UserInfo.FLAG_DEMO) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002825 final long ident = Binder.clearCallingIdentity();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002826 UserInfo userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08002827 UserData userData;
Amith Yamasanibb054c92015-07-09 14:16:27 -07002828 final int userId;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002829 try {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002830 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002831 UserData parent = null;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002832 if (parentId != UserHandle.USER_NULL) {
2833 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002834 parent = getUserDataLU(parentId);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00002835 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002836 if (parent == null) return null;
2837 }
2838 if (isManagedProfile && !canAddMoreManagedProfiles(parentId, false)) {
2839 Log.e(LOG_TAG, "Cannot add more managed profiles for user " + parentId);
2840 return null;
2841 }
Amith Yamasani52c21e32016-05-31 09:12:20 -07002842 if (!isGuest && !isManagedProfile && !isDemo && isUserLimitReached()) {
Felipe Lemec1ca4412019-09-11 09:23:26 -07002843 // If we're not adding a guest/demo user or a managed profile,
2844 // and the limit has been reached, cannot add a user.
jovanaka6763a32018-12-03 17:23:20 -08002845 Log.e(LOG_TAG, "Cannot add user. Maximum user limit is reached.");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002846 return null;
2847 }
2848 // If we're adding a guest and there already exists one, bail.
Felipe Lemee35f5b02019-10-14 15:37:44 -07002849 if (isGuest && !preCreate && findCurrentGuestUser() != null) {
jovanaka6763a32018-12-03 17:23:20 -08002850 Log.e(LOG_TAG, "Cannot add guest user. Guest user already exists.");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002851 return null;
2852 }
2853 // In legacy mode, restricted profile's parent can only be the owner user
2854 if (isRestricted && !UserManager.isSplitSystemUser()
2855 && (parentId != UserHandle.USER_SYSTEM)) {
2856 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
2857 return null;
2858 }
2859 if (isRestricted && UserManager.isSplitSystemUser()) {
2860 if (parent == null) {
2861 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be "
2862 + "specified");
Nicolas Prevot12678a92015-05-13 12:15:03 -07002863 return null;
2864 }
Amith Yamasani12747872015-12-07 14:19:49 -08002865 if (!parent.info.canHaveProfile()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002866 Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be "
2867 + "created for the specified parent user id " + parentId);
Amith Yamasani95ab7842014-08-11 17:09:26 -07002868 return null;
2869 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002870 }
Ying Zheng215116f2019-09-11 12:50:09 -07002871
Bookatz75f0a072019-08-05 14:12:16 -07002872 if (!isManagedProfile) {
2873 // New users cannot be system, and it's not a profile, so per-force it's FULL.
2874 flags |= UserInfo.FLAG_FULL;
2875 }
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002876
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002877 userId = getNextAvailableId();
2878 Environment.getUserSystemDirectory(userId).mkdirs();
Felipe Lemec1ca4412019-09-11 09:23:26 -07002879 boolean ephemeralGuests = areGuestUsersEphemeral();
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002880
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002881 synchronized (mUsersLock) {
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002882 // Add ephemeral flag to guests/users if required. Also inherit it from parent.
2883 if ((isGuest && ephemeralGuests) || mForceEphemeralUsers
2884 || (parent != null && parent.info.isEphemeral())) {
2885 flags |= UserInfo.FLAG_EPHEMERAL;
2886 }
2887
2888 userInfo = new UserInfo(userId, name, null, flags);
2889 userInfo.serialNumber = mNextSerialNumber++;
Felipe Lemec1ca4412019-09-11 09:23:26 -07002890 userInfo.creationTime = getCreationTime();
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002891 userInfo.partial = true;
Felipe Lemec1ca4412019-09-11 09:23:26 -07002892 userInfo.preCreated = preCreate;
Fyodor Kupolov83c24242016-03-31 13:30:42 -07002893 userInfo.lastLoggedInFingerprint = Build.FINGERPRINT;
Kenny Guy02c89902016-11-15 19:36:38 +00002894 if (isManagedProfile && parentId != UserHandle.USER_NULL) {
2895 userInfo.profileBadge = getFreeProfileBadgeLU(parentId);
2896 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002897 userData = new UserData();
2898 userData.info = userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08002899 mUsers.put(userId, userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002900 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06002901 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002902 writeUserListLP();
2903 if (parent != null) {
2904 if (isManagedProfile) {
Amith Yamasani12747872015-12-07 14:19:49 -08002905 if (parent.info.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
2906 parent.info.profileGroupId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002907 writeUserLP(parent);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002908 }
Amith Yamasani12747872015-12-07 14:19:49 -08002909 userInfo.profileGroupId = parent.info.profileGroupId;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002910 } else if (isRestricted) {
Amith Yamasani12747872015-12-07 14:19:49 -08002911 if (parent.info.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) {
2912 parent.info.restrictedProfileParentId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002913 writeUserLP(parent);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002914 }
Amith Yamasani12747872015-12-07 14:19:49 -08002915 userInfo.restrictedProfileParentId = parent.info.restrictedProfileParentId;
Makoto Onuki068c54a2015-10-13 14:34:03 -07002916 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002917 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07002918 }
jovanakdd7e4752019-09-04 12:35:45 -07002919
2920 t.traceBegin("createUserKey");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002921 final StorageManager storage = mContext.getSystemService(StorageManager.class);
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002922 storage.createUserKey(userId, userInfo.serialNumber, userInfo.isEphemeral());
jovanakdd7e4752019-09-04 12:35:45 -07002923 t.traceEnd();
2924
2925 t.traceBegin("prepareUserData");
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -08002926 mUserDataPreparer.prepareUserData(userId, userInfo.serialNumber,
Jeff Sharkey47f71082016-02-01 17:03:54 -07002927 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
jovanakdd7e4752019-09-04 12:35:45 -07002928 t.traceEnd();
2929
Bookatz04d7ae52019-08-05 14:07:12 -07002930 final Set<String> installablePackages =
2931 mSystemPackageInstaller.getInstallablePackagesForUserType(flags);
jovanakdd7e4752019-09-04 12:35:45 -07002932 t.traceBegin("PM.createNewUser");
Bookatz04d7ae52019-08-05 14:07:12 -07002933 mPm.createNewUser(userId, installablePackages, disallowedPackages);
jovanakdd7e4752019-09-04 12:35:45 -07002934 t.traceEnd();
2935
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002936 userInfo.partial = false;
2937 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002938 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002939 }
2940 updateUserIds();
2941 Bundle restrictions = new Bundle();
Fyodor Kupolove04462c2015-11-30 15:02:53 -08002942 if (isGuest) {
2943 synchronized (mGuestRestrictions) {
2944 restrictions.putAll(mGuestRestrictions);
2945 }
2946 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002947 synchronized (mRestrictionsLock) {
2948 mBaseUserRestrictions.append(userId, restrictions);
2949 }
jovanakdd7e4752019-09-04 12:35:45 -07002950
2951 t.traceBegin("PM.onNewUserCreated");
Fyodor Kupolov5fd967d2016-07-12 14:46:19 -07002952 mPm.onNewUserCreated(userId);
jovanakdd7e4752019-09-04 12:35:45 -07002953
Felipe Lemec1ca4412019-09-11 09:23:26 -07002954 if (preCreate) {
2955 // Must start user (which will be stopped right away, through
2956 // UserController.finishUserUnlockedCompleted) so services can properly
2957 // intialize it.
2958 // TODO(b/140750212): in the long-term, we should add a onCreateUser() callback
2959 // on SystemService instead.
2960 Slog.i(LOG_TAG, "starting pre-created user " + userInfo.toFullString());
2961 final IActivityManager am = ActivityManager.getService();
2962 try {
2963 am.startUserInBackground(userId);
2964 } catch (RemoteException e) {
2965 Slog.w(LOG_TAG, "could not start pre-created user " + userId, e);
2966 }
2967 } else {
2968 dispatchUserAddedIntent(userInfo);
2969 }
2970
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002971 } finally {
2972 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07002973 }
Felipe Lemec1ca4412019-09-11 09:23:26 -07002974
2975 // TODO(b/140750212): it's possible to reach "max users overflow" when the user is created
2976 // "from scratch" (i.e., not from a pre-created user) and reaches the maximum number of
2977 // users without counting the pre-created one. Then when the pre-created is converted, the
2978 // "effective" number of max users is exceeds. Example:
2979 // Max: 3 Current: 2 full (u0 and u10) + 1 pre-created (u11)
2980 // Step 1: create(/* flags doesn't match u11 */): u12 is created, "effective max" is now 3
2981 // (u0, u10, u12) but "real" max is 4 (u0, u10, u11, u12)
2982 // Step 2: create(/* flags match u11 */): u11 is converted, now "effective max" is also 4
2983 // (u0, u10, u11, u12)
2984 // One way to avoid this issue is by removing a pre-created user from the pool when the
2985 // "real" max exceeds the max here.
2986
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002987 return userInfo;
2988 }
2989
Bookatz04d7ae52019-08-05 14:07:12 -07002990 /** Install/uninstall system packages for all users based on their user-type, as applicable. */
2991 boolean installWhitelistedSystemPackages(boolean isFirstBoot, boolean isUpgrade) {
2992 return mSystemPackageInstaller.installWhitelistedSystemPackages(isFirstBoot, isUpgrade);
2993 }
2994
Felipe Lemec1ca4412019-09-11 09:23:26 -07002995 private long getCreationTime() {
2996 final long now = System.currentTimeMillis();
2997 return (now > EPOCH_PLUS_30_YEARS) ? now : 0;
2998 }
2999
3000 private void dispatchUserAddedIntent(@NonNull UserInfo userInfo) {
3001 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
3002 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userInfo.id);
3003 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
3004 android.Manifest.permission.MANAGE_USERS);
3005 MetricsLogger.count(mContext, userInfo.isGuest() ? TRON_GUEST_CREATED
3006 : (userInfo.isDemo() ? TRON_DEMO_CREATED : TRON_USER_CREATED), 1);
3007 }
3008
3009 private boolean areGuestUsersEphemeral() {
3010 return Resources.getSystem()
3011 .getBoolean(com.android.internal.R.bool.config_guestUserEphemeral);
3012 }
3013
3014 /**
3015 * Gets a pre-created user for the given flag.
3016 *
3017 * <p>Should be used only during user creation, so the pre-created user can be used (instead of
3018 * creating and initializing a new user from scratch).
3019 */
3020 // TODO(b/140750212): add unit test
3021 @GuardedBy("mUsersLock")
3022 private @Nullable UserData getPreCreatedUserLU(@UserInfoFlag int flags) {
3023 if (DBG) {
3024 Slog.d(LOG_TAG, "getPreCreatedUser(): initialFlags= " + UserInfo.flagsToString(flags));
3025 }
3026 flags |= UserInfo.FLAG_FULL;
3027 if (UserInfo.isGuest(flags) && areGuestUsersEphemeral()) {
3028 flags |= UserInfo.FLAG_EPHEMERAL;
3029 }
3030 if (DBG) {
3031 Slog.d(LOG_TAG, "getPreCreatedUser(): targetFlags= " + UserInfo.flagsToString(flags));
3032 }
3033 final int userSize = mUsers.size();
3034 for (int i = 0; i < userSize; i++) {
3035 final UserData user = mUsers.valueAt(i);
3036 if (DBG) Slog.d(LOG_TAG, i + ":" + user.info.toFullString());
3037 if (user.info.preCreated
3038 && (user.info.flags & ~UserInfo.FLAG_INITIALIZED) == flags) {
3039 if (!user.info.isInitialized()) {
3040 Slog.w(LOG_TAG, "found pre-created user for flags "
3041 + "" + UserInfo.flagsToString(flags)
3042 + ", but it's not initialized yet: " + user.info.toFullString());
3043 continue;
3044 }
3045 return user;
3046 }
3047 }
3048 return null;
3049 }
3050
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003051 @VisibleForTesting
3052 UserData putUserInfo(UserInfo userInfo) {
3053 final UserData userData = new UserData();
3054 userData.info = userInfo;
3055 synchronized (mUsers) {
3056 mUsers.put(userInfo.id, userData);
3057 }
3058 return userData;
3059 }
3060
3061 @VisibleForTesting
Bookatzf56f2582019-09-04 16:06:41 -07003062 void removeUserInfo(@UserIdInt int userId) {
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003063 synchronized (mUsers) {
3064 mUsers.remove(userId);
3065 }
3066 }
3067
Amith Yamasani0b285492011-04-14 17:35:23 -07003068 /**
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003069 * @hide
3070 */
Amith Yamasani12747872015-12-07 14:19:49 -08003071 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003072 public UserInfo createRestrictedProfile(String name, int parentUserId) {
Sudheer Shanka53d41472016-06-16 09:11:08 -07003073 checkManageOrCreateUsersPermission("setupRestrictedProfile");
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07003074 final UserInfo user = createProfileForUser(
3075 name, UserInfo.FLAG_RESTRICTED, parentUserId, null);
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003076 if (user == null) {
3077 return null;
3078 }
Fyodor Kupolov9e912ba2016-02-09 18:29:43 -08003079 long identity = Binder.clearCallingIdentity();
3080 try {
3081 setUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, true, user.id);
3082 // Change the setting before applying the DISALLOW_SHARE_LOCATION restriction, otherwise
3083 // the putIntForUser() will fail.
3084 android.provider.Settings.Secure.putIntForUser(mContext.getContentResolver(),
3085 android.provider.Settings.Secure.LOCATION_MODE,
3086 android.provider.Settings.Secure.LOCATION_MODE_OFF, user.id);
3087 setUserRestriction(UserManager.DISALLOW_SHARE_LOCATION, true, user.id);
3088 } finally {
3089 Binder.restoreCallingIdentity(identity);
3090 }
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003091 return user;
3092 }
3093
3094 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07003095 * Find the current guest user. If the Guest user is partial,
3096 * then do not include it in the results as it is about to die.
Adam Lesinskieddeb492014-09-08 17:50:03 -07003097 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07003098 private UserInfo findCurrentGuestUser() {
3099 synchronized (mUsersLock) {
3100 final int size = mUsers.size();
3101 for (int i = 0; i < size; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003102 final UserInfo user = mUsers.valueAt(i).info;
Felipe Lemee35f5b02019-10-14 15:37:44 -07003103 if (user.isGuest() && !user.guestToRemove && !user.preCreated
3104 && !mRemovingUserIds.get(user.id)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003105 return user;
3106 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07003107 }
3108 }
3109 return null;
3110 }
3111
3112 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07003113 * Mark this guest user for deletion to allow us to create another guest
3114 * and switch to that user before actually removing this guest.
Bookatzf56f2582019-09-04 16:06:41 -07003115 * @param userId the userid of the current guest
Amith Yamasani1df14732014-08-29 21:37:27 -07003116 * @return whether the user could be marked for deletion
3117 */
Amith Yamasani12747872015-12-07 14:19:49 -08003118 @Override
Bookatzf56f2582019-09-04 16:06:41 -07003119 public boolean markGuestForDeletion(@UserIdInt int userId) {
Amith Yamasani1df14732014-08-29 21:37:27 -07003120 checkManageUsersPermission("Only the system can remove users");
3121 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
3122 UserManager.DISALLOW_REMOVE_USER, false)) {
3123 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
3124 return false;
3125 }
3126
3127 long ident = Binder.clearCallingIdentity();
3128 try {
Amith Yamasani12747872015-12-07 14:19:49 -08003129 final UserData userData;
Amith Yamasani1df14732014-08-29 21:37:27 -07003130 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003131 synchronized (mUsersLock) {
Bookatzf56f2582019-09-04 16:06:41 -07003132 userData = mUsers.get(userId);
3133 if (userId == 0 || userData == null || mRemovingUserIds.get(userId)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003134 return false;
3135 }
Amith Yamasani1df14732014-08-29 21:37:27 -07003136 }
Amith Yamasani12747872015-12-07 14:19:49 -08003137 if (!userData.info.isGuest()) {
Amith Yamasani1df14732014-08-29 21:37:27 -07003138 return false;
3139 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07003140 // We set this to a guest user that is to be removed. This is a temporary state
3141 // where we are allowed to add new Guest users, even if this one is still not
3142 // removed. This user will still show up in getUserInfo() calls.
3143 // If we don't get around to removing this Guest user, it will be purged on next
3144 // startup.
Amith Yamasani12747872015-12-07 14:19:49 -08003145 userData.info.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07003146 // Mark it as disabled, so that it isn't returned any more when
3147 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08003148 userData.info.flags |= UserInfo.FLAG_DISABLED;
3149 writeUserLP(userData);
Amith Yamasani1df14732014-08-29 21:37:27 -07003150 }
3151 } finally {
3152 Binder.restoreCallingIdentity(ident);
3153 }
3154 return true;
3155 }
3156
3157 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07003158 * Removes a user and all data directories created for that user. This method should be called
3159 * after the user's processes have been terminated.
Bookatzf56f2582019-09-04 16:06:41 -07003160 * @param userId the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07003161 */
Amith Yamasani12747872015-12-07 14:19:49 -08003162 @Override
Bookatzf56f2582019-09-04 16:06:41 -07003163 public boolean removeUser(@UserIdInt int userId) {
3164 Slog.i(LOG_TAG, "removeUser u" + userId);
Sudheer Shankaf5cea032016-06-08 17:13:24 -07003165 checkManageOrCreateUsersPermission("Only the system can remove users");
Esteban Talavera6c9116a2016-11-24 16:12:44 +00003166
3167 final boolean isManagedProfile;
3168 synchronized (mUsersLock) {
Bookatzf56f2582019-09-04 16:06:41 -07003169 UserInfo userInfo = getUserInfoLU(userId);
Esteban Talavera6c9116a2016-11-24 16:12:44 +00003170 isManagedProfile = userInfo != null && userInfo.isManagedProfile();
3171 }
3172 String restriction = isManagedProfile
3173 ? UserManager.DISALLOW_REMOVE_MANAGED_PROFILE : UserManager.DISALLOW_REMOVE_USER;
3174 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(restriction, false)) {
3175 Log.w(LOG_TAG, "Cannot remove user. " + restriction + " is enabled.");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04003176 return false;
3177 }
Bookatzf56f2582019-09-04 16:06:41 -07003178 return removeUserUnchecked(userId);
Nicolas Prevotdf1b87d2016-10-25 13:57:08 +01003179 }
Julia Reynolds4ac5f852014-06-23 17:38:51 -04003180
Bookatzf56f2582019-09-04 16:06:41 -07003181 private boolean removeUserUnchecked(@UserIdInt int userId) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01003182 long ident = Binder.clearCallingIdentity();
3183 try {
Amith Yamasani12747872015-12-07 14:19:49 -08003184 final UserData userData;
Fyodor Kupolov0df68cd2015-10-01 13:54:22 -07003185 int currentUser = ActivityManager.getCurrentUser();
Bookatzf56f2582019-09-04 16:06:41 -07003186 if (currentUser == userId) {
jovanaka6763a32018-12-03 17:23:20 -08003187 Log.w(LOG_TAG, "Current user cannot be removed.");
Fyodor Kupolov0df68cd2015-10-01 13:54:22 -07003188 return false;
3189 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01003190 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003191 synchronized (mUsersLock) {
Bookatzf56f2582019-09-04 16:06:41 -07003192 userData = mUsers.get(userId);
3193 if (userId == UserHandle.USER_SYSTEM) {
jovanaka6763a32018-12-03 17:23:20 -08003194 Log.e(LOG_TAG, "System user cannot be removed.");
3195 return false;
3196 }
3197
3198 if (userData == null) {
3199 Log.e(LOG_TAG, String.format(
Bookatzf56f2582019-09-04 16:06:41 -07003200 "Cannot remove user %d, invalid user id provided.", userId));
jovanaka6763a32018-12-03 17:23:20 -08003201 return false;
3202 }
3203
Bookatzf56f2582019-09-04 16:06:41 -07003204 if (mRemovingUserIds.get(userId)) {
jovanaka6763a32018-12-03 17:23:20 -08003205 Log.e(LOG_TAG, String.format(
Bookatzf56f2582019-09-04 16:06:41 -07003206 "User %d is already scheduled for removal.", userId));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003207 return false;
3208 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08003209
Bookatzf56f2582019-09-04 16:06:41 -07003210 addRemovingUserIdLocked(userId);
Fyodor Kupolov82402752015-10-28 14:54:51 -07003211 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08003212
Kenny Guyee58b4f2014-05-23 15:19:53 +01003213 // Set this to a partially created user, so that the user will be purged
3214 // on next startup, in case the runtime stops now before stopping and
3215 // removing the user completely.
Amith Yamasani12747872015-12-07 14:19:49 -08003216 userData.info.partial = true;
Kenny Guyee58b4f2014-05-23 15:19:53 +01003217 // Mark it as disabled, so that it isn't returned any more when
3218 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08003219 userData.info.flags |= UserInfo.FLAG_DISABLED;
3220 writeUserLP(userData);
Kenny Guyee58b4f2014-05-23 15:19:53 +01003221 }
Fyodor Kupolov6c96f7f2017-06-28 18:22:59 -07003222 try {
Bookatzf56f2582019-09-04 16:06:41 -07003223 mAppOpsService.removeUser(userId);
Fyodor Kupolov6c96f7f2017-06-28 18:22:59 -07003224 } catch (RemoteException e) {
jovanaka6763a32018-12-03 17:23:20 -08003225 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user.", e);
Fyodor Kupolov6c96f7f2017-06-28 18:22:59 -07003226 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01003227
Amith Yamasani12747872015-12-07 14:19:49 -08003228 if (userData.info.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
3229 && userData.info.isManagedProfile()) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01003230 // Send broadcast to notify system that the user removed was a
3231 // managed user.
Amith Yamasani12747872015-12-07 14:19:49 -08003232 sendProfileRemovedBroadcast(userData.info.profileGroupId, userData.info.id);
Kenny Guyee58b4f2014-05-23 15:19:53 +01003233 }
3234
Bookatzf56f2582019-09-04 16:06:41 -07003235 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userId);
Kenny Guyee58b4f2014-05-23 15:19:53 +01003236 int res;
3237 try {
Bookatzf56f2582019-09-04 16:06:41 -07003238 res = ActivityManager.getService().stopUser(userId, /* force= */ true,
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07003239 new IStopUserCallback.Stub() {
Kenny Guyee58b4f2014-05-23 15:19:53 +01003240 @Override
Bookatzf56f2582019-09-04 16:06:41 -07003241 public void userStopped(int userIdParam) {
3242 finishRemoveUser(userIdParam);
Kenny Guyee58b4f2014-05-23 15:19:53 +01003243 }
3244 @Override
Bookatzf56f2582019-09-04 16:06:41 -07003245 public void userStopAborted(int userIdParam) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01003246 }
3247 });
3248 } catch (RemoteException e) {
jovanaka6763a32018-12-03 17:23:20 -08003249 Log.w(LOG_TAG, "Failed to stop user during removal.", e);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003250 return false;
3251 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01003252 return res == ActivityManager.USER_OP_SUCCESS;
3253 } finally {
3254 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003255 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003256 }
3257
Andreas Gampea36dc622018-02-05 17:19:22 -08003258 @GuardedBy("mUsersLock")
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003259 @VisibleForTesting
Bookatzf56f2582019-09-04 16:06:41 -07003260 void addRemovingUserIdLocked(@UserIdInt int userId) {
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003261 // We remember deleted user IDs to prevent them from being
3262 // reused during the current boot; they can still be reused
3263 // after a reboot or recycling of userIds.
3264 mRemovingUserIds.put(userId, true);
3265 mRecentlyRemovedIds.add(userId);
3266 // Keep LRU queue of recently removed IDs for recycling
3267 if (mRecentlyRemovedIds.size() > MAX_RECENTLY_REMOVED_IDS_SIZE) {
3268 mRecentlyRemovedIds.removeFirst();
3269 }
3270 }
3271
Bookatzf56f2582019-09-04 16:06:41 -07003272 void finishRemoveUser(final @UserIdInt int userId) {
3273 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userId);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07003274 // Let other services shutdown any activity and clean up their state before completely
3275 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07003276 long ident = Binder.clearCallingIdentity();
3277 try {
3278 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
Bookatzf56f2582019-09-04 16:06:41 -07003279 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07003280 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
3281 android.Manifest.permission.MANAGE_USERS,
3282
3283 new BroadcastReceiver() {
3284 @Override
3285 public void onReceive(Context context, Intent intent) {
3286 if (DBG) {
3287 Slog.i(LOG_TAG,
3288 "USER_REMOVED broadcast sent, cleaning up user data "
Bookatzf56f2582019-09-04 16:06:41 -07003289 + userId);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07003290 }
3291 new Thread() {
Amith Yamasani12747872015-12-07 14:19:49 -08003292 @Override
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07003293 public void run() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003294 // Clean up any ActivityTaskManager state
3295 LocalServices.getService(ActivityTaskManagerInternal.class)
Bookatzf56f2582019-09-04 16:06:41 -07003296 .onUserStopped(userId);
3297 removeUserState(userId);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07003298 }
3299 }.start();
3300 }
3301 },
3302
3303 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07003304 } finally {
3305 Binder.restoreCallingIdentity(ident);
3306 }
Amith Yamasani2a003292012-08-14 18:25:45 -07003307 }
3308
Bookatzf56f2582019-09-04 16:06:41 -07003309 private void removeUserState(final @UserIdInt int userId) {
Paul Crowley91293792016-03-25 15:23:07 -07003310 try {
Bookatzf56f2582019-09-04 16:06:41 -07003311 mContext.getSystemService(StorageManager.class).destroyUserKey(userId);
Paul Crowley91293792016-03-25 15:23:07 -07003312 } catch (IllegalStateException e) {
3313 // This may be simply because the user was partially created.
Bookatzf56f2582019-09-04 16:06:41 -07003314 Slog.i(LOG_TAG, "Destroying key for user " + userId + " failed, continuing anyway", e);
Paul Crowley91293792016-03-25 15:23:07 -07003315 }
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06003316
Amith Yamasanid04aaa32016-06-13 12:09:36 -07003317 // Cleanup gatekeeper secure user id
3318 try {
3319 final IGateKeeperService gk = GateKeeper.getService();
3320 if (gk != null) {
Bookatzf56f2582019-09-04 16:06:41 -07003321 gk.clearSecureUserId(userId);
Amith Yamasanid04aaa32016-06-13 12:09:36 -07003322 }
3323 } catch (Exception ex) {
3324 Slog.w(LOG_TAG, "unable to clear GK secure user id");
3325 }
3326
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003327 // Cleanup package manager settings
Bookatzf56f2582019-09-04 16:06:41 -07003328 mPm.cleanUpUser(this, userId);
Amith Yamasanid04aaa32016-06-13 12:09:36 -07003329
3330 // Clean up all data before removing metadata
Bookatzf56f2582019-09-04 16:06:41 -07003331 mUserDataPreparer.destroyUserData(userId,
Amith Yamasanid04aaa32016-06-13 12:09:36 -07003332 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
3333
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003334 // Remove this user from the list
Fyodor Kupolov82402752015-10-28 14:54:51 -07003335 synchronized (mUsersLock) {
Bookatzf56f2582019-09-04 16:06:41 -07003336 mUsers.remove(userId);
3337 mIsUserManaged.delete(userId);
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003338 }
3339 synchronized (mUserStates) {
Bookatzf56f2582019-09-04 16:06:41 -07003340 mUserStates.delete(userId);
Makoto Onukie7927da2015-11-25 10:05:17 -08003341 }
3342 synchronized (mRestrictionsLock) {
Bookatzf56f2582019-09-04 16:06:41 -07003343 mBaseUserRestrictions.remove(userId);
3344 mAppliedUserRestrictions.remove(userId);
3345 mCachedEffectiveUserRestrictions.remove(userId);
3346 mDevicePolicyLocalUserRestrictions.remove(userId);
3347 if (mDevicePolicyGlobalUserRestrictions.get(userId) != null) {
3348 mDevicePolicyGlobalUserRestrictions.remove(userId);
Pavel Grafov6a40f092016-10-25 15:46:51 +01003349 applyUserRestrictionsForAllUsersLR();
3350 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07003351 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003352 // Update the user list
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003353 synchronized (mPackagesLock) {
3354 writeUserListLP();
3355 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06003356 // Remove user file
Bookatzf56f2582019-09-04 16:06:41 -07003357 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userId + XML_SUFFIX));
Jeff Sharkeycd575992016-03-29 14:12:49 -06003358 userFile.delete();
Fyodor Kupolov82402752015-10-28 14:54:51 -07003359 updateUserIds();
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003360 if (RELEASE_DELETED_USER_ID) {
3361 synchronized (mUsers) {
Bookatzf56f2582019-09-04 16:06:41 -07003362 mRemovingUserIds.delete(userId);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003363 }
3364 }
Amith Yamasani61f57372012-08-31 12:12:28 -07003365 }
3366
Kenny Guyf8d3a232014-05-15 16:09:52 +01003367 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01003368 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01003369 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
3370 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01003371 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
Jeff Sharkeyaf6ec292015-12-17 11:19:00 -07003372 managedProfileIntent.putExtra(Intent.EXTRA_USER_HANDLE, removedUserId);
Kenny Guyf8d3a232014-05-15 16:09:52 +01003373 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01003374 }
3375
Amith Yamasani2a003292012-08-14 18:25:45 -07003376 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07003377 public Bundle getApplicationRestrictions(String packageName) {
3378 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
3379 }
3380
3381 @Override
Bookatzf56f2582019-09-04 16:06:41 -07003382 public Bundle getApplicationRestrictionsForUser(String packageName, @UserIdInt int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003383 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07003384 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07003385 checkSystemOrRoot("get application restrictions for other user/app " + packageName);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003386 }
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003387 synchronized (mAppRestrictionsLock) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003388 // Read the restrictions from XML
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003389 return readApplicationRestrictionsLAr(packageName, userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003390 }
3391 }
3392
3393 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07003394 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Bookatzf56f2582019-09-04 16:06:41 -07003395 @UserIdInt int userId) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00003396 checkSystemOrRoot("set application restrictions");
Fyodor Kupolov0d88d542016-04-19 11:37:22 -07003397 if (restrictions != null) {
3398 restrictions.setDefusable(true);
3399 }
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003400 synchronized (mAppRestrictionsLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01003401 if (restrictions == null || restrictions.isEmpty()) {
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003402 cleanAppRestrictionsForPackageLAr(packageName, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01003403 } else {
3404 // Write the restrictions to XML
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003405 writeApplicationRestrictionsLAr(packageName, restrictions, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01003406 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003407 }
Robin Lee66e5d962014-04-09 16:44:21 +01003408
Fyodor Kupolovd2846122016-02-11 18:06:34 -08003409 // Notify package of changes via an intent - only sent to explicitly registered receivers.
3410 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
3411 changeIntent.setPackage(packageName);
3412 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3413 mContext.sendBroadcastAsUser(changeIntent, UserHandle.of(userId));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003414 }
3415
3416 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07003417 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003418 try {
3419 return mContext.getPackageManager().getApplicationInfo(packageName,
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07003420 PackageManager.MATCH_ANY_USER).uid;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003421 } catch (NameNotFoundException nnfe) {
3422 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07003423 } finally {
3424 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003425 }
3426 }
3427
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003428 @GuardedBy("mAppRestrictionsLock")
Bookatzf56f2582019-09-04 16:06:41 -07003429 private static Bundle readApplicationRestrictionsLAr(String packageName,
3430 @UserIdInt int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003431 AtomicFile restrictionsFile =
3432 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
3433 packageToRestrictionsFileName(packageName)));
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003434 return readApplicationRestrictionsLAr(restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003435 }
3436
3437 @VisibleForTesting
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003438 @GuardedBy("mAppRestrictionsLock")
3439 static Bundle readApplicationRestrictionsLAr(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07003440 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003441 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07003442 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07003443 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07003444 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003445
3446 FileInputStream fis = null;
3447 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003448 fis = restrictionsFile.openRead();
3449 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01003450 parser.setInput(fis, StandardCharsets.UTF_8.name());
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003451 XmlUtils.nextElement(parser);
3452 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003453 Slog.e(LOG_TAG, "Unable to read restrictions file "
3454 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07003455 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003456 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003457 while (parser.next() != XmlPullParser.END_DOCUMENT) {
3458 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003459 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003460 } catch (IOException|XmlPullParserException e) {
3461 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003462 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003463 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003464 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07003465 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003466 }
3467
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003468 private static void readEntry(Bundle restrictions, ArrayList<String> values,
3469 XmlPullParser parser) throws XmlPullParserException, IOException {
3470 int type = parser.getEventType();
3471 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
3472 String key = parser.getAttributeValue(null, ATTR_KEY);
3473 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
3474 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
3475 if (multiple != null) {
3476 values.clear();
3477 int count = Integer.parseInt(multiple);
3478 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
3479 if (type == XmlPullParser.START_TAG
3480 && parser.getName().equals(TAG_VALUE)) {
3481 values.add(parser.nextText().trim());
3482 count--;
3483 }
3484 }
3485 String [] valueStrings = new String[values.size()];
3486 values.toArray(valueStrings);
3487 restrictions.putStringArray(key, valueStrings);
3488 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
3489 restrictions.putBundle(key, readBundleEntry(parser, values));
3490 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
3491 final int outerDepth = parser.getDepth();
3492 ArrayList<Bundle> bundleList = new ArrayList<>();
3493 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
3494 Bundle childBundle = readBundleEntry(parser, values);
3495 bundleList.add(childBundle);
3496 }
3497 restrictions.putParcelableArray(key,
3498 bundleList.toArray(new Bundle[bundleList.size()]));
3499 } else {
3500 String value = parser.nextText().trim();
3501 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
3502 restrictions.putBoolean(key, Boolean.parseBoolean(value));
3503 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
3504 restrictions.putInt(key, Integer.parseInt(value));
3505 } else {
3506 restrictions.putString(key, value);
3507 }
3508 }
3509 }
3510 }
3511
3512 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
3513 throws IOException, XmlPullParserException {
3514 Bundle childBundle = new Bundle();
3515 final int outerDepth = parser.getDepth();
3516 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
3517 readEntry(childBundle, values, parser);
3518 }
3519 return childBundle;
3520 }
3521
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003522 @GuardedBy("mAppRestrictionsLock")
3523 private static void writeApplicationRestrictionsLAr(String packageName,
Bookatzf56f2582019-09-04 16:06:41 -07003524 Bundle restrictions, @UserIdInt int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003525 AtomicFile restrictionsFile = new AtomicFile(
3526 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07003527 packageToRestrictionsFileName(packageName)));
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003528 writeApplicationRestrictionsLAr(restrictions, restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003529 }
3530
3531 @VisibleForTesting
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003532 @GuardedBy("mAppRestrictionsLock")
3533 static void writeApplicationRestrictionsLAr(Bundle restrictions, AtomicFile restrictionsFile) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003534 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003535 try {
3536 fos = restrictionsFile.startWrite();
3537 final BufferedOutputStream bos = new BufferedOutputStream(fos);
3538
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003539 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01003540 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003541 serializer.startDocument(null, true);
3542 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
3543
3544 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003545 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003546 serializer.endTag(null, TAG_RESTRICTIONS);
3547
3548 serializer.endDocument();
3549 restrictionsFile.finishWrite(fos);
3550 } catch (Exception e) {
3551 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003552 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
3553 }
3554 }
3555
3556 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
3557 throws IOException {
3558 for (String key : restrictions.keySet()) {
3559 Object value = restrictions.get(key);
3560 serializer.startTag(null, TAG_ENTRY);
3561 serializer.attribute(null, ATTR_KEY, key);
3562
3563 if (value instanceof Boolean) {
3564 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
3565 serializer.text(value.toString());
3566 } else if (value instanceof Integer) {
3567 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
3568 serializer.text(value.toString());
3569 } else if (value == null || value instanceof String) {
3570 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
3571 serializer.text(value != null ? (String) value : "");
3572 } else if (value instanceof Bundle) {
3573 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
3574 writeBundle((Bundle) value, serializer);
3575 } else if (value instanceof Parcelable[]) {
3576 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
3577 Parcelable[] array = (Parcelable[]) value;
3578 for (Parcelable parcelable : array) {
3579 if (!(parcelable instanceof Bundle)) {
3580 throw new IllegalArgumentException("bundle-array can only hold Bundles");
3581 }
3582 serializer.startTag(null, TAG_ENTRY);
3583 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
3584 writeBundle((Bundle) parcelable, serializer);
3585 serializer.endTag(null, TAG_ENTRY);
3586 }
3587 } else {
3588 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
3589 String[] values = (String[]) value;
3590 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
3591 for (String choice : values) {
3592 serializer.startTag(null, TAG_VALUE);
3593 serializer.text(choice != null ? choice : "");
3594 serializer.endTag(null, TAG_VALUE);
3595 }
3596 }
3597 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003598 }
3599 }
3600
3601 @Override
Bookatzf56f2582019-09-04 16:06:41 -07003602 public int getUserSerialNumber(@UserIdInt int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003603 synchronized (mUsersLock) {
Bookatzf56f2582019-09-04 16:06:41 -07003604 final UserInfo userInfo = getUserInfoLU(userId);
Pavel Grafov9c295d42019-03-26 19:42:08 +00003605 return userInfo != null ? userInfo.serialNumber : -1;
Amith Yamasani2a003292012-08-14 18:25:45 -07003606 }
3607 }
3608
3609 @Override
Bookatzf56f2582019-09-04 16:06:41 -07003610 public boolean isUserNameSet(@UserIdInt int userId) {
Fyodor Kupolov605b12a2017-05-10 15:58:09 -07003611 synchronized (mUsersLock) {
Bookatzf56f2582019-09-04 16:06:41 -07003612 final UserInfo userInfo = getUserInfoLU(userId);
Fyodor Kupolov605b12a2017-05-10 15:58:09 -07003613 return userInfo != null && userInfo.name != null;
3614 }
3615 }
3616
3617 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07003618 public int getUserHandle(int userSerialNumber) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003619 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07003620 for (int userId : mUserIds) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003621 UserInfo info = getUserInfoLU(userId);
Kenny Guy945f8832015-02-10 15:17:26 +00003622 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07003623 }
3624 // Not found
3625 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07003626 }
3627 }
3628
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003629 @Override
Bookatzf56f2582019-09-04 16:06:41 -07003630 public long getUserCreationTime(@UserIdInt int userId) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003631 int callingUserId = UserHandle.getCallingUserId();
3632 UserInfo userInfo = null;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003633 synchronized (mUsersLock) {
Bookatzf56f2582019-09-04 16:06:41 -07003634 if (callingUserId == userId) {
3635 userInfo = getUserInfoLU(userId);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003636 } else {
Bookatzf56f2582019-09-04 16:06:41 -07003637 UserInfo parent = getProfileParentLU(userId);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003638 if (parent != null && parent.id == callingUserId) {
Bookatzf56f2582019-09-04 16:06:41 -07003639 userInfo = getUserInfoLU(userId);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003640 }
3641 }
3642 }
3643 if (userInfo == null) {
Bookatzf56f2582019-09-04 16:06:41 -07003644 throw new SecurityException("userId can only be the calling user or a managed "
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003645 + "profile associated with this user");
3646 }
3647 return userInfo.creationTime;
3648 }
3649
Amith Yamasani0b285492011-04-14 17:35:23 -07003650 /**
3651 * Caches the list of user ids in an array, adjusting the array size when necessary.
3652 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07003653 private void updateUserIds() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003654 int num = 0;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003655 synchronized (mUsersLock) {
3656 final int userSize = mUsers.size();
3657 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003658 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003659 num++;
3660 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003661 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07003662 final int[] newUsers = new int[num];
3663 int n = 0;
3664 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003665 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003666 newUsers[n++] = mUsers.keyAt(i);
3667 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003668 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07003669 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07003670 }
3671 }
3672
3673 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003674 * Called right before a user is started. This gives us a chance to prepare
3675 * app storage and apply any user restrictions.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003676 */
Bookatzf56f2582019-09-04 16:06:41 -07003677 public void onBeforeStartUser(@UserIdInt int userId) {
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003678 UserInfo userInfo = getUserInfo(userId);
3679 if (userInfo == null) {
3680 return;
3681 }
Felipe Leme3aad1be2019-05-31 11:43:12 -07003682 TimingsTraceAndSlog t = new TimingsTraceAndSlog();
3683 t.traceBegin("onBeforeStartUser-" + userId);
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003684 final int userSerial = userInfo.serialNumber;
3685 // Migrate only if build fingerprints mismatch
3686 boolean migrateAppsData = !Build.FINGERPRINT.equals(userInfo.lastLoggedInFingerprint);
Felipe Leme3aad1be2019-05-31 11:43:12 -07003687 t.traceBegin("prepareUserData");
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -08003688 mUserDataPreparer.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_DE);
Felipe Leme3aad1be2019-05-31 11:43:12 -07003689 t.traceEnd();
3690 t.traceBegin("reconcileAppsData");
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003691 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_DE, migrateAppsData);
Felipe Leme3aad1be2019-05-31 11:43:12 -07003692 t.traceEnd();
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003693
3694 if (userId != UserHandle.USER_SYSTEM) {
Felipe Leme3aad1be2019-05-31 11:43:12 -07003695 t.traceBegin("applyUserRestrictions");
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003696 synchronized (mRestrictionsLock) {
3697 applyUserRestrictionsLR(userId);
3698 }
Felipe Leme3aad1be2019-05-31 11:43:12 -07003699 t.traceEnd();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003700 }
Felipe Leme3aad1be2019-05-31 11:43:12 -07003701 t.traceEnd(); // onBeforeStartUser
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003702 }
3703
3704 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003705 * Called right before a user is unlocked. This gives us a chance to prepare
3706 * app storage.
3707 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003708 public void onBeforeUnlockUser(@UserIdInt int userId) {
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003709 UserInfo userInfo = getUserInfo(userId);
3710 if (userInfo == null) {
3711 return;
3712 }
3713 final int userSerial = userInfo.serialNumber;
3714 // Migrate only if build fingerprints mismatch
3715 boolean migrateAppsData = !Build.FINGERPRINT.equals(userInfo.lastLoggedInFingerprint);
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -08003716 mUserDataPreparer.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_CE);
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003717 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_CE, migrateAppsData);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003718 }
3719
3720 /**
Fyodor Kupolov50979d12017-01-27 17:36:32 -08003721 * Examine all users present on given mounted volume, and destroy data
3722 * belonging to users that are no longer valid, or whose user ID has been
3723 * recycled.
3724 */
3725 void reconcileUsers(String volumeUuid) {
3726 mUserDataPreparer.reconcileUsers(volumeUuid, getUsers(true /* excludeDying */));
3727 }
3728
3729 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07003730 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasanieb437d42016-04-29 09:31:25 -07003731 * This is called with ActivityManagerService lock held.
Amith Yamasani920ace02012-09-20 22:15:37 -07003732 * @param userId the user that was just foregrounded
3733 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003734 public void onUserLoggedIn(@UserIdInt int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -08003735 UserData userData = getUserDataNoChecks(userId);
3736 if (userData == null || userData.info.partial) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003737 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
3738 return;
3739 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003740
3741 final long now = System.currentTimeMillis();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003742 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani12747872015-12-07 14:19:49 -08003743 userData.info.lastLoggedInTime = now;
Amith Yamasani920ace02012-09-20 22:15:37 -07003744 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003745 userData.info.lastLoggedInFingerprint = Build.FINGERPRINT;
3746 scheduleWriteUser(userData);
Amith Yamasani920ace02012-09-20 22:15:37 -07003747 }
3748
3749 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07003750 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani0b285492011-04-14 17:35:23 -07003751 */
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003752 @VisibleForTesting
3753 int getNextAvailableId() {
3754 int nextId;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003755 synchronized (mUsersLock) {
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003756 nextId = scanNextAvailableIdLocked();
3757 if (nextId >= 0) {
3758 return nextId;
3759 }
3760 // All ids up to MAX_USER_ID were used. Remove all mRemovingUserIds,
3761 // except most recently removed
3762 if (mRemovingUserIds.size() > 0) {
3763 Slog.i(LOG_TAG, "All available IDs are used. Recycling LRU ids.");
3764 mRemovingUserIds.clear();
3765 for (Integer recentlyRemovedId : mRecentlyRemovedIds) {
3766 mRemovingUserIds.put(recentlyRemovedId, true);
Amith Yamasani195263742012-08-21 15:40:12 -07003767 }
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003768 nextId = scanNextAvailableIdLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003769 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003770 }
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003771 if (nextId < 0) {
3772 throw new IllegalStateException("No user id available!");
3773 }
3774 return nextId;
3775 }
3776
Andreas Gampea36dc622018-02-05 17:19:22 -08003777 @GuardedBy("mUsersLock")
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003778 private int scanNextAvailableIdLocked() {
3779 for (int i = MIN_USER_ID; i < MAX_USER_ID; i++) {
3780 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
3781 return i;
3782 }
3783 }
3784 return -1;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003785 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003786
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003787 private static String packageToRestrictionsFileName(String packageName) {
Amith Yamasanifc95e702013-09-26 13:20:17 -07003788 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
3789 }
3790
Amith Yamasani920ace02012-09-20 22:15:37 -07003791 @Override
Bookatzf56f2582019-09-04 16:06:41 -07003792 public void setSeedAccountData(@UserIdInt int userId, String accountName, String accountType,
Amith Yamasani12747872015-12-07 14:19:49 -08003793 PersistableBundle accountOptions, boolean persist) {
3794 checkManageUsersPermission("Require MANAGE_USERS permission to set user seed data");
3795 synchronized (mPackagesLock) {
3796 final UserData userData;
3797 synchronized (mUsersLock) {
3798 userData = getUserDataLU(userId);
3799 if (userData == null) {
3800 Slog.e(LOG_TAG, "No such user for settings seed data u=" + userId);
3801 return;
3802 }
3803 userData.seedAccountName = accountName;
3804 userData.seedAccountType = accountType;
3805 userData.seedAccountOptions = accountOptions;
3806 userData.persistSeedData = persist;
3807 }
3808 if (persist) {
3809 writeUserLP(userData);
3810 }
3811 }
3812 }
3813
3814 @Override
3815 public String getSeedAccountName() throws RemoteException {
3816 checkManageUsersPermission("Cannot get seed account information");
3817 synchronized (mUsersLock) {
3818 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3819 return userData.seedAccountName;
3820 }
3821 }
3822
3823 @Override
3824 public String getSeedAccountType() throws RemoteException {
3825 checkManageUsersPermission("Cannot get seed account information");
3826 synchronized (mUsersLock) {
3827 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3828 return userData.seedAccountType;
3829 }
3830 }
3831
3832 @Override
3833 public PersistableBundle getSeedAccountOptions() throws RemoteException {
3834 checkManageUsersPermission("Cannot get seed account information");
3835 synchronized (mUsersLock) {
3836 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3837 return userData.seedAccountOptions;
3838 }
3839 }
3840
3841 @Override
3842 public void clearSeedAccountData() throws RemoteException {
3843 checkManageUsersPermission("Cannot clear seed account information");
3844 synchronized (mPackagesLock) {
3845 UserData userData;
3846 synchronized (mUsersLock) {
3847 userData = getUserDataLU(UserHandle.getCallingUserId());
3848 if (userData == null) return;
3849 userData.clearSeedAccountData();
3850 }
3851 writeUserLP(userData);
3852 }
3853 }
3854
3855 @Override
3856 public boolean someUserHasSeedAccount(String accountName, String accountType)
3857 throws RemoteException {
3858 checkManageUsersPermission("Cannot check seed account information");
3859 synchronized (mUsersLock) {
3860 final int userSize = mUsers.size();
3861 for (int i = 0; i < userSize; i++) {
3862 final UserData data = mUsers.valueAt(i);
3863 if (data.info.isInitialized()) continue;
3864 if (data.seedAccountName == null || !data.seedAccountName.equals(accountName)) {
3865 continue;
3866 }
3867 if (data.seedAccountType == null || !data.seedAccountType.equals(accountType)) {
3868 continue;
3869 }
3870 return true;
3871 }
3872 }
3873 return false;
3874 }
3875
3876 @Override
Todd Kennedy60459ab2015-10-30 11:32:16 -07003877 public void onShellCommand(FileDescriptor in, FileDescriptor out,
Dianne Hackborn354736e2016-08-22 17:00:05 -07003878 FileDescriptor err, String[] args, ShellCallback callback,
3879 ResultReceiver resultReceiver) {
3880 (new Shell()).exec(this, in, out, err, args, callback, resultReceiver);
Todd Kennedy60459ab2015-10-30 11:32:16 -07003881 }
3882
3883 int onShellCommand(Shell shell, String cmd) {
3884 if (cmd == null) {
3885 return shell.handleDefaultCommands(cmd);
3886 }
3887
3888 final PrintWriter pw = shell.getOutPrintWriter();
3889 try {
3890 switch(cmd) {
3891 case "list":
Felipe Lemec1ca4412019-09-11 09:23:26 -07003892 return runList(pw, shell);
Hui Yu8ba65972018-04-16 18:45:48 -07003893 default:
3894 return shell.handleDefaultCommands(cmd);
Todd Kennedy60459ab2015-10-30 11:32:16 -07003895 }
3896 } catch (RemoteException e) {
3897 pw.println("Remote exception: " + e);
3898 }
3899 return -1;
3900 }
3901
Felipe Lemec1ca4412019-09-11 09:23:26 -07003902 private int runList(PrintWriter pw, Shell shell) throws RemoteException {
3903 boolean all = false;
3904 boolean verbose = false;
3905 String opt;
3906 while ((opt = shell.getNextOption()) != null) {
3907 switch (opt) {
3908 case "-v":
3909 verbose = true;
3910 break;
3911 case "--all":
3912 all = true;
3913 break;
3914 default:
3915 pw.println("Invalid option: " + opt);
3916 return -1;
3917 }
3918 }
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003919 final IActivityManager am = ActivityManager.getService();
Felipe Lemec1ca4412019-09-11 09:23:26 -07003920 final List<UserInfo> users = getUsers(/* excludePartial= */ !all,
3921 /* excludingDying=*/ false, /* excludePreCreated= */ !all);
Todd Kennedy60459ab2015-10-30 11:32:16 -07003922 if (users == null) {
3923 pw.println("Error: couldn't get users");
3924 return 1;
3925 } else {
Felipe Lemec1ca4412019-09-11 09:23:26 -07003926 final int size = users.size();
3927 int currentUser = UserHandle.USER_NULL;
3928 if (verbose) {
3929 pw.printf("%d users:\n\n", size);
3930 currentUser = am.getCurrentUser().id;
3931 } else {
3932 // NOTE: the standard "list users" command is used by integration tests and
3933 // hence should not be changed. If you need to add more info, use the
3934 // verbose option.
3935 pw.println("Users:");
3936 }
3937 for (int i = 0; i < size; i++) {
3938 final UserInfo user = users.get(i);
3939 final boolean running = am.isUserRunning(user.id, 0);
3940 final boolean current = user.id == currentUser;
3941 if (verbose) {
3942 pw.printf("%d: id=%d, name=%s, flags=%s%s%s%s%s\n", i, user.id, user.name,
3943 UserInfo.flagsToString(user.flags),
3944 running ? " (running)" : "",
3945 user.partial ? " (partial)" : "",
3946 user.preCreated ? " (pre-created)" : "",
3947 current ? " (current)" : "");
3948 } else {
3949 // NOTE: the standard "list users" command is used by integration tests and
3950 // hence should not be changed. If you need to add more info, use the
3951 // verbose option.
3952 pw.printf("\t%s%s\n", user, running ? " running" : "");
3953 }
Todd Kennedy60459ab2015-10-30 11:32:16 -07003954 }
3955 return 0;
3956 }
3957 }
3958
3959 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -07003960 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06003961 if (!DumpUtils.checkDumpPermission(mContext, LOG_TAG, pw)) return;
Amith Yamasani920ace02012-09-20 22:15:37 -07003962
3963 long now = System.currentTimeMillis();
Makoto Onuki73dded22017-12-20 13:14:48 +09003964 final long nowRealtime = SystemClock.elapsedRealtime();
Felipe Lemed7b88382019-06-12 17:40:53 -07003965
3966 final int currentUser = LocalServices.getService(ActivityManagerInternal.class)
3967 .getCurrentUserId();
3968 pw.print("Current user: "); pw.println(currentUser);
3969
Amith Yamasani920ace02012-09-20 22:15:37 -07003970 StringBuilder sb = new StringBuilder();
3971 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003972 synchronized (mUsersLock) {
3973 pw.println("Users:");
3974 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003975 UserData userData = mUsers.valueAt(i);
3976 if (userData == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003977 continue;
3978 }
Amith Yamasani12747872015-12-07 14:19:49 -08003979 UserInfo userInfo = userData.info;
3980 final int userId = userInfo.id;
3981 pw.print(" "); pw.print(userInfo);
3982 pw.print(" serialNo="); pw.print(userInfo.serialNumber);
Felipe Lemed7b88382019-06-12 17:40:53 -07003983 pw.print(" isPrimary="); pw.print(userInfo.isPrimary());
Makoto Onukie7927da2015-11-25 10:05:17 -08003984 if (mRemovingUserIds.get(userId)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003985 pw.print(" <removing> ");
3986 }
Amith Yamasani12747872015-12-07 14:19:49 -08003987 if (userInfo.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003988 pw.print(" <partial>");
3989 }
Felipe Lemec1ca4412019-09-11 09:23:26 -07003990 if (userInfo.preCreated) {
3991 pw.print(" <pre-created>");
3992 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07003993 pw.println();
Felipe Lemee5434c32019-08-13 09:28:33 -07003994 pw.print(" Flags: "); pw.print(userInfo.flags); pw.print(" (");
3995 pw.print(UserInfo.flagsToString(userInfo.flags)); pw.println(")");
Makoto Onuki88aef752017-03-29 16:52:03 -07003996 pw.print(" State: ");
3997 final int state;
3998 synchronized (mUserStates) {
3999 state = mUserStates.get(userId, -1);
4000 }
4001 pw.println(UserState.stateToString(state));
Fyodor Kupolov82402752015-10-28 14:54:51 -07004002 pw.print(" Created: ");
Makoto Onuki73dded22017-12-20 13:14:48 +09004003 dumpTimeAgo(pw, sb, now, userInfo.creationTime);
4004
Fyodor Kupolov82402752015-10-28 14:54:51 -07004005 pw.print(" Last logged in: ");
Makoto Onuki73dded22017-12-20 13:14:48 +09004006 dumpTimeAgo(pw, sb, now, userInfo.lastLoggedInTime);
4007
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06004008 pw.print(" Last logged in fingerprint: ");
4009 pw.println(userInfo.lastLoggedInFingerprint);
Makoto Onuki73dded22017-12-20 13:14:48 +09004010
4011 pw.print(" Start time: ");
4012 dumpTimeAgo(pw, sb, nowRealtime, userData.startRealtime);
4013
4014 pw.print(" Unlock time: ");
4015 dumpTimeAgo(pw, sb, nowRealtime, userData.unlockRealtime);
4016
Makoto Onukie7927da2015-11-25 10:05:17 -08004017 pw.print(" Has profile owner: ");
4018 pw.println(mIsUserManaged.get(userId));
Fyodor Kupolov82402752015-10-28 14:54:51 -07004019 pw.println(" Restrictions:");
4020 synchronized (mRestrictionsLock) {
4021 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08004022 pw, " ", mBaseUserRestrictions.get(userInfo.id));
Pavel Grafov6a40f092016-10-25 15:46:51 +01004023 pw.println(" Device policy global restrictions:");
4024 UserRestrictionsUtils.dumpRestrictions(
4025 pw, " ", mDevicePolicyGlobalUserRestrictions.get(userInfo.id));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08004026 pw.println(" Device policy local restrictions:");
4027 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08004028 pw, " ", mDevicePolicyLocalUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07004029 pw.println(" Effective restrictions:");
4030 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08004031 pw, " ", mCachedEffectiveUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07004032 }
Amith Yamasani12747872015-12-07 14:19:49 -08004033
4034 if (userData.account != null) {
4035 pw.print(" Account name: " + userData.account);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08004036 pw.println();
4037 }
Amith Yamasani12747872015-12-07 14:19:49 -08004038
4039 if (userData.seedAccountName != null) {
4040 pw.print(" Seed account name: " + userData.seedAccountName);
4041 pw.println();
4042 if (userData.seedAccountType != null) {
4043 pw.print(" account type: " + userData.seedAccountType);
4044 pw.println();
4045 }
4046 if (userData.seedAccountOptions != null) {
4047 pw.print(" account options exist");
4048 pw.println();
4049 }
4050 }
Amith Yamasani920ace02012-09-20 22:15:37 -07004051 }
Amith Yamasani920ace02012-09-20 22:15:37 -07004052 }
Amith Yamasani12747872015-12-07 14:19:49 -08004053 pw.println();
Pavel Grafov6a40f092016-10-25 15:46:51 +01004054 pw.println(" Device owner id:" + mDeviceOwnerUserId);
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01004055 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08004056 pw.println(" Guest restrictions:");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08004057 synchronized (mGuestRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08004058 UserRestrictionsUtils.dumpRestrictions(pw, " ", mGuestRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08004059 }
Makoto Onukie7927da2015-11-25 10:05:17 -08004060 synchronized (mUsersLock) {
4061 pw.println();
4062 pw.println(" Device managed: " + mIsDeviceManaged);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07004063 if (mRemovingUserIds.size() > 0) {
4064 pw.println();
4065 pw.println(" Recently removed userIds: " + mRecentlyRemovedIds);
4066 }
Makoto Onukie7927da2015-11-25 10:05:17 -08004067 }
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00004068 synchronized (mUserStates) {
4069 pw.println(" Started users state: " + mUserStates);
4070 }
Felipe Lemed7b88382019-06-12 17:40:53 -07004071 } // synchronized (mPackagesLock)
4072
4073 // Dump some capabilities
4074 pw.println();
Felipe Lemec1ca4412019-09-11 09:23:26 -07004075 pw.print(" Max users: " + UserManager.getMaxSupportedUsers());
4076 pw.println(" (limit reached: " + isUserLimitReached() + ")");
Felipe Lemed7b88382019-06-12 17:40:53 -07004077 pw.println(" Supports switchable users: " + UserManager.supportsMultipleUsers());
Felipe Lemec1ca4412019-09-11 09:23:26 -07004078 pw.println(" All guests ephemeral: " + areGuestUsersEphemeral());
Felipe Lemed7b88382019-06-12 17:40:53 -07004079 pw.println(" Is split-system user: " + UserManager.isSplitSystemUser());
Felipe Lemee5434c32019-08-13 09:28:33 -07004080 pw.println(" Is headless-system mode: " + UserManager.isHeadlessSystemUserMode());
4081 pw.println(" User version: " + mUserVersion);
Bookatz04d7ae52019-08-05 14:07:12 -07004082
4083 // Dump package whitelist
4084 pw.println();
4085 mSystemPackageInstaller.dump(pw);
Amith Yamasani920ace02012-09-20 22:15:37 -07004086 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08004087
Makoto Onuki73dded22017-12-20 13:14:48 +09004088 private static void dumpTimeAgo(PrintWriter pw, StringBuilder sb, long nowTime, long time) {
4089 if (time == 0) {
4090 pw.println("<unknown>");
4091 } else {
4092 sb.setLength(0);
4093 TimeUtils.formatDuration(nowTime - time, sb);
4094 sb.append(" ago");
4095 pw.println(sb);
4096 }
4097 }
4098
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08004099 final class MainHandler extends Handler {
4100
4101 @Override
4102 public void handleMessage(Message msg) {
4103 switch (msg.what) {
4104 case WRITE_USER_MSG:
4105 removeMessages(WRITE_USER_MSG, msg.obj);
4106 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08004107 int userId = ((UserData) msg.obj).info.id;
4108 UserData userData = getUserDataNoChecks(userId);
4109 if (userData != null) {
4110 writeUserLP(userData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08004111 }
4112 }
4113 }
4114 }
4115 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07004116
4117 /**
4118 * @param userId
4119 * @return whether the user has been initialized yet
4120 */
Bookatzf56f2582019-09-04 16:06:41 -07004121 boolean isUserInitialized(@UserIdInt int userId) {
Todd Kennedy0eb97382017-10-03 16:57:22 -07004122 return mLocalService.isUserInitialized(userId);
Amith Yamasanibb054c92015-07-09 14:16:27 -07004123 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07004124
4125 private class LocalService extends UserManagerInternal {
Makoto Onuki068c54a2015-10-13 14:34:03 -07004126 @Override
Bookatzf56f2582019-09-04 16:06:41 -07004127 public void setDevicePolicyUserRestrictions(@UserIdInt int userId,
4128 @Nullable Bundle restrictions, boolean isDeviceOwner, int cameraRestrictionScope) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01004129 UserManagerService.this.setDevicePolicyUserRestrictionsInner(userId, restrictions,
4130 isDeviceOwner, cameraRestrictionScope);
Makoto Onuki068c54a2015-10-13 14:34:03 -07004131 }
4132
4133 @Override
Bookatzf56f2582019-09-04 16:06:41 -07004134 public Bundle getBaseUserRestrictions(@UserIdInt int userId) {
Makoto Onuki068c54a2015-10-13 14:34:03 -07004135 synchronized (mRestrictionsLock) {
4136 return mBaseUserRestrictions.get(userId);
4137 }
4138 }
4139
4140 @Override
4141 public void setBaseUserRestrictionsByDpmsForMigration(
Bookatzf56f2582019-09-04 16:06:41 -07004142 @UserIdInt int userId, Bundle baseRestrictions) {
Makoto Onuki068c54a2015-10-13 14:34:03 -07004143 synchronized (mRestrictionsLock) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01004144 if (updateRestrictionsIfNeededLR(
4145 userId, new Bundle(baseRestrictions), mBaseUserRestrictions)) {
4146 invalidateEffectiveUserRestrictionsLR(userId);
4147 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07004148 }
4149
Amith Yamasani12747872015-12-07 14:19:49 -08004150 final UserData userData = getUserDataNoChecks(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07004151 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08004152 if (userData != null) {
4153 writeUserLP(userData);
Makoto Onuki068c54a2015-10-13 14:34:03 -07004154 } else {
4155 Slog.w(LOG_TAG, "UserInfo not found for " + userId);
4156 }
4157 }
4158 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08004159
4160 @Override
Bookatzf56f2582019-09-04 16:06:41 -07004161 public boolean getUserRestriction(@UserIdInt int userId, String key) {
Makoto Onukid45a4a22015-11-02 17:17:38 -08004162 return getUserRestrictions(userId).getBoolean(key);
4163 }
4164
4165 @Override
4166 public void addUserRestrictionsListener(UserRestrictionsListener listener) {
4167 synchronized (mUserRestrictionsListeners) {
4168 mUserRestrictionsListeners.add(listener);
4169 }
4170 }
4171
4172 @Override
4173 public void removeUserRestrictionsListener(UserRestrictionsListener listener) {
4174 synchronized (mUserRestrictionsListeners) {
4175 mUserRestrictionsListeners.remove(listener);
4176 }
4177 }
Makoto Onukie7927da2015-11-25 10:05:17 -08004178
4179 @Override
4180 public void setDeviceManaged(boolean isManaged) {
4181 synchronized (mUsersLock) {
4182 mIsDeviceManaged = isManaged;
4183 }
4184 }
4185
4186 @Override
Rubin Xu0f1e56d2019-08-23 13:34:25 +01004187 public boolean isDeviceManaged() {
4188 synchronized (mUsersLock) {
4189 return mIsDeviceManaged;
4190 }
4191 }
4192
4193 @Override
Bookatzf56f2582019-09-04 16:06:41 -07004194 public void setUserManaged(@UserIdInt int userId, boolean isManaged) {
Makoto Onukie7927da2015-11-25 10:05:17 -08004195 synchronized (mUsersLock) {
4196 mIsUserManaged.put(userId, isManaged);
4197 }
4198 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01004199
4200 @Override
Rubin Xu0f1e56d2019-08-23 13:34:25 +01004201 public boolean isUserManaged(@UserIdInt int userId) {
4202 synchronized (mUsersLock) {
4203 return mIsUserManaged.get(userId);
4204 }
4205 }
4206
4207 @Override
Bookatzf56f2582019-09-04 16:06:41 -07004208 public void setUserIcon(@UserIdInt int userId, Bitmap bitmap) {
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01004209 long ident = Binder.clearCallingIdentity();
4210 try {
4211 synchronized (mPackagesLock) {
4212 UserData userData = getUserDataNoChecks(userId);
4213 if (userData == null || userData.info.partial) {
4214 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
4215 return;
4216 }
4217 writeBitmapLP(userData.info, bitmap);
4218 writeUserLP(userData);
4219 }
4220 sendUserInfoChangedBroadcast(userId);
4221 } finally {
4222 Binder.restoreCallingIdentity(ident);
4223 }
4224 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01004225
4226 @Override
4227 public void setForceEphemeralUsers(boolean forceEphemeralUsers) {
4228 synchronized (mUsersLock) {
4229 mForceEphemeralUsers = forceEphemeralUsers;
4230 }
4231 }
4232
4233 @Override
4234 public void removeAllUsers() {
4235 if (UserHandle.USER_SYSTEM == ActivityManager.getCurrentUser()) {
4236 // Remove the non-system users straight away.
4237 removeNonSystemUsers();
4238 } else {
4239 // Switch to the system user first and then remove the other users.
4240 BroadcastReceiver userSwitchedReceiver = new BroadcastReceiver() {
4241 @Override
4242 public void onReceive(Context context, Intent intent) {
4243 int userId =
4244 intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
4245 if (userId != UserHandle.USER_SYSTEM) {
4246 return;
4247 }
4248 mContext.unregisterReceiver(this);
4249 removeNonSystemUsers();
4250 }
4251 };
4252 IntentFilter userSwitchedFilter = new IntentFilter();
4253 userSwitchedFilter.addAction(Intent.ACTION_USER_SWITCHED);
4254 mContext.registerReceiver(
4255 userSwitchedReceiver, userSwitchedFilter, null, mHandler);
4256
4257 // Switch to the system user.
4258 ActivityManager am =
4259 (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
4260 am.switchUser(UserHandle.USER_SYSTEM);
4261 }
4262 }
phweisse9c44062016-02-10 12:57:38 +01004263
4264 @Override
Bookatzf56f2582019-09-04 16:06:41 -07004265 public void onEphemeralUserStop(@UserIdInt int userId) {
Lenka Trochtova1ddda472016-02-12 10:42:12 +01004266 synchronized (mUsersLock) {
4267 UserInfo userInfo = getUserInfoLU(userId);
4268 if (userInfo != null && userInfo.isEphemeral()) {
4269 // Do not allow switching back to the ephemeral user again as the user is going
4270 // to be deleted.
4271 userInfo.flags |= UserInfo.FLAG_DISABLED;
4272 if (userInfo.isGuest()) {
4273 // Indicate that the guest will be deleted after it stops.
4274 userInfo.guestToRemove = true;
4275 }
4276 }
4277 }
4278 }
4279
4280 @Override
Alex Chaub6a9f942017-11-07 11:28:56 +08004281 public UserInfo createUserEvenWhenDisallowed(String name, int flags,
4282 String[] disallowedPackages) {
4283 UserInfo user = createUserInternalUnchecked(name, flags, UserHandle.USER_NULL,
Felipe Lemec1ca4412019-09-11 09:23:26 -07004284 /* preCreated= */ false, disallowedPackages);
phweisse9c44062016-02-10 12:57:38 +01004285 // Keep this in sync with UserManager.createUser
Christine Franks97a54802017-08-09 10:06:43 -07004286 if (user != null && !user.isAdmin() && !user.isDemo()) {
phweisse9c44062016-02-10 12:57:38 +01004287 setUserRestriction(UserManager.DISALLOW_SMS, true, user.id);
4288 setUserRestriction(UserManager.DISALLOW_OUTGOING_CALLS, true, user.id);
4289 }
4290 return user;
4291 }
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07004292
4293 @Override
Bookatzf56f2582019-09-04 16:06:41 -07004294 public boolean removeUserEvenWhenDisallowed(@UserIdInt int userId) {
Nicolas Prevotdf1b87d2016-10-25 13:57:08 +01004295 return removeUserUnchecked(userId);
4296 }
4297
4298 @Override
Bookatzf56f2582019-09-04 16:06:41 -07004299 public boolean isUserRunning(@UserIdInt int userId) {
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00004300 synchronized (mUserStates) {
4301 return mUserStates.get(userId, -1) >= 0;
4302 }
4303 }
4304
4305 @Override
Bookatzf56f2582019-09-04 16:06:41 -07004306 public void setUserState(@UserIdInt int userId, int userState) {
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00004307 synchronized (mUserStates) {
4308 mUserStates.put(userId, userState);
4309 }
4310 }
4311
4312 @Override
Bookatzf56f2582019-09-04 16:06:41 -07004313 public void removeUserState(@UserIdInt int userId) {
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00004314 synchronized (mUserStates) {
4315 mUserStates.delete(userId);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07004316 }
4317 }
4318
4319 @Override
Michael Wachenschwanz3f2b6552017-05-15 13:53:09 -07004320 public int[] getUserIds() {
4321 return UserManagerService.this.getUserIds();
4322 }
4323
4324 @Override
Bookatzf56f2582019-09-04 16:06:41 -07004325 public boolean isUserUnlockingOrUnlocked(@UserIdInt int userId) {
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07004326 int state;
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00004327 synchronized (mUserStates) {
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07004328 state = mUserStates.get(userId, -1);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07004329 }
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07004330 // Special case, in the stopping/shutdown state user key can still be unlocked
4331 if (state == UserState.STATE_STOPPING || state == UserState.STATE_SHUTDOWN) {
4332 return StorageManager.isUserKeyUnlocked(userId);
4333 }
4334 return (state == UserState.STATE_RUNNING_UNLOCKING)
4335 || (state == UserState.STATE_RUNNING_UNLOCKED);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07004336 }
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08004337
4338 @Override
Bookatzf56f2582019-09-04 16:06:41 -07004339 public boolean isUserUnlocked(@UserIdInt int userId) {
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07004340 int state;
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08004341 synchronized (mUserStates) {
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07004342 state = mUserStates.get(userId, -1);
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08004343 }
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07004344 // Special case, in the stopping/shutdown state user key can still be unlocked
4345 if (state == UserState.STATE_STOPPING || state == UserState.STATE_SHUTDOWN) {
4346 return StorageManager.isUserKeyUnlocked(userId);
4347 }
4348 return state == UserState.STATE_RUNNING_UNLOCKED;
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08004349 }
Todd Kennedy0eb97382017-10-03 16:57:22 -07004350
4351 @Override
Bookatzf56f2582019-09-04 16:06:41 -07004352 public boolean isUserInitialized(@UserIdInt int userId) {
Todd Kennedy0eb97382017-10-03 16:57:22 -07004353 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
4354 }
4355
4356 @Override
Bookatzf56f2582019-09-04 16:06:41 -07004357 public boolean exists(@UserIdInt int userId) {
Todd Kennedy0eb97382017-10-03 16:57:22 -07004358 return getUserInfoNoChecks(userId) != null;
4359 }
Sunny Goyal145c8f82018-02-15 14:27:09 -08004360
4361 @Override
4362 public boolean isProfileAccessible(int callingUserId, int targetUserId, String debugMsg,
4363 boolean throwSecurityException) {
4364 if (targetUserId == callingUserId) {
4365 return true;
4366 }
4367 synchronized (mUsersLock) {
4368 UserInfo callingUserInfo = getUserInfoLU(callingUserId);
4369 if (callingUserInfo == null || callingUserInfo.isManagedProfile()) {
4370 if (throwSecurityException) {
4371 throw new SecurityException(
4372 debugMsg + " for another profile "
4373 + targetUserId + " from " + callingUserId);
4374 }
4375 }
4376
4377 UserInfo targetUserInfo = getUserInfoLU(targetUserId);
4378 if (targetUserInfo == null || !targetUserInfo.isEnabled()) {
4379 // Do not throw any exception here as this could happen due to race conditions
4380 // between the system updating its state and the client getting notified.
4381 if (throwSecurityException) {
4382 Slog.w(LOG_TAG, debugMsg + " for disabled profile "
4383 + targetUserId + " from " + callingUserId);
4384 }
4385 return false;
4386 }
4387
4388 if (targetUserInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID ||
4389 targetUserInfo.profileGroupId != callingUserInfo.profileGroupId) {
4390 if (throwSecurityException) {
4391 throw new SecurityException(
4392 debugMsg + " for unrelated profile " + targetUserId);
4393 }
4394 return false;
4395 }
4396 }
4397 return true;
4398 }
4399
4400 @Override
Bookatzf56f2582019-09-04 16:06:41 -07004401 public int getProfileParentId(@UserIdInt int userId) {
Sunny Goyal145c8f82018-02-15 14:27:09 -08004402 synchronized (mUsersLock) {
4403 UserInfo profileParent = getProfileParentLU(userId);
4404 if (profileParent == null) {
4405 return userId;
4406 }
4407 return profileParent.id;
4408 }
4409 }
yuemingw1d13eae2018-01-30 17:27:54 +00004410
4411 @Override
4412 public boolean isSettingRestrictedForUser(String setting, @UserIdInt int userId,
4413 String value, int callingUid) {
4414 return UserRestrictionsUtils.isSettingRestrictedForUser(mContext, setting, userId,
4415 value, callingUid);
4416 }
Patrick Baumann2f2fd712019-07-31 15:18:53 -07004417
4418 @Override
Bookatzf56f2582019-09-04 16:06:41 -07004419 public boolean hasUserRestriction(String restrictionKey, @UserIdInt int userId) {
Patrick Baumann2f2fd712019-07-31 15:18:53 -07004420 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
4421 return false;
4422 }
4423 Bundle restrictions = getEffectiveUserRestrictions(userId);
4424 return restrictions != null && restrictions.getBoolean(restrictionKey);
4425 }
Felipe Lemee5434c32019-08-13 09:28:33 -07004426
Rubin Xu0f1e56d2019-08-23 13:34:25 +01004427 @Override
Felipe Lemee5434c32019-08-13 09:28:33 -07004428 public @Nullable UserInfo getUserInfo(@UserIdInt int userId) {
4429 UserData userData;
4430 synchronized (mUsersLock) {
4431 userData = mUsers.get(userId);
4432 }
4433 return userData == null ? null : userData.info;
4434 }
Felipe Leme987655d2019-08-26 10:45:24 -07004435
4436 public @NonNull UserInfo[] getUserInfos() {
4437 synchronized (mUsersLock) {
4438 int userSize = mUsers.size();
4439 UserInfo[] allInfos = new UserInfo[userSize];
4440 for (int i = 0; i < userSize; i++) {
4441 allInfos[i] = mUsers.valueAt(i).info;
4442 }
4443 return allInfos;
4444 }
4445 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01004446 }
4447
4448 /* Remove all the users except of the system one. */
4449 private void removeNonSystemUsers() {
4450 ArrayList<UserInfo> usersToRemove = new ArrayList<>();
4451 synchronized (mUsersLock) {
4452 final int userSize = mUsers.size();
4453 for (int i = 0; i < userSize; i++) {
4454 UserInfo ui = mUsers.valueAt(i).info;
4455 if (ui.id != UserHandle.USER_SYSTEM) {
4456 usersToRemove.add(ui);
4457 }
4458 }
4459 }
4460 for (UserInfo ui: usersToRemove) {
4461 removeUser(ui.id);
4462 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07004463 }
Todd Kennedy60459ab2015-10-30 11:32:16 -07004464
4465 private class Shell extends ShellCommand {
4466 @Override
4467 public int onCommand(String cmd) {
4468 return onShellCommand(this, cmd);
4469 }
4470
4471 @Override
4472 public void onHelp() {
4473 final PrintWriter pw = getOutPrintWriter();
4474 pw.println("User manager (user) commands:");
4475 pw.println(" help");
4476 pw.println(" Print this help text.");
4477 pw.println("");
Felipe Lemec1ca4412019-09-11 09:23:26 -07004478 pw.println(" list [-v] [-all]");
Todd Kennedy60459ab2015-10-30 11:32:16 -07004479 pw.println(" Prints all users on the system.");
4480 }
4481 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08004482
4483 private static void debug(String message) {
4484 Log.d(LOG_TAG, message +
4485 (DBG_WITH_STACKTRACE ? " called at\n" + Debug.getCallers(10, " ") : ""));
4486 }
Kenny Guy02c89902016-11-15 19:36:38 +00004487
4488 @VisibleForTesting
4489 static int getMaxManagedProfiles() {
4490 // Allow overriding max managed profiles on debuggable builds for testing
4491 // of multiple profiles.
4492 if (!Build.IS_DEBUGGABLE) {
4493 return MAX_MANAGED_PROFILES;
4494 } else {
4495 return SystemProperties.getInt("persist.sys.max_profiles",
4496 MAX_MANAGED_PROFILES);
4497 }
4498 }
4499
Andreas Gampe2e8c7672018-07-20 13:01:08 -07004500 @GuardedBy("mUsersLock")
Kenny Guy02c89902016-11-15 19:36:38 +00004501 @VisibleForTesting
4502 int getFreeProfileBadgeLU(int parentUserId) {
4503 int maxManagedProfiles = getMaxManagedProfiles();
4504 boolean[] usedBadges = new boolean[maxManagedProfiles];
4505 final int userSize = mUsers.size();
4506 for (int i = 0; i < userSize; i++) {
4507 UserInfo ui = mUsers.valueAt(i).info;
4508 // Check which badge indexes are already used by this profile group.
4509 if (ui.isManagedProfile()
4510 && ui.profileGroupId == parentUserId
4511 && !mRemovingUserIds.get(ui.id)
4512 && ui.profileBadge < maxManagedProfiles) {
4513 usedBadges[ui.profileBadge] = true;
4514 }
4515 }
4516 for (int i = 0; i < maxManagedProfiles; i++) {
4517 if (!usedBadges[i]) {
4518 return i;
4519 }
4520 }
4521 return 0;
4522 }
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07004523
4524 /**
4525 * Checks if the given user has a managed profile associated with it.
4526 * @param userId The parent user
4527 * @return
4528 */
Bookatzf56f2582019-09-04 16:06:41 -07004529 boolean hasManagedProfile(@UserIdInt int userId) {
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07004530 synchronized (mUsersLock) {
4531 UserInfo userInfo = getUserInfoLU(userId);
4532 final int userSize = mUsers.size();
4533 for (int i = 0; i < userSize; i++) {
4534 UserInfo profile = mUsers.valueAt(i).info;
4535 if (userId != profile.id && isProfileOf(userInfo, profile)) {
4536 return true;
4537 }
4538 }
4539 return false;
4540 }
4541 }
Tony Makd390ae92017-12-28 13:23:10 +00004542
4543 /**
4544 * Check if the calling package name matches with the calling UID, throw
4545 * {@link SecurityException} if not.
4546 */
4547 private void verifyCallingPackage(String callingPackage, int callingUid) {
4548 int packageUid = mPm.getPackageUid(callingPackage, 0, UserHandle.getUserId(callingUid));
4549 if (packageUid != callingUid) {
4550 throw new SecurityException("Specified package " + callingPackage
4551 + " does not match the calling uid " + callingUid);
4552 }
4553 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07004554}