blob: 9371c4473bb343f7ca071fb6e53c8b7836e7bb1c [file] [log] [blame]
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
Benjamin Franzf02420c2016-04-04 18:52:21 +010019import static android.content.Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS;
20import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
21
Xiaohui Chenb3b92582015-12-07 11:22:13 -080022import android.Manifest;
Xiaohui Chen594f2082015-08-18 11:04:20 -070023import android.annotation.NonNull;
Makoto Onuki068c54a2015-10-13 14:34:03 -070024import android.annotation.Nullable;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -060025import android.annotation.UserIdInt;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070026import android.app.Activity;
Amith Yamasani2a003292012-08-14 18:25:45 -070027import android.app.ActivityManager;
Amith Yamasani515d4062015-09-28 11:30:06 -070028import android.app.ActivityManagerInternal;
Andrew Scull85a63bc2016-10-24 13:47:47 +010029import android.app.ActivityManagerNative;
Todd Kennedy60459ab2015-10-30 11:32:16 -070030import android.app.IActivityManager;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070031import android.app.IStopUserCallback;
Benjamin Franzf02420c2016-04-04 18:52:21 +010032import android.app.KeyguardManager;
Ricky Waib1dd80b2016-06-07 18:00:55 +010033import android.app.PendingIntent;
arangelov9b632d72018-12-07 23:21:22 +000034import android.app.admin.DevicePolicyEventLogger;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070035import android.content.BroadcastReceiver;
Amith Yamasani258848d2012-08-10 17:06:33 -070036import android.content.Context;
37import android.content.Intent;
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +010038import android.content.IntentFilter;
Benjamin Franzf02420c2016-04-04 18:52:21 +010039import android.content.IntentSender;
Amith Yamasani0b285492011-04-14 17:35:23 -070040import android.content.pm.PackageManager;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -080041import android.content.pm.PackageManager.NameNotFoundException;
Tony Make3d1f652017-12-12 11:00:37 +000042import android.content.pm.ShortcutServiceInternal;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070043import android.content.pm.UserInfo;
Lenka Trochtova02fee152015-12-22 14:26:18 +010044import android.content.res.Resources;
Amith Yamasanie928d7d2012-09-17 21:46:51 -070045import android.graphics.Bitmap;
Amith Yamasani258848d2012-08-10 17:06:33 -070046import android.os.Binder;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -060047import android.os.Build;
Amith Yamasanie4cf7342012-12-17 11:12:09 -080048import android.os.Bundle;
Makoto Onuki1a2cd742015-11-16 13:51:27 -080049import android.os.Debug;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070050import android.os.Environment;
51import android.os.FileUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080052import android.os.Handler;
Svet Ganov9cea80cd2016-02-16 11:47:00 -080053import android.os.IBinder;
Tony Mak64fd8c02017-12-01 19:11:59 +000054import android.os.IProgressListener;
Amith Yamasani258848d2012-08-10 17:06:33 -070055import android.os.IUserManager;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -080056import android.os.Message;
Adrian Roos1bdff912015-02-17 15:51:35 +010057import android.os.ParcelFileDescriptor;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070058import android.os.Parcelable;
Amith Yamasani12747872015-12-07 14:19:49 -080059import android.os.PersistableBundle;
Amith Yamasani258848d2012-08-10 17:06:33 -070060import android.os.Process;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070061import android.os.RemoteException;
Todd Kennedy60459ab2015-10-30 11:32:16 -070062import android.os.ResultReceiver;
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +010063import android.os.SELinux;
Jason Monk62062992014-05-06 09:55:28 -040064import android.os.ServiceManager;
Dianne Hackborn354736e2016-08-22 17:00:05 -070065import android.os.ShellCallback;
Todd Kennedy60459ab2015-10-30 11:32:16 -070066import android.os.ShellCommand;
Makoto Onuki73dded22017-12-20 13:14:48 +090067import android.os.SystemClock;
Kenny Guy02c89902016-11-15 19:36:38 +000068import android.os.SystemProperties;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070069import android.os.UserHandle;
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070070import android.os.UserManager;
Pavel Grafov6a40f092016-10-25 15:46:51 +010071import android.os.UserManager.EnforcingUser;
Makoto Onuki068c54a2015-10-13 14:34:03 -070072import android.os.UserManagerInternal;
Makoto Onukid45a4a22015-11-02 17:17:38 -080073import android.os.UserManagerInternal.UserRestrictionsListener;
Paul Crowley85e4e812015-05-19 12:42:00 +010074import android.os.storage.StorageManager;
Amith Yamasanid04aaa32016-06-13 12:09:36 -070075import android.security.GateKeeper;
76import android.service.gatekeeper.IGateKeeperService;
arangelov9b632d72018-12-07 23:21:22 +000077import android.stats.devicepolicy.DevicePolicyEnums;
Bookatz75f0a072019-08-05 14:12:16 -070078import android.util.ArraySet;
Amith Yamasani2a003292012-08-14 18:25:45 -070079import android.util.AtomicFile;
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -070080import android.util.IntArray;
Amith Yamasani655d0e22013-06-12 14:19:10 -070081import android.util.Log;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070082import android.util.Slog;
83import android.util.SparseArray;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080084import android.util.SparseBooleanArray;
Amith Yamasaniea1b9d72016-05-27 15:57:38 +000085import android.util.SparseIntArray;
Amith Yamasani920ace02012-09-20 22:15:37 -070086import android.util.TimeUtils;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070087import android.util.Xml;
88
Makoto Onuki068c54a2015-10-13 14:34:03 -070089import com.android.internal.annotations.GuardedBy;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070090import com.android.internal.annotations.VisibleForTesting;
Jason Monk62062992014-05-06 09:55:28 -040091import com.android.internal.app.IAppOpsService;
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -080092import com.android.internal.logging.MetricsLogger;
Fyodor Kupolova68a2862018-01-30 18:22:00 -080093import com.android.internal.os.BackgroundThread;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -060094import com.android.internal.util.DumpUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080095import com.android.internal.util.FastXmlSerializer;
Makoto Onuki068c54a2015-10-13 14:34:03 -070096import com.android.internal.util.Preconditions;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070097import com.android.internal.util.XmlUtils;
Clara Bayarri10ad84a2015-12-01 17:38:05 +000098import com.android.internal.widget.LockPatternUtils;
Amith Yamasani515d4062015-09-28 11:30:06 -070099import com.android.server.LocalServices;
Jeff Sharkey5f3e9342017-03-13 14:53:11 -0600100import com.android.server.LockGuard;
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700101import com.android.server.SystemService;
Amith Yamasaniea1b9d72016-05-27 15:57:38 +0000102import com.android.server.am.UserState;
Suprabh Shuklac5e057c2016-08-08 16:22:44 -0700103import com.android.server.storage.DeviceStorageMonitorInternal;
Felipe Leme3aad1be2019-05-31 11:43:12 -0700104import com.android.server.utils.TimingsTraceAndSlog;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700105import com.android.server.wm.ActivityTaskManagerInternal;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800106
arangelov9b632d72018-12-07 23:21:22 +0000107import libcore.io.IoUtils;
108
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800109import org.xmlpull.v1.XmlPullParser;
110import org.xmlpull.v1.XmlPullParserException;
111import org.xmlpull.v1.XmlSerializer;
112
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700113import java.io.BufferedOutputStream;
114import java.io.File;
Amith Yamasani920ace02012-09-20 22:15:37 -0700115import java.io.FileDescriptor;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700116import java.io.FileInputStream;
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700117import java.io.FileNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700118import java.io.FileOutputStream;
Tony Mak64fd8c02017-12-01 19:11:59 +0000119import java.io.IOException;
Kenny Guy02c89902016-11-15 19:36:38 +0000120import java.io.InputStream;
121import java.io.OutputStream;
Amith Yamasani920ace02012-09-20 22:15:37 -0700122import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100123import java.nio.charset.StandardCharsets;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700124import java.util.ArrayList;
Pavel Grafov6a40f092016-10-25 15:46:51 +0100125import java.util.Collections;
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700126import java.util.LinkedList;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700127import java.util.List;
Narayan Kamath607223f2018-02-19 14:09:02 +0000128import java.util.Objects;
Bookatz75f0a072019-08-05 14:12:16 -0700129import java.util.Set;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700130
Makoto Onuki068c54a2015-10-13 14:34:03 -0700131/**
132 * Service for {@link UserManager}.
133 *
134 * Method naming convention:
Fyodor Kupolov82402752015-10-28 14:54:51 -0700135 * <ul>
Fyodor Kupolovd31cee92017-09-05 16:31:08 -0700136 * <li> Methods suffixed with "LAr" should be called within the {@link #mAppRestrictionsLock} lock.
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800137 * <li> Methods suffixed with "LP" should be called within the {@link #mPackagesLock} lock.
Fyodor Kupolov82402752015-10-28 14:54:51 -0700138 * <li> Methods suffixed with "LR" should be called within the {@link #mRestrictionsLock} lock.
139 * <li> Methods suffixed with "LU" should be called within the {@link #mUsersLock} lock.
140 * </ul>
Makoto Onuki068c54a2015-10-13 14:34:03 -0700141 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700142public class UserManagerService extends IUserManager.Stub {
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700143
Amith Yamasani2a003292012-08-14 18:25:45 -0700144 private static final String LOG_TAG = "UserManagerService";
Makoto Onuki81c61ea2016-01-22 11:22:26 -0800145 static final boolean DBG = false; // DO NOT SUBMIT WITH TRUE
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800146 private static final boolean DBG_WITH_STACKTRACE = false; // DO NOT SUBMIT WITH TRUE
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700147 // Can be used for manual testing of id recycling
148 private static final boolean RELEASE_DELETED_USER_ID = false; // DO NOT SUBMIT WITH TRUE
Amith Yamasani16389312012-10-17 21:20:14 -0700149
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700150 private static final String TAG_NAME = "name";
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800151 private static final String TAG_ACCOUNT = "account";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700152 private static final String ATTR_FLAGS = "flags";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700153 private static final String ATTR_ICON_PATH = "icon";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700154 private static final String ATTR_ID = "id";
Amith Yamasani920ace02012-09-20 22:15:37 -0700155 private static final String ATTR_CREATION_TIME = "created";
156 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -0600157 private static final String ATTR_LAST_LOGGED_IN_FINGERPRINT = "lastLoggedInFingerprint";
Amith Yamasani2a003292012-08-14 18:25:45 -0700158 private static final String ATTR_SERIAL_NO = "serialNumber";
159 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700160 private static final String ATTR_PARTIAL = "partial";
Adam Lesinskieddeb492014-09-08 17:50:03 -0700161 private static final String ATTR_GUEST_TO_REMOVE = "guestToRemove";
Amith Yamasani6f34b412012-10-22 18:19:27 -0700162 private static final String ATTR_USER_VERSION = "version";
Kenny Guy2a764942014-04-02 13:29:20 +0100163 private static final String ATTR_PROFILE_GROUP_ID = "profileGroupId";
Kenny Guy02c89902016-11-15 19:36:38 +0000164 private static final String ATTR_PROFILE_BADGE = "profileBadge";
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700165 private static final String ATTR_RESTRICTED_PROFILE_PARENT_ID = "restrictedProfileParentId";
Amith Yamasani12747872015-12-07 14:19:49 -0800166 private static final String ATTR_SEED_ACCOUNT_NAME = "seedAccountName";
167 private static final String ATTR_SEED_ACCOUNT_TYPE = "seedAccountType";
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530168 private static final String TAG_GUEST_RESTRICTIONS = "guestRestrictions";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700169 private static final String TAG_USERS = "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700170 private static final String TAG_USER = "user";
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800171 private static final String TAG_RESTRICTIONS = "restrictions";
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800172 private static final String TAG_DEVICE_POLICY_RESTRICTIONS = "device_policy_restrictions";
Pavel Grafov6a40f092016-10-25 15:46:51 +0100173 private static final String TAG_DEVICE_POLICY_GLOBAL_RESTRICTIONS =
174 "device_policy_global_restrictions";
175 /** Legacy name for device owner id tag. */
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +0100176 private static final String TAG_GLOBAL_RESTRICTION_OWNER_ID = "globalRestrictionOwnerUserId";
Pavel Grafov6a40f092016-10-25 15:46:51 +0100177 private static final String TAG_DEVICE_OWNER_USER_ID = "deviceOwnerUserId";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800178 private static final String TAG_ENTRY = "entry";
179 private static final String TAG_VALUE = "value";
Amith Yamasani12747872015-12-07 14:19:49 -0800180 private static final String TAG_SEED_ACCOUNT_OPTIONS = "seedAccountOptions";
arangelov9b632d72018-12-07 23:21:22 +0000181 private static final String TAG_LAST_REQUEST_QUIET_MODE_ENABLED_CALL =
182 "lastRequestQuietModeEnabledCall";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800183 private static final String ATTR_KEY = "key";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700184 private static final String ATTR_VALUE_TYPE = "type";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800185 private static final String ATTR_MULTIPLE = "m";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700186
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700187 private static final String ATTR_TYPE_STRING_ARRAY = "sa";
188 private static final String ATTR_TYPE_STRING = "s";
189 private static final String ATTR_TYPE_BOOLEAN = "b";
Amith Yamasani5b5aa402014-06-01 20:10:14 -0700190 private static final String ATTR_TYPE_INTEGER = "i";
Fyodor Kupolov262f9952015-03-23 18:55:11 -0700191 private static final String ATTR_TYPE_BUNDLE = "B";
192 private static final String ATTR_TYPE_BUNDLE_ARRAY = "BA";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700193
Amith Yamasani0b285492011-04-14 17:35:23 -0700194 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700195 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700196 private static final String USER_PHOTO_FILENAME = "photo.png";
Adrian Roos1bdff912015-02-17 15:51:35 +0100197 private static final String USER_PHOTO_FILENAME_TMP = USER_PHOTO_FILENAME + ".tmp";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700198
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800199 private static final String RESTRICTIONS_FILE_PREFIX = "res_";
Amith Yamasanifc95e702013-09-26 13:20:17 -0700200 private static final String XML_SUFFIX = ".xml";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800201
Sudheer Shankaf5cea032016-06-08 17:13:24 -0700202 private static final int ALLOWED_FLAGS_FOR_CREATE_USERS_PERMISSION =
203 UserInfo.FLAG_MANAGED_PROFILE
204 | UserInfo.FLAG_EPHEMERAL
205 | UserInfo.FLAG_RESTRICTED
Sudheer Shanka234d1af2016-08-26 15:42:53 -0700206 | UserInfo.FLAG_GUEST
207 | UserInfo.FLAG_DEMO;
Sudheer Shankaf5cea032016-06-08 17:13:24 -0700208
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700209 @VisibleForTesting
210 static final int MIN_USER_ID = 10;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700211 // We need to keep process uid within Integer.MAX_VALUE.
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700212 @VisibleForTesting
213 static final int MAX_USER_ID = Integer.MAX_VALUE / UserHandle.PER_USER_RANGE;
214
215 // Max size of the queue of recently removed users
216 @VisibleForTesting
217 static final int MAX_RECENTLY_REMOVED_IDS_SIZE = 100;
Amith Yamasani634cf312012-10-04 17:34:21 -0700218
Bookatz75f0a072019-08-05 14:12:16 -0700219 private static final int USER_VERSION = 8;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700220
Amith Yamasani920ace02012-09-20 22:15:37 -0700221 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
222
Nicolas Prevotb8186812015-08-06 15:00:03 +0100223 // Maximum number of managed profiles permitted per user is 1. This cannot be increased
Amith Yamasani95ab7842014-08-11 17:09:26 -0700224 // without first making sure that the rest of the framework is prepared for it.
Kenny Guy02c89902016-11-15 19:36:38 +0000225 @VisibleForTesting
226 static final int MAX_MANAGED_PROFILES = 1;
Amith Yamasani95ab7842014-08-11 17:09:26 -0700227
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800228 static final int WRITE_USER_MSG = 1;
229 static final int WRITE_USER_DELAY = 2*1000; // 2 seconds
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530230
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -0800231 // Tron counters
232 private static final String TRON_GUEST_CREATED = "users_guest_created";
233 private static final String TRON_USER_CREATED = "users_user_created";
Christine Franks88220562017-05-24 11:11:21 -0700234 private static final String TRON_DEMO_CREATED = "users_demo_created";
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -0800235
Dianne Hackborn4428e172012-08-24 17:43:05 -0700236 private final Context mContext;
237 private final PackageManagerService mPm;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700238 private final Object mPackagesLock;
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800239 private final UserDataPreparer mUserDataPreparer;
Fyodor Kupolov82402752015-10-28 14:54:51 -0700240 // Short-term lock for internal state, when interaction/sync with PM is not required
Jeff Sharkey5f3e9342017-03-13 14:53:11 -0600241 private final Object mUsersLock = LockGuard.installNewLock(LockGuard.INDEX_USER);
Fyodor Kupolov82402752015-10-28 14:54:51 -0700242 private final Object mRestrictionsLock = new Object();
Fyodor Kupolovd31cee92017-09-05 16:31:08 -0700243 // Used for serializing access to app restriction files
244 private final Object mAppRestrictionsLock = new Object();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700245
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800246 private final Handler mHandler;
247
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700248 private final File mUsersDir;
249 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700250
Svet Ganov9cea80cd2016-02-16 11:47:00 -0800251 private static final IBinder mUserRestriconToken = new Binder();
252
Makoto Onuki068c54a2015-10-13 14:34:03 -0700253 /**
Makoto Onuki73dded22017-12-20 13:14:48 +0900254 * Internal non-parcelable wrapper for UserInfo that is not exposed to other system apps.
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800255 */
Kenny Guy02c89902016-11-15 19:36:38 +0000256 @VisibleForTesting
257 static class UserData {
Amith Yamasani12747872015-12-07 14:19:49 -0800258 // Basic user information and properties
259 UserInfo info;
260 // Account name used when there is a strong association between a user and an account
261 String account;
262 // Account information for seeding into a newly created user. This could also be
263 // used for login validation for an existing user, for updating their credentials.
264 // In the latter case, data may not need to be persisted as it is only valid for the
265 // current login session.
266 String seedAccountName;
267 String seedAccountType;
268 PersistableBundle seedAccountOptions;
269 // Whether to perist the seed account information to be available after a boot
270 boolean persistSeedData;
271
Makoto Onuki73dded22017-12-20 13:14:48 +0900272 /** Elapsed realtime since boot when the user started. */
273 long startRealtime;
274
275 /** Elapsed realtime since boot when the user was unlocked. */
276 long unlockRealtime;
277
arangelov9b632d72018-12-07 23:21:22 +0000278 private long mLastRequestQuietModeEnabledMillis;
279
280 void setLastRequestQuietModeEnabledMillis(long millis) {
281 mLastRequestQuietModeEnabledMillis = millis;
282 }
283
284 long getLastRequestQuietModeEnabledMillis() {
285 return mLastRequestQuietModeEnabledMillis;
286 }
287
Amith Yamasani12747872015-12-07 14:19:49 -0800288 void clearSeedAccountData() {
289 seedAccountName = null;
290 seedAccountType = null;
291 seedAccountOptions = null;
292 persistSeedData = false;
293 }
294 }
295
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800296 @GuardedBy("mUsersLock")
Amith Yamasani12747872015-12-07 14:19:49 -0800297 private final SparseArray<UserData> mUsers = new SparseArray<>();
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800298
299 /**
Makoto Onuki068c54a2015-10-13 14:34:03 -0700300 * User restrictions set via UserManager. This doesn't include restrictions set by
Pavel Grafov6a40f092016-10-25 15:46:51 +0100301 * device owner / profile owners. Only non-empty restriction bundles are stored.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700302 *
303 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
304 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
305 * maybe shared between {@link #mBaseUserRestrictions} and
306 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
307 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700308 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700309 */
310 @GuardedBy("mRestrictionsLock")
311 private final SparseArray<Bundle> mBaseUserRestrictions = new SparseArray<>();
312
313 /**
314 * Cached user restrictions that are in effect -- i.e. {@link #mBaseUserRestrictions} combined
315 * with device / profile owner restrictions. We'll initialize it lazily; use
316 * {@link #getEffectiveUserRestrictions} to access it.
317 *
318 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
319 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
320 * maybe shared between {@link #mBaseUserRestrictions} and
321 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
322 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700323 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700324 */
325 @GuardedBy("mRestrictionsLock")
326 private final SparseArray<Bundle> mCachedEffectiveUserRestrictions = new SparseArray<>();
327
Makoto Onuki4f160732015-10-27 17:15:38 -0700328 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800329 * User restrictions that have already been applied in
330 * {@link #updateUserRestrictionsInternalLR(Bundle, int)}. We use it to detect restrictions
331 * that have changed since the last
332 * {@link #updateUserRestrictionsInternalLR(Bundle, int)} call.
Makoto Onuki4f160732015-10-27 17:15:38 -0700333 */
334 @GuardedBy("mRestrictionsLock")
335 private final SparseArray<Bundle> mAppliedUserRestrictions = new SparseArray<>();
336
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800337 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800338 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
Pavel Grafov6a40f092016-10-25 15:46:51 +0100339 * that should be applied to all users, including guests. Only non-empty restriction bundles are
340 * stored.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800341 */
342 @GuardedBy("mRestrictionsLock")
Pavel Grafov6a40f092016-10-25 15:46:51 +0100343 private final SparseArray<Bundle> mDevicePolicyGlobalUserRestrictions = new SparseArray<>();
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800344
345 /**
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +0100346 * Id of the user that set global restrictions.
347 */
348 @GuardedBy("mRestrictionsLock")
Pavel Grafov6a40f092016-10-25 15:46:51 +0100349 private int mDeviceOwnerUserId = UserHandle.USER_NULL;
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +0100350
351 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800352 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
Pavel Grafov6a40f092016-10-25 15:46:51 +0100353 * for each user. Only non-empty restriction bundles are stored.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800354 */
355 @GuardedBy("mRestrictionsLock")
356 private final SparseArray<Bundle> mDevicePolicyLocalUserRestrictions = new SparseArray<>();
357
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800358 @GuardedBy("mGuestRestrictions")
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530359 private final Bundle mGuestRestrictions = new Bundle();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800360
361 /**
362 * Set of user IDs being actively removed. Removed IDs linger in this set
363 * for several seconds to work around a VFS caching issue.
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700364 * Use {@link #addRemovingUserIdLocked(int)} to add elements to this array
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800365 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700366 @GuardedBy("mUsersLock")
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800367 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700368
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700369 /**
370 * Queue of recently removed userIds. Used for recycling of userIds
371 */
372 @GuardedBy("mUsersLock")
373 private final LinkedList<Integer> mRecentlyRemovedIds = new LinkedList<>();
374
Fyodor Kupolov82402752015-10-28 14:54:51 -0700375 @GuardedBy("mUsersLock")
Amith Yamasani0b285492011-04-14 17:35:23 -0700376 private int[] mUserIds;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800377 @GuardedBy("mPackagesLock")
Amith Yamasani2a003292012-08-14 18:25:45 -0700378 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700379 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700380
Jason Monk62062992014-05-06 09:55:28 -0400381 private IAppOpsService mAppOpsService;
382
Makoto Onuki068c54a2015-10-13 14:34:03 -0700383 private final LocalService mLocalService;
384
Makoto Onukie7927da2015-11-25 10:05:17 -0800385 @GuardedBy("mUsersLock")
386 private boolean mIsDeviceManaged;
387
388 @GuardedBy("mUsersLock")
389 private final SparseBooleanArray mIsUserManaged = new SparseBooleanArray();
390
Makoto Onukid45a4a22015-11-02 17:17:38 -0800391 @GuardedBy("mUserRestrictionsListeners")
392 private final ArrayList<UserRestrictionsListener> mUserRestrictionsListeners =
393 new ArrayList<>();
394
Clara Bayarria1771112015-12-18 16:29:18 +0000395 private final LockPatternUtils mLockPatternUtils;
396
Ricky Waib1dd80b2016-06-07 18:00:55 +0100397 private final String ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK =
398 "com.android.server.pm.DISABLE_QUIET_MODE_AFTER_UNLOCK";
399
400 private final BroadcastReceiver mDisableQuietModeCallback = new BroadcastReceiver() {
401 @Override
402 public void onReceive(Context context, Intent intent) {
Tony Mak64fd8c02017-12-01 19:11:59 +0000403 if (!ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK.equals(intent.getAction())) {
404 return;
Ricky Waib1dd80b2016-06-07 18:00:55 +0100405 }
Tony Mak64fd8c02017-12-01 19:11:59 +0000406 final IntentSender target = intent.getParcelableExtra(Intent.EXTRA_INTENT);
Bookatzf56f2582019-09-04 16:06:41 -0700407 final int userId = intent.getIntExtra(Intent.EXTRA_USER_ID, UserHandle.USER_NULL);
Fyodor Kupolova68a2862018-01-30 18:22:00 -0800408 // Call setQuietModeEnabled on bg thread to avoid ANR
arangelov9b632d72018-12-07 23:21:22 +0000409 BackgroundThread.getHandler().post(() ->
Bookatzf56f2582019-09-04 16:06:41 -0700410 setQuietModeEnabled(userId, false, target, /* callingPackage */ null));
Ricky Waib1dd80b2016-06-07 18:00:55 +0100411 }
412 };
413
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +0100414 /**
Tony Mak64fd8c02017-12-01 19:11:59 +0000415 * Start an {@link IntentSender} when user is unlocked after disabling quiet mode.
416 *
Tony Makbece85d2018-01-12 12:10:17 +0000417 * @see {@link #requestQuietModeEnabled(String, boolean, int, IntentSender)}
Tony Mak64fd8c02017-12-01 19:11:59 +0000418 */
419 private class DisableQuietModeUserUnlockedCallback extends IProgressListener.Stub {
420 private final IntentSender mTarget;
421
422 public DisableQuietModeUserUnlockedCallback(IntentSender target) {
423 Preconditions.checkNotNull(target);
424 mTarget = target;
425 }
426
427 @Override
428 public void onStarted(int id, Bundle extras) {}
429
430 @Override
431 public void onProgress(int id, int progress, Bundle extras) {}
432
433 @Override
434 public void onFinished(int id, Bundle extras) {
435 try {
436 mContext.startIntentSender(mTarget, null, 0, 0, 0);
437 } catch (IntentSender.SendIntentException e) {
438 Slog.e(LOG_TAG, "Failed to start the target in the callback", e);
439 }
440 }
441 }
442
443 /**
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +0100444 * Whether all users should be created ephemeral.
445 */
446 @GuardedBy("mUsersLock")
447 private boolean mForceEphemeralUsers;
448
Amith Yamasaniea1b9d72016-05-27 15:57:38 +0000449 @GuardedBy("mUserStates")
450 private final SparseIntArray mUserStates = new SparseIntArray();
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -0700451
Amith Yamasani258848d2012-08-10 17:06:33 -0700452 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700453
Dianne Hackborn4428e172012-08-24 17:43:05 -0700454 public static UserManagerService getInstance() {
455 synchronized (UserManagerService.class) {
456 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700457 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700458 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700459
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700460 public static class LifeCycle extends SystemService {
461
462 private UserManagerService mUms;
463
464 /**
465 * @param context
466 */
467 public LifeCycle(Context context) {
468 super(context);
469 }
470
471 @Override
472 public void onStart() {
473 mUms = UserManagerService.getInstance();
474 publishBinderService(Context.USER_SERVICE, mUms);
475 }
476
477 @Override
478 public void onBootPhase(int phase) {
479 if (phase == SystemService.PHASE_ACTIVITY_MANAGER_READY) {
480 mUms.cleanupPartialUsers();
481 }
482 }
Makoto Onuki73dded22017-12-20 13:14:48 +0900483
484 @Override
Bookatzf56f2582019-09-04 16:06:41 -0700485 public void onStartUser(@UserIdInt int userId) {
Makoto Onuki73dded22017-12-20 13:14:48 +0900486 synchronized (mUms.mUsersLock) {
Bookatzf56f2582019-09-04 16:06:41 -0700487 final UserData user = mUms.getUserDataLU(userId);
Makoto Onuki73dded22017-12-20 13:14:48 +0900488 if (user != null) {
489 user.startRealtime = SystemClock.elapsedRealtime();
490 }
491 }
492 }
493
494 @Override
Bookatzf56f2582019-09-04 16:06:41 -0700495 public void onUnlockUser(@UserIdInt int userId) {
Makoto Onuki73dded22017-12-20 13:14:48 +0900496 synchronized (mUms.mUsersLock) {
Bookatzf56f2582019-09-04 16:06:41 -0700497 final UserData user = mUms.getUserDataLU(userId);
Makoto Onuki73dded22017-12-20 13:14:48 +0900498 if (user != null) {
499 user.unlockRealtime = SystemClock.elapsedRealtime();
500 }
501 }
502 }
503
504 @Override
Bookatzf56f2582019-09-04 16:06:41 -0700505 public void onStopUser(@UserIdInt int userId) {
Makoto Onuki73dded22017-12-20 13:14:48 +0900506 synchronized (mUms.mUsersLock) {
Bookatzf56f2582019-09-04 16:06:41 -0700507 final UserData user = mUms.getUserDataLU(userId);
Makoto Onuki73dded22017-12-20 13:14:48 +0900508 if (user != null) {
509 user.startRealtime = 0;
510 user.unlockRealtime = 0;
511 }
512 }
513 }
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700514 }
515
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700516 // TODO b/28848102 Add support for test dependencies injection
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800517 @VisibleForTesting
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700518 UserManagerService(Context context) {
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800519 this(context, null, null, new Object(), context.getCacheDir());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700520 }
521
Dianne Hackborn4428e172012-08-24 17:43:05 -0700522 /**
523 * Called by package manager to create the service. This is closely
524 * associated with the package manager, and the given lock is the
525 * package manager's own lock.
526 */
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800527 UserManagerService(Context context, PackageManagerService pm, UserDataPreparer userDataPreparer,
528 Object packagesLock) {
529 this(context, pm, userDataPreparer, packagesLock, Environment.getDataDirectory());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700530 }
531
Dianne Hackborn4428e172012-08-24 17:43:05 -0700532 private UserManagerService(Context context, PackageManagerService pm,
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800533 UserDataPreparer userDataPreparer, Object packagesLock, File dataDir) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700534 mContext = context;
535 mPm = pm;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700536 mPackagesLock = packagesLock;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800537 mHandler = new MainHandler();
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800538 mUserDataPreparer = userDataPreparer;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800539 synchronized (mPackagesLock) {
540 mUsersDir = new File(dataDir, USER_INFO_DIR);
541 mUsersDir.mkdirs();
542 // Make zeroth user directory, for services to migrate their files to that location
543 File userZeroDir = new File(mUsersDir, String.valueOf(UserHandle.USER_SYSTEM));
544 userZeroDir.mkdirs();
545 FileUtils.setPermissions(mUsersDir.toString(),
546 FileUtils.S_IRWXU | FileUtils.S_IRWXG | FileUtils.S_IROTH | FileUtils.S_IXOTH,
547 -1, -1);
548 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
549 initDefaultGuestRestrictions();
550 readUserListLP();
551 sInstance = this;
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700552 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700553 mLocalService = new LocalService();
554 LocalServices.addService(UserManagerInternal.class, mLocalService);
Clara Bayarria1771112015-12-18 16:29:18 +0000555 mLockPatternUtils = new LockPatternUtils(mContext);
Amith Yamasaniea1b9d72016-05-27 15:57:38 +0000556 mUserStates.put(UserHandle.USER_SYSTEM, UserState.STATE_BOOTING);
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700557 }
558
559 void systemReady() {
Jason Monk62062992014-05-06 09:55:28 -0400560 mAppOpsService = IAppOpsService.Stub.asInterface(
561 ServiceManager.getService(Context.APP_OPS_SERVICE));
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800562
563 synchronized (mRestrictionsLock) {
564 applyUserRestrictionsLR(UserHandle.USER_SYSTEM);
Jason Monk62062992014-05-06 09:55:28 -0400565 }
Samuel Tand9453b82016-03-14 15:57:02 -0700566
567 UserInfo currentGuestUser = findCurrentGuestUser();
568 if (currentGuestUser != null && !hasUserRestriction(
569 UserManager.DISALLOW_CONFIG_WIFI, currentGuestUser.id)) {
570 // If a guest user currently exists, apply the DISALLOW_CONFIG_WIFI option
571 // to it, in case this guest was created in a previous version where this
572 // user restriction was not a default guest restriction.
573 setUserRestriction(UserManager.DISALLOW_CONFIG_WIFI, true, currentGuestUser.id);
574 }
Amith Yamasanieb437d42016-04-29 09:31:25 -0700575
Ricky Waib1dd80b2016-06-07 18:00:55 +0100576 mContext.registerReceiver(mDisableQuietModeCallback,
577 new IntentFilter(ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK),
578 null, mHandler);
Amith Yamasani258848d2012-08-10 17:06:33 -0700579 }
580
Patrick Baumann6ae7afc2019-07-30 13:11:28 -0700581 /**
582 * This method retrieves the {@link UserManagerInternal} only for the purpose of
583 * PackageManagerService construction.
584 */
585 UserManagerInternal getInternalForInjectorOnly() {
586 return mLocalService;
587 }
588
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700589 void cleanupPartialUsers() {
590 // Prune out any partially created, partially removed and ephemeral users.
591 ArrayList<UserInfo> partials = new ArrayList<>();
592 synchronized (mUsersLock) {
593 final int userSize = mUsers.size();
594 for (int i = 0; i < userSize; i++) {
595 UserInfo ui = mUsers.valueAt(i).info;
596 if ((ui.partial || ui.guestToRemove || ui.isEphemeral()) && i != 0) {
597 partials.add(ui);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700598 addRemovingUserIdLocked(ui.id);
Amith Yamasaniae261892016-06-27 10:40:09 -0700599 ui.partial = true;
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700600 }
601 }
602 }
603 final int partialsSize = partials.size();
604 for (int i = 0; i < partialsSize; i++) {
605 UserInfo ui = partials.get(i);
606 Slog.w(LOG_TAG, "Removing partially created user " + ui.id
607 + " (name=" + ui.name + ")");
608 removeUserState(ui.id);
609 }
610 }
611
Amith Yamasani258848d2012-08-10 17:06:33 -0700612 @Override
Bookatzf56f2582019-09-04 16:06:41 -0700613 public String getUserAccount(@UserIdInt int userId) {
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800614 checkManageUserAndAcrossUsersFullPermission("get user account");
615 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800616 return mUsers.get(userId).account;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800617 }
618 }
619
620 @Override
Bookatzf56f2582019-09-04 16:06:41 -0700621 public void setUserAccount(@UserIdInt int userId, String accountName) {
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800622 checkManageUserAndAcrossUsersFullPermission("set user account");
Amith Yamasani12747872015-12-07 14:19:49 -0800623 UserData userToUpdate = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800624 synchronized (mPackagesLock) {
625 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800626 final UserData userData = mUsers.get(userId);
627 if (userData == null) {
628 Slog.e(LOG_TAG, "User not found for setting user account: u" + userId);
629 return;
630 }
631 String currentAccount = userData.account;
Narayan Kamath607223f2018-02-19 14:09:02 +0000632 if (!Objects.equals(currentAccount, accountName)) {
Amith Yamasani12747872015-12-07 14:19:49 -0800633 userData.account = accountName;
634 userToUpdate = userData;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800635 }
636 }
637
638 if (userToUpdate != null) {
639 writeUserLP(userToUpdate);
640 }
641 }
642 }
643
644 @Override
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700645 public UserInfo getPrimaryUser() {
646 checkManageUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700647 synchronized (mUsersLock) {
Amith Yamasani515d4062015-09-28 11:30:06 -0700648 final int userSize = mUsers.size();
649 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800650 UserInfo ui = mUsers.valueAt(i).info;
Xiaohui Chend3e9e182015-11-18 13:37:32 -0800651 if (ui.isPrimary() && !mRemovingUserIds.get(ui.id)) {
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700652 return ui;
653 }
654 }
655 }
656 return null;
657 }
658
659 @Override
Xiaohui Chen594f2082015-08-18 11:04:20 -0700660 public @NonNull List<UserInfo> getUsers(boolean excludeDying) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -0700661 checkManageOrCreateUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700662 synchronized (mUsersLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700663 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasani515d4062015-09-28 11:30:06 -0700664 final int userSize = mUsers.size();
665 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800666 UserInfo ui = mUsers.valueAt(i).info;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700667 if (ui.partial) {
668 continue;
669 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800670 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Amith Yamasani6f48d6e2016-03-23 14:28:25 -0700671 users.add(userWithName(ui));
Amith Yamasani920ace02012-09-20 22:15:37 -0700672 }
Amith Yamasani13593602012-03-22 16:16:17 -0700673 }
674 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700675 }
Amith Yamasani13593602012-03-22 16:16:17 -0700676 }
677
Amith Yamasani258848d2012-08-10 17:06:33 -0700678 @Override
Bookatzf56f2582019-09-04 16:06:41 -0700679 public List<UserInfo> getProfiles(@UserIdInt int userId, boolean enabledOnly) {
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700680 boolean returnFullInfo = true;
Amith Yamasani4f582632014-02-19 14:31:52 -0800681 if (userId != UserHandle.getCallingUserId()) {
Sudheer Shanka74680912016-07-29 11:03:37 -0700682 checkManageOrCreateUsersPermission("getting profiles related to user " + userId);
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700683 } else {
684 returnFullInfo = hasManageUsersPermission();
Amith Yamasani4f582632014-02-19 14:31:52 -0800685 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700686 final long ident = Binder.clearCallingIdentity();
687 try {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700688 synchronized (mUsersLock) {
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700689 return getProfilesLU(userId, enabledOnly, returnFullInfo);
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100690 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700691 } finally {
692 Binder.restoreCallingIdentity(ident);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000693 }
694 }
695
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700696 @Override
Bookatzf56f2582019-09-04 16:06:41 -0700697 public int[] getProfileIds(@UserIdInt int userId, boolean enabledOnly) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700698 if (userId != UserHandle.getCallingUserId()) {
bohu12d23a12016-09-26 16:20:07 -0700699 checkManageOrCreateUsersPermission("getting profiles related to user " + userId);
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700700 }
701 final long ident = Binder.clearCallingIdentity();
702 try {
703 synchronized (mUsersLock) {
704 return getProfileIdsLU(userId, enabledOnly).toArray();
705 }
706 } finally {
707 Binder.restoreCallingIdentity(ident);
708 }
709 }
710
Amith Yamasanibe465322014-04-24 13:45:17 -0700711 /** Assume permissions already checked and caller's identity cleared */
Andreas Gampe2e8c7672018-07-20 13:01:08 -0700712 @GuardedBy("mUsersLock")
Bookatzf56f2582019-09-04 16:06:41 -0700713 private List<UserInfo> getProfilesLU(@UserIdInt int userId, boolean enabledOnly,
714 boolean fullInfo) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700715 IntArray profileIds = getProfileIdsLU(userId, enabledOnly);
716 ArrayList<UserInfo> users = new ArrayList<>(profileIds.size());
717 for (int i = 0; i < profileIds.size(); i++) {
718 int profileId = profileIds.get(i);
719 UserInfo userInfo = mUsers.get(profileId).info;
720 // If full info is not required - clear PII data to prevent 3P apps from reading it
721 if (!fullInfo) {
722 userInfo = new UserInfo(userInfo);
723 userInfo.name = null;
724 userInfo.iconPath = null;
725 } else {
726 userInfo = userWithName(userInfo);
727 }
728 users.add(userInfo);
729 }
730 return users;
731 }
732
733 /**
734 * Assume permissions already checked and caller's identity cleared
735 */
Andreas Gampe2e8c7672018-07-20 13:01:08 -0700736 @GuardedBy("mUsersLock")
Bookatzf56f2582019-09-04 16:06:41 -0700737 private IntArray getProfileIdsLU(@UserIdInt int userId, boolean enabledOnly) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700738 UserInfo user = getUserInfoLU(userId);
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700739 IntArray result = new IntArray(mUsers.size());
Amith Yamasanidda003f2014-08-28 18:06:51 -0700740 if (user == null) {
741 // Probably a dying user
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700742 return result;
Amith Yamasanidda003f2014-08-28 18:06:51 -0700743 }
Amith Yamasani515d4062015-09-28 11:30:06 -0700744 final int userSize = mUsers.size();
745 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800746 UserInfo profile = mUsers.valueAt(i).info;
Amith Yamasanibe465322014-04-24 13:45:17 -0700747 if (!isProfileOf(user, profile)) {
748 continue;
749 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100750 if (enabledOnly && !profile.isEnabled()) {
751 continue;
Amith Yamasanibe465322014-04-24 13:45:17 -0700752 }
Amith Yamasani70fcf0c2014-07-11 08:40:19 -0700753 if (mRemovingUserIds.get(profile.id)) {
754 continue;
755 }
Tony Mak80189cd2016-04-05 17:21:42 +0100756 if (profile.partial) {
757 continue;
758 }
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700759 result.add(profile.id);
Amith Yamasanibe465322014-04-24 13:45:17 -0700760 }
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700761 return result;
Amith Yamasanibe465322014-04-24 13:45:17 -0700762 }
763
Jessica Hummelbe81c802014-04-22 15:49:22 +0100764 @Override
Bookatzf56f2582019-09-04 16:06:41 -0700765 public int getCredentialOwnerProfile(@UserIdInt int userId) {
Andres Moralesc5548c02015-08-05 10:23:12 -0700766 checkManageUsersPermission("get the credential owner");
Bookatzf56f2582019-09-04 16:06:41 -0700767 if (!mLockPatternUtils.isSeparateProfileChallengeEnabled(userId)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700768 synchronized (mUsersLock) {
Bookatzf56f2582019-09-04 16:06:41 -0700769 UserInfo profileParent = getProfileParentLU(userId);
Andres Moralesc5548c02015-08-05 10:23:12 -0700770 if (profileParent != null) {
771 return profileParent.id;
772 }
773 }
774 }
775
Bookatzf56f2582019-09-04 16:06:41 -0700776 return userId;
Andres Moralesc5548c02015-08-05 10:23:12 -0700777 }
778
779 @Override
Bookatzf56f2582019-09-04 16:06:41 -0700780 public boolean isSameProfileGroup(@UserIdInt int userId, int otherUserId) {
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700781 if (userId == otherUserId) return true;
782 checkManageUsersPermission("check if in the same profile group");
Fyodor Kupolov0fb772e2016-10-13 16:27:34 -0700783 return isSameProfileGroupNoChecks(userId, otherUserId);
784 }
785
Bookatzf56f2582019-09-04 16:06:41 -0700786 private boolean isSameProfileGroupNoChecks(@UserIdInt int userId, int otherUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700787 synchronized (mUsersLock) {
788 UserInfo userInfo = getUserInfoLU(userId);
789 if (userInfo == null || userInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
790 return false;
791 }
792 UserInfo otherUserInfo = getUserInfoLU(otherUserId);
793 if (otherUserInfo == null
794 || otherUserInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
795 return false;
796 }
797 return userInfo.profileGroupId == otherUserInfo.profileGroupId;
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700798 }
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700799 }
800
801 @Override
Bookatzf56f2582019-09-04 16:06:41 -0700802 public UserInfo getProfileParent(@UserIdInt int userId) {
Jessica Hummelbe81c802014-04-22 15:49:22 +0100803 checkManageUsersPermission("get the profile parent");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700804 synchronized (mUsersLock) {
Bookatzf56f2582019-09-04 16:06:41 -0700805 return getProfileParentLU(userId);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700806 }
807 }
808
Jakub Pawlowski0f1f5b72017-11-15 14:50:43 -0800809 @Override
Bookatzf56f2582019-09-04 16:06:41 -0700810 public int getProfileParentId(@UserIdInt int userId) {
Jakub Pawlowski0f1f5b72017-11-15 14:50:43 -0800811 checkManageUsersPermission("get the profile parent");
Bookatzf56f2582019-09-04 16:06:41 -0700812 return mLocalService.getProfileParentId(userId);
Jakub Pawlowski0f1f5b72017-11-15 14:50:43 -0800813 }
814
Andreas Gampe2e8c7672018-07-20 13:01:08 -0700815 @GuardedBy("mUsersLock")
Bookatzf56f2582019-09-04 16:06:41 -0700816 private UserInfo getProfileParentLU(@UserIdInt int userId) {
817 UserInfo profile = getUserInfoLU(userId);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700818 if (profile == null) {
819 return null;
820 }
821 int parentUserId = profile.profileGroupId;
Bookatzf56f2582019-09-04 16:06:41 -0700822 if (parentUserId == userId || parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700823 return null;
824 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700825 return getUserInfoLU(parentUserId);
Jessica Hummelbe81c802014-04-22 15:49:22 +0100826 }
827 }
828
Fyodor Kupolov82402752015-10-28 14:54:51 -0700829 private static boolean isProfileOf(UserInfo user, UserInfo profile) {
Kenny Guy2a764942014-04-02 13:29:20 +0100830 return user.id == profile.id ||
831 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
832 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000833 }
834
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000835 private void broadcastProfileAvailabilityChanges(UserHandle profileHandle,
Rubin Xuf13c9802016-01-21 18:06:00 +0000836 UserHandle parentHandle, boolean inQuietMode) {
Rubin Xue95057a2016-04-01 16:49:25 +0100837 Intent intent = new Intent();
838 if (inQuietMode) {
839 intent.setAction(Intent.ACTION_MANAGED_PROFILE_UNAVAILABLE);
840 } else {
841 intent.setAction(Intent.ACTION_MANAGED_PROFILE_AVAILABLE);
842 }
Rubin Xuf13c9802016-01-21 18:06:00 +0000843 intent.putExtra(Intent.EXTRA_QUIET_MODE, inQuietMode);
844 intent.putExtra(Intent.EXTRA_USER, profileHandle);
845 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileHandle.getIdentifier());
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000846 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Rubin Xuf13c9802016-01-21 18:06:00 +0000847 mContext.sendBroadcastAsUser(intent, parentHandle);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000848 }
849
850 @Override
Tony Makbece85d2018-01-12 12:10:17 +0000851 public boolean requestQuietModeEnabled(@NonNull String callingPackage, boolean enableQuietMode,
Bookatzf56f2582019-09-04 16:06:41 -0700852 @UserIdInt int userId, @Nullable IntentSender target) {
Tony Make3d1f652017-12-12 11:00:37 +0000853 Preconditions.checkNotNull(callingPackage);
854
Tony Makb7e6fd42017-12-05 19:40:28 +0000855 if (enableQuietMode && target != null) {
856 throw new IllegalArgumentException(
857 "target should only be specified when we are disabling quiet mode.");
858 }
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000859
Tony Makd390ae92017-12-28 13:23:10 +0000860 ensureCanModifyQuietMode(callingPackage, Binder.getCallingUid(), target != null);
Tony Makb7e6fd42017-12-05 19:40:28 +0000861 final long identity = Binder.clearCallingIdentity();
862 try {
arangelov9b632d72018-12-07 23:21:22 +0000863 boolean result = false;
Tony Makb7e6fd42017-12-05 19:40:28 +0000864 if (enableQuietMode) {
arangelov9b632d72018-12-07 23:21:22 +0000865 setQuietModeEnabled(
Bookatzf56f2582019-09-04 16:06:41 -0700866 userId, true /* enableQuietMode */, target, callingPackage);
arangelov9b632d72018-12-07 23:21:22 +0000867 result = true;
Tony Makb7e6fd42017-12-05 19:40:28 +0000868 } else {
869 boolean needToShowConfirmCredential =
Bookatzf56f2582019-09-04 16:06:41 -0700870 mLockPatternUtils.isSecure(userId)
871 && !StorageManager.isUserKeyUnlocked(userId);
Tony Makb7e6fd42017-12-05 19:40:28 +0000872 if (needToShowConfirmCredential) {
Bookatzf56f2582019-09-04 16:06:41 -0700873 showConfirmCredentialToDisableQuietMode(userId, target);
Tony Makb7e6fd42017-12-05 19:40:28 +0000874 } else {
arangelov9b632d72018-12-07 23:21:22 +0000875 setQuietModeEnabled(
Bookatzf56f2582019-09-04 16:06:41 -0700876 userId, false /* enableQuietMode */, target, callingPackage);
arangelov9b632d72018-12-07 23:21:22 +0000877 result = true;
Tony Makb7e6fd42017-12-05 19:40:28 +0000878 }
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000879 }
arangelov9b632d72018-12-07 23:21:22 +0000880 return result;
Tony Makb7e6fd42017-12-05 19:40:28 +0000881 } finally {
882 Binder.restoreCallingIdentity(identity);
883 }
884 }
885
Tony Make3d1f652017-12-12 11:00:37 +0000886 /**
Tony Makd390ae92017-12-28 13:23:10 +0000887 * The caller can modify quiet mode if it meets one of these conditions:
Tony Make3d1f652017-12-12 11:00:37 +0000888 * <ul>
889 * <li>Has system UID or root UID</li>
890 * <li>Has {@link Manifest.permission#MODIFY_QUIET_MODE}</li>
891 * <li>Has {@link Manifest.permission#MANAGE_USERS}</li>
892 * </ul>
Tony Makd390ae92017-12-28 13:23:10 +0000893 * <p>
894 * If caller wants to start an intent after disabling the quiet mode, it must has
895 * {@link Manifest.permission#MANAGE_USERS}.
Tony Make3d1f652017-12-12 11:00:37 +0000896 */
Tony Makd390ae92017-12-28 13:23:10 +0000897 private void ensureCanModifyQuietMode(String callingPackage, int callingUid,
898 boolean startIntent) {
Tony Make3d1f652017-12-12 11:00:37 +0000899 if (hasManageUsersPermission()) {
Tony Makd390ae92017-12-28 13:23:10 +0000900 return;
Tony Make3d1f652017-12-12 11:00:37 +0000901 }
Tony Makd390ae92017-12-28 13:23:10 +0000902 if (startIntent) {
903 throw new SecurityException("MANAGE_USERS permission is required to start intent "
904 + "after disabling quiet mode.");
905 }
jovanakf24ad492018-05-18 12:15:59 -0700906 final boolean hasModifyQuietModePermission = hasPermissionGranted(
907 Manifest.permission.MODIFY_QUIET_MODE, callingUid);
Tony Make3d1f652017-12-12 11:00:37 +0000908 if (hasModifyQuietModePermission) {
Tony Makd390ae92017-12-28 13:23:10 +0000909 return;
Tony Make3d1f652017-12-12 11:00:37 +0000910 }
911
Tony Makd390ae92017-12-28 13:23:10 +0000912 verifyCallingPackage(callingPackage, callingUid);
Tony Make3d1f652017-12-12 11:00:37 +0000913 final ShortcutServiceInternal shortcutInternal =
914 LocalServices.getService(ShortcutServiceInternal.class);
915 if (shortcutInternal != null) {
916 boolean isForegroundLauncher =
917 shortcutInternal.isForegroundDefaultLauncher(callingPackage, callingUid);
918 if (isForegroundLauncher) {
Tony Makd390ae92017-12-28 13:23:10 +0000919 return;
Tony Make3d1f652017-12-12 11:00:37 +0000920 }
921 }
Tony Makd390ae92017-12-28 13:23:10 +0000922 throw new SecurityException("Can't modify quiet mode, caller is neither foreground "
923 + "default launcher nor has MANAGE_USERS/MODIFY_QUIET_MODE permission");
Tony Make3d1f652017-12-12 11:00:37 +0000924 }
925
Bookatzf56f2582019-09-04 16:06:41 -0700926 private void setQuietModeEnabled(@UserIdInt int userId, boolean enableQuietMode,
arangelov9b632d72018-12-07 23:21:22 +0000927 IntentSender target, @Nullable String callingPackage) {
Tony Makb7e6fd42017-12-05 19:40:28 +0000928 final UserInfo profile, parent;
929 final UserData profileUserData;
930 synchronized (mUsersLock) {
Bookatzf56f2582019-09-04 16:06:41 -0700931 profile = getUserInfoLU(userId);
932 parent = getProfileParentLU(userId);
Tony Makb7e6fd42017-12-05 19:40:28 +0000933
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000934 if (profile == null || !profile.isManagedProfile()) {
Bookatzf56f2582019-09-04 16:06:41 -0700935 throw new IllegalArgumentException("User " + userId + " is not a profile");
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000936 }
Tony Makb7e6fd42017-12-05 19:40:28 +0000937 if (profile.isQuietModeEnabled() == enableQuietMode) {
938 Slog.i(LOG_TAG, "Quiet mode is already " + enableQuietMode);
939 return;
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000940 }
Tony Makb7e6fd42017-12-05 19:40:28 +0000941 profile.flags ^= UserInfo.FLAG_QUIET_MODE;
942 profileUserData = getUserDataLU(profile.id);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000943 }
Tony Makb7e6fd42017-12-05 19:40:28 +0000944 synchronized (mPackagesLock) {
945 writeUserLP(profileUserData);
946 }
947 try {
948 if (enableQuietMode) {
Bookatzf56f2582019-09-04 16:06:41 -0700949 ActivityManager.getService().stopUser(userId, /* force */true, null);
Tony Makb7e6fd42017-12-05 19:40:28 +0000950 LocalServices.getService(ActivityManagerInternal.class)
Bookatzf56f2582019-09-04 16:06:41 -0700951 .killForegroundAppsForUser(userId);
Tony Makb7e6fd42017-12-05 19:40:28 +0000952 } else {
953 IProgressListener callback = target != null
954 ? new DisableQuietModeUserUnlockedCallback(target)
955 : null;
956 ActivityManager.getService().startUserInBackgroundWithListener(
Bookatzf56f2582019-09-04 16:06:41 -0700957 userId, callback);
Rubin Xuf13c9802016-01-21 18:06:00 +0000958 }
Bookatzf56f2582019-09-04 16:06:41 -0700959 logQuietModeEnabled(userId, enableQuietMode, callingPackage);
Tony Makb7e6fd42017-12-05 19:40:28 +0000960 } catch (RemoteException e) {
961 // Should not happen, same process.
962 e.rethrowAsRuntimeException();
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000963 }
Tony Makb7e6fd42017-12-05 19:40:28 +0000964 broadcastProfileAvailabilityChanges(profile.getUserHandle(), parent.getUserHandle(),
965 enableQuietMode);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000966 }
967
Bookatzf56f2582019-09-04 16:06:41 -0700968 private void logQuietModeEnabled(@UserIdInt int userId, boolean enableQuietMode,
arangelov9b632d72018-12-07 23:21:22 +0000969 @Nullable String callingPackage) {
970 UserData userData;
971 synchronized (mUsersLock) {
Bookatzf56f2582019-09-04 16:06:41 -0700972 userData = getUserDataLU(userId);
arangelov9b632d72018-12-07 23:21:22 +0000973 }
974 if (userData == null) {
975 return;
976 }
977 final long now = System.currentTimeMillis();
978 final long period = (userData.getLastRequestQuietModeEnabledMillis() != 0L
979 ? now - userData.getLastRequestQuietModeEnabledMillis()
980 : now - userData.info.creationTime);
981 DevicePolicyEventLogger
982 .createEvent(DevicePolicyEnums.REQUEST_QUIET_MODE_ENABLED)
983 .setStrings(callingPackage)
984 .setBoolean(enableQuietMode)
985 .setTimePeriod(period)
986 .write();
987 userData.setLastRequestQuietModeEnabledMillis(now);
988 }
989
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000990 @Override
Bookatzf56f2582019-09-04 16:06:41 -0700991 public boolean isQuietModeEnabled(@UserIdInt int userId) {
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000992 synchronized (mPackagesLock) {
993 UserInfo info;
994 synchronized (mUsersLock) {
Bookatzf56f2582019-09-04 16:06:41 -0700995 info = getUserInfoLU(userId);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000996 }
997 if (info == null || !info.isManagedProfile()) {
Rubin Xuf13c9802016-01-21 18:06:00 +0000998 return false;
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000999 }
1000 return info.isQuietModeEnabled();
1001 }
1002 }
1003
Tony Makb7e6fd42017-12-05 19:40:28 +00001004 /**
1005 * Show confirm credential screen to unlock user in order to turn off quiet mode.
1006 */
1007 private void showConfirmCredentialToDisableQuietMode(
Bookatzf56f2582019-09-04 16:06:41 -07001008 @UserIdInt int userId, @Nullable IntentSender target) {
Tony Makb7e6fd42017-12-05 19:40:28 +00001009 // otherwise, we show a profile challenge to trigger decryption of the user
1010 final KeyguardManager km = (KeyguardManager) mContext.getSystemService(
1011 Context.KEYGUARD_SERVICE);
Bookatzf56f2582019-09-04 16:06:41 -07001012 // We should use userId not credentialOwnerUserId here, as even if it is unified
Tony Makb7e6fd42017-12-05 19:40:28 +00001013 // lock, confirm screenlock page will know and show personal challenge, and unlock
1014 // work profile when personal challenge is correct
Bookatzf56f2582019-09-04 16:06:41 -07001015 final Intent unlockIntent = km.createConfirmDeviceCredentialIntent(null, null, userId);
Tony Makb7e6fd42017-12-05 19:40:28 +00001016 if (unlockIntent == null) {
1017 return;
Benjamin Franzf02420c2016-04-04 18:52:21 +01001018 }
Tony Makb7e6fd42017-12-05 19:40:28 +00001019 final Intent callBackIntent = new Intent(
1020 ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK);
1021 if (target != null) {
1022 callBackIntent.putExtra(Intent.EXTRA_INTENT, target);
Benjamin Franzf02420c2016-04-04 18:52:21 +01001023 }
Bookatzf56f2582019-09-04 16:06:41 -07001024 callBackIntent.putExtra(Intent.EXTRA_USER_ID, userId);
Tony Makb7e6fd42017-12-05 19:40:28 +00001025 callBackIntent.setPackage(mContext.getPackageName());
1026 callBackIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1027 final PendingIntent pendingIntent = PendingIntent.getBroadcast(
1028 mContext,
1029 0,
1030 callBackIntent,
1031 PendingIntent.FLAG_CANCEL_CURRENT |
1032 PendingIntent.FLAG_ONE_SHOT |
1033 PendingIntent.FLAG_IMMUTABLE);
1034 // After unlocking the challenge, it will disable quiet mode and run the original
1035 // intentSender
1036 unlockIntent.putExtra(Intent.EXTRA_INTENT, pendingIntent.getIntentSender());
1037 unlockIntent.setFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
1038 mContext.startActivity(unlockIntent);
Benjamin Franzf02420c2016-04-04 18:52:21 +01001039 }
1040
1041 @Override
Bookatzf56f2582019-09-04 16:06:41 -07001042 public void setUserEnabled(@UserIdInt int userId) {
Alexandra Gherghinadf35d572014-04-09 13:54:39 +01001043 checkManageUsersPermission("enable user");
1044 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001045 UserInfo info;
1046 synchronized (mUsersLock) {
1047 info = getUserInfoLU(userId);
1048 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +01001049 if (info != null && !info.isEnabled()) {
1050 info.flags ^= UserInfo.FLAG_DISABLED;
Amith Yamasani12747872015-12-07 14:19:49 -08001051 writeUserLP(getUserDataLU(info.id));
Alexandra Gherghinadf35d572014-04-09 13:54:39 +01001052 }
1053 }
1054 }
1055
jovanakf24ad492018-05-18 12:15:59 -07001056 @Override
Bookatzf56f2582019-09-04 16:06:41 -07001057 public void setUserAdmin(@UserIdInt int userId) {
jovanakf24ad492018-05-18 12:15:59 -07001058 checkManageUserAndAcrossUsersFullPermission("set user admin");
1059
1060 synchronized (mPackagesLock) {
1061 UserInfo info;
1062 synchronized (mUsersLock) {
1063 info = getUserInfoLU(userId);
1064 }
1065 if (info == null || info.isAdmin()) {
1066 // Exit if no user found with that id, or the user is already an Admin.
1067 return;
1068 }
1069
1070 info.flags ^= UserInfo.FLAG_ADMIN;
1071 writeUserLP(getUserDataLU(info.id));
1072 }
1073
1074 // Remove non-admin restrictions.
1075 // Keep synchronized with createUserEvenWhenDisallowed.
1076 setUserRestriction(UserManager.DISALLOW_SMS, false, userId);
1077 setUserRestriction(UserManager.DISALLOW_OUTGOING_CALLS, false, userId);
1078 }
1079
Andrew Scull85a63bc2016-10-24 13:47:47 +01001080 /**
1081 * Evicts a user's CE key by stopping and restarting the user.
1082 *
1083 * The key is evicted automatically by the user controller when the user has stopped.
1084 */
1085 @Override
1086 public void evictCredentialEncryptionKey(@UserIdInt int userId) {
1087 checkManageUsersPermission("evict CE key");
1088 final IActivityManager am = ActivityManagerNative.getDefault();
1089 final long identity = Binder.clearCallingIdentity();
1090 try {
1091 am.restartUserInBackground(userId);
1092 } catch (RemoteException re) {
1093 throw re.rethrowAsRuntimeException();
1094 } finally {
1095 Binder.restoreCallingIdentity(identity);
1096 }
1097 }
1098
Alexandra Gherghinadf35d572014-04-09 13:54:39 +01001099 @Override
Bookatzf56f2582019-09-04 16:06:41 -07001100 public UserInfo getUserInfo(@UserIdInt int userId) {
Sudheer Shankaaccaa082016-06-14 16:22:57 -07001101 checkManageOrCreateUsersPermission("query user");
Tony Mak8673b282016-03-21 21:10:59 +00001102 synchronized (mUsersLock) {
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001103 return userWithName(getUserInfoLU(userId));
1104 }
1105 }
1106
1107 /**
1108 * Returns a UserInfo object with the name filled in, for Owner, or the original
1109 * if the name is already set.
1110 */
1111 private UserInfo userWithName(UserInfo orig) {
1112 if (orig != null && orig.name == null && orig.id == UserHandle.USER_SYSTEM) {
1113 UserInfo withName = new UserInfo(orig);
1114 withName.name = getOwnerName();
1115 return withName;
1116 } else {
1117 return orig;
Tony Mak8673b282016-03-21 21:10:59 +00001118 }
1119 }
1120
1121 @Override
Kenny Guy02c89902016-11-15 19:36:38 +00001122 public int getManagedProfileBadge(@UserIdInt int userId) {
Jon Miranda2b340a22019-01-25 14:03:49 -08001123 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "getManagedProfileBadge");
Kenny Guy02c89902016-11-15 19:36:38 +00001124 synchronized (mUsersLock) {
1125 UserInfo userInfo = getUserInfoLU(userId);
1126 return userInfo != null ? userInfo.profileBadge : 0;
1127 }
1128 }
1129
1130 @Override
Bookatzf56f2582019-09-04 16:06:41 -07001131 public boolean isManagedProfile(@UserIdInt int userId) {
Jon Miranda2b340a22019-01-25 14:03:49 -08001132 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isManagedProfile");
Fyodor Kupolov82402752015-10-28 14:54:51 -07001133 synchronized (mUsersLock) {
Amith Yamasani1c41dc82016-06-28 16:13:15 -07001134 UserInfo userInfo = getUserInfoLU(userId);
Tony Mak8673b282016-03-21 21:10:59 +00001135 return userInfo != null && userInfo.isManagedProfile();
Amith Yamasani13593602012-03-22 16:16:17 -07001136 }
1137 }
1138
Amith Yamasani71e6c692013-03-24 17:39:28 -07001139 @Override
Bookatzf56f2582019-09-04 16:06:41 -07001140 public boolean isUserUnlockingOrUnlocked(@UserIdInt int userId) {
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08001141 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isUserUnlockingOrUnlocked");
Fyodor Kupolovc413f702016-10-06 17:11:14 -07001142 return mLocalService.isUserUnlockingOrUnlocked(userId);
1143 }
1144
1145 @Override
Bookatzf56f2582019-09-04 16:06:41 -07001146 public boolean isUserUnlocked(@UserIdInt int userId) {
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08001147 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isUserUnlocked");
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07001148 return mLocalService.isUserUnlocked(userId);
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08001149 }
1150
1151 @Override
Bookatzf56f2582019-09-04 16:06:41 -07001152 public boolean isUserRunning(@UserIdInt int userId) {
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08001153 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isUserRunning");
1154 return mLocalService.isUserRunning(userId);
1155 }
1156
Makoto Onuki73dded22017-12-20 13:14:48 +09001157 @Override
Bookatzcde3d922019-03-08 14:30:00 -08001158 public String getUserName() {
1159 if (!hasManageUsersOrPermission(android.Manifest.permission.GET_ACCOUNTS_PRIVILEGED)) {
1160 throw new SecurityException("You need MANAGE_USERS or GET_ACCOUNTS_PRIVILEGED "
1161 + "permissions to: get user name");
1162 }
1163 final int userId = UserHandle.getUserId(Binder.getCallingUid());
1164 synchronized (mUsersLock) {
1165 UserInfo userInfo = userWithName(getUserInfoLU(userId));
1166 return userInfo == null ? "" : userInfo.name;
1167 }
1168 }
1169
1170 @Override
Makoto Onuki73dded22017-12-20 13:14:48 +09001171 public long getUserStartRealtime() {
1172 final int userId = UserHandle.getUserId(Binder.getCallingUid());
1173 synchronized (mUsersLock) {
1174 final UserData user = getUserDataLU(userId);
1175 if (user != null) {
1176 return user.startRealtime;
1177 }
1178 return 0;
1179 }
1180 }
1181
1182 @Override
1183 public long getUserUnlockRealtime() {
1184 synchronized (mUsersLock) {
1185 final UserData user = getUserDataLU(UserHandle.getUserId(Binder.getCallingUid()));
1186 if (user != null) {
1187 return user.unlockRealtime;
1188 }
1189 return 0;
1190 }
1191 }
1192
Bookatzf56f2582019-09-04 16:06:41 -07001193 private void checkManageOrInteractPermIfCallerInOtherProfileGroup(@UserIdInt int userId,
1194 String name) {
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08001195 int callingUserId = UserHandle.getCallingUserId();
1196 if (callingUserId == userId || isSameProfileGroupNoChecks(callingUserId, userId) ||
1197 hasManageUsersPermission()) {
1198 return;
1199 }
jovanakf24ad492018-05-18 12:15:59 -07001200 if (!hasPermissionGranted(Manifest.permission.INTERACT_ACROSS_USERS,
1201 Binder.getCallingUid())) {
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08001202 throw new SecurityException("You need INTERACT_ACROSS_USERS or MANAGE_USERS permission "
1203 + "to: check " + name);
1204 }
1205 }
1206
1207 @Override
Bookatzf56f2582019-09-04 16:06:41 -07001208 public boolean isDemoUser(@UserIdInt int userId) {
Amith Yamasani1c41dc82016-06-28 16:13:15 -07001209 int callingUserId = UserHandle.getCallingUserId();
1210 if (callingUserId != userId && !hasManageUsersPermission()) {
1211 throw new SecurityException("You need MANAGE_USERS permission to query if u=" + userId
1212 + " is a demo user");
1213 }
1214 synchronized (mUsersLock) {
1215 UserInfo userInfo = getUserInfoLU(userId);
1216 return userInfo != null && userInfo.isDemo();
1217 }
1218 }
1219
1220 @Override
Amith Yamasani71e6c692013-03-24 17:39:28 -07001221 public boolean isRestricted() {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001222 synchronized (mUsersLock) {
1223 return getUserInfoLU(UserHandle.getCallingUserId()).isRestricted();
Amith Yamasani71e6c692013-03-24 17:39:28 -07001224 }
1225 }
1226
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001227 @Override
Bookatzf56f2582019-09-04 16:06:41 -07001228 public boolean canHaveRestrictedProfile(@UserIdInt int userId) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001229 checkManageUsersPermission("canHaveRestrictedProfile");
Fyodor Kupolov82402752015-10-28 14:54:51 -07001230 synchronized (mUsersLock) {
1231 final UserInfo userInfo = getUserInfoLU(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001232 if (userInfo == null || !userInfo.canHaveProfile()) {
1233 return false;
1234 }
1235 if (!userInfo.isAdmin()) {
1236 return false;
1237 }
Makoto Onukie7927da2015-11-25 10:05:17 -08001238 // restricted profile can be created if there is no DO set and the admin user has no PO;
1239 return !mIsDeviceManaged && !mIsUserManaged.get(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001240 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001241 }
1242
Fyodor Kupolovca177562017-11-09 17:43:01 -08001243 @Override
1244 public boolean hasRestrictedProfiles() {
1245 checkManageUsersPermission("hasRestrictedProfiles");
1246 final int callingUserId = UserHandle.getCallingUserId();
1247 synchronized (mUsersLock) {
1248 final int userSize = mUsers.size();
1249 for (int i = 0; i < userSize; i++) {
1250 UserInfo profile = mUsers.valueAt(i).info;
1251 if (callingUserId != profile.id
1252 && profile.restrictedProfileParentId == callingUserId) {
1253 return true;
1254 }
1255 }
1256 return false;
1257 }
1258 }
1259
Amith Yamasani195263742012-08-21 15:40:12 -07001260 /*
1261 * Should be locked on mUsers before calling this.
1262 */
Andreas Gampe2e8c7672018-07-20 13:01:08 -07001263 @GuardedBy("mUsersLock")
Bookatzf56f2582019-09-04 16:06:41 -07001264 private UserInfo getUserInfoLU(@UserIdInt int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -08001265 final UserData userData = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -07001266 // If it is partial and not in the process of being removed, return as unknown user.
Amith Yamasani12747872015-12-07 14:19:49 -08001267 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001268 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
1269 return null;
1270 }
Amith Yamasani12747872015-12-07 14:19:49 -08001271 return userData != null ? userData.info : null;
1272 }
1273
Andreas Gampe2e8c7672018-07-20 13:01:08 -07001274 @GuardedBy("mUsersLock")
Bookatzf56f2582019-09-04 16:06:41 -07001275 private UserData getUserDataLU(@UserIdInt int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -08001276 final UserData userData = mUsers.get(userId);
1277 // If it is partial and not in the process of being removed, return as unknown user.
1278 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
1279 return null;
1280 }
1281 return userData;
Amith Yamasani195263742012-08-21 15:40:12 -07001282 }
1283
Fyodor Kupolov82402752015-10-28 14:54:51 -07001284 /**
1285 * Obtains {@link #mUsersLock} and return UserInfo from mUsers.
1286 * <p>No permissions checking or any addition checks are made</p>
1287 */
Bookatzf56f2582019-09-04 16:06:41 -07001288 private UserInfo getUserInfoNoChecks(@UserIdInt int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001289 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001290 final UserData userData = mUsers.get(userId);
1291 return userData != null ? userData.info : null;
1292 }
1293 }
1294
1295 /**
1296 * Obtains {@link #mUsersLock} and return UserData from mUsers.
1297 * <p>No permissions checking or any addition checks are made</p>
1298 */
Bookatzf56f2582019-09-04 16:06:41 -07001299 private UserData getUserDataNoChecks(@UserIdInt int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -08001300 synchronized (mUsersLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001301 return mUsers.get(userId);
1302 }
1303 }
1304
Amith Yamasani236b2b52015-08-18 14:32:14 -07001305 /** Called by PackageManagerService */
Bookatzf56f2582019-09-04 16:06:41 -07001306 public boolean exists(@UserIdInt int userId) {
Todd Kennedy0eb97382017-10-03 16:57:22 -07001307 return mLocalService.exists(userId);
Amith Yamasani13593602012-03-22 16:16:17 -07001308 }
1309
Amith Yamasani258848d2012-08-10 17:06:33 -07001310 @Override
Bookatzf56f2582019-09-04 16:06:41 -07001311 public void setUserName(@UserIdInt int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001312 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001313 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -07001314 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001315 UserData userData = getUserDataNoChecks(userId);
1316 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001317 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
1318 return;
1319 }
Amith Yamasani12747872015-12-07 14:19:49 -08001320 if (name != null && !name.equals(userData.info.name)) {
1321 userData.info.name = name;
1322 writeUserLP(userData);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001323 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -07001324 }
1325 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001326 if (changed) {
Bookatzf9368552019-03-14 11:57:09 -07001327 long ident = Binder.clearCallingIdentity();
1328 try {
1329 sendUserInfoChangedBroadcast(userId);
1330 } finally {
1331 Binder.restoreCallingIdentity(ident);
1332 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001333 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001334 }
1335
Amith Yamasani258848d2012-08-10 17:06:33 -07001336 @Override
Bookatzf56f2582019-09-04 16:06:41 -07001337 public void setUserIcon(@UserIdInt int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001338 checkManageUsersPermission("update users");
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01001339 if (hasUserRestriction(UserManager.DISALLOW_SET_USER_ICON, userId)) {
1340 Log.w(LOG_TAG, "Cannot set user icon. DISALLOW_SET_USER_ICON is enabled.");
1341 return;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001342 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01001343 mLocalService.setUserIcon(userId, bitmap);
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001344 }
1345
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01001346
1347
Bookatzf56f2582019-09-04 16:06:41 -07001348 private void sendUserInfoChangedBroadcast(@UserIdInt int userId) {
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001349 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
1350 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
1351 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -07001352 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001353 }
1354
Amith Yamasani258848d2012-08-10 17:06:33 -07001355 @Override
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001356 public ParcelFileDescriptor getUserIcon(int targetUserId) {
Bookatzcde3d922019-03-08 14:30:00 -08001357 if (!hasManageUsersOrPermission(android.Manifest.permission.GET_ACCOUNTS_PRIVILEGED)) {
1358 throw new SecurityException("You need MANAGE_USERS or GET_ACCOUNTS_PRIVILEGED "
1359 + "permissions to: get user icon");
1360 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001361 String iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001362 synchronized (mPackagesLock) {
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001363 UserInfo targetUserInfo = getUserInfoNoChecks(targetUserId);
1364 if (targetUserInfo == null || targetUserInfo.partial) {
1365 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + targetUserId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001366 return null;
1367 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001368
1369 final int callingUserId = UserHandle.getCallingUserId();
1370 final int callingGroupId = getUserInfoNoChecks(callingUserId).profileGroupId;
1371 final int targetGroupId = targetUserInfo.profileGroupId;
1372 final boolean sameGroup = (callingGroupId != UserInfo.NO_PROFILE_GROUP_ID
1373 && callingGroupId == targetGroupId);
1374 if ((callingUserId != targetUserId) && !sameGroup) {
Nicolas Prevot88cc3462014-05-14 14:51:48 +01001375 checkManageUsersPermission("get the icon of a user who is not related");
1376 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001377
1378 if (targetUserInfo.iconPath == null) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001379 return null;
1380 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001381 iconPath = targetUserInfo.iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001382 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001383
1384 try {
1385 return ParcelFileDescriptor.open(
1386 new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
1387 } catch (FileNotFoundException e) {
1388 Log.e(LOG_TAG, "Couldn't find icon file", e);
1389 }
1390 return null;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001391 }
1392
Bookatzf56f2582019-09-04 16:06:41 -07001393 public void makeInitialized(@UserIdInt int userId) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001394 checkManageUsersPermission("makeInitialized");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001395 boolean scheduleWriteUser = false;
Amith Yamasani12747872015-12-07 14:19:49 -08001396 UserData userData;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001397 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001398 userData = mUsers.get(userId);
1399 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001400 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001401 return;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001402 }
Amith Yamasani12747872015-12-07 14:19:49 -08001403 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1404 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001405 scheduleWriteUser = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001406 }
1407 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001408 if (scheduleWriteUser) {
Amith Yamasani12747872015-12-07 14:19:49 -08001409 scheduleWriteUser(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001410 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001411 }
1412
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001413 /**
1414 * If default guest restrictions haven't been initialized yet, add the basic
1415 * restrictions.
1416 */
1417 private void initDefaultGuestRestrictions() {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001418 synchronized (mGuestRestrictions) {
1419 if (mGuestRestrictions.isEmpty()) {
Samuel Tand9453b82016-03-14 15:57:02 -07001420 mGuestRestrictions.putBoolean(UserManager.DISALLOW_CONFIG_WIFI, true);
Fyodor Kupolove04462c2015-11-30 15:02:53 -08001421 mGuestRestrictions.putBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, true);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001422 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
1423 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
1424 }
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001425 }
1426 }
1427
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001428 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301429 public Bundle getDefaultGuestRestrictions() {
1430 checkManageUsersPermission("getDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001431 synchronized (mGuestRestrictions) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301432 return new Bundle(mGuestRestrictions);
1433 }
1434 }
1435
1436 @Override
1437 public void setDefaultGuestRestrictions(Bundle restrictions) {
1438 checkManageUsersPermission("setDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001439 synchronized (mGuestRestrictions) {
1440 mGuestRestrictions.clear();
1441 mGuestRestrictions.putAll(restrictions);
1442 }
1443 synchronized (mPackagesLock) {
1444 writeUserListLP();
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301445 }
1446 }
1447
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001448 /**
Pavel Grafov6a40f092016-10-25 15:46:51 +01001449 * See {@link UserManagerInternal#setDevicePolicyUserRestrictions}
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001450 */
Bookatzf56f2582019-09-04 16:06:41 -07001451 private void setDevicePolicyUserRestrictionsInner(@UserIdInt int userId,
1452 @Nullable Bundle restrictions, boolean isDeviceOwner, int cameraRestrictionScope) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001453 final Bundle global = new Bundle();
1454 final Bundle local = new Bundle();
1455
1456 // Sort restrictions into local and global ensuring they don't overlap.
1457 UserRestrictionsUtils.sortToGlobalAndLocal(restrictions, isDeviceOwner,
1458 cameraRestrictionScope, global, local);
1459
1460 boolean globalChanged, localChanged;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001461 synchronized (mRestrictionsLock) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001462 // Update global and local restrictions if they were changed.
1463 globalChanged = updateRestrictionsIfNeededLR(
1464 userId, global, mDevicePolicyGlobalUserRestrictions);
1465 localChanged = updateRestrictionsIfNeededLR(
1466 userId, local, mDevicePolicyLocalUserRestrictions);
1467
1468 if (isDeviceOwner) {
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001469 // Remember the global restriction owner userId to be able to make a distinction
1470 // in getUserRestrictionSource on who set local policies.
Pavel Grafov6a40f092016-10-25 15:46:51 +01001471 mDeviceOwnerUserId = userId;
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001472 } else {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001473 if (mDeviceOwnerUserId == userId) {
Zoltan Szatmary-Ban8a5536d2016-05-27 17:56:44 +01001474 // When profile owner sets restrictions it passes null global bundle and we
1475 // reset global restriction owner userId.
1476 // This means this user used to have DO, but now the DO is gone and the user
1477 // instead has PO.
Pavel Grafov6a40f092016-10-25 15:46:51 +01001478 mDeviceOwnerUserId = UserHandle.USER_NULL;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001479 }
1480 }
1481 }
1482 if (DBG) {
1483 Log.d(LOG_TAG, "setDevicePolicyUserRestrictions: userId=" + userId
1484 + " global=" + global + (globalChanged ? " (changed)" : "")
1485 + " local=" + local + (localChanged ? " (changed)" : "")
1486 );
1487 }
1488 // Don't call them within the mRestrictionsLock.
1489 synchronized (mPackagesLock) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001490 if (localChanged || globalChanged) {
Amith Yamasani12747872015-12-07 14:19:49 -08001491 writeUserLP(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001492 }
1493 }
1494
1495 synchronized (mRestrictionsLock) {
1496 if (globalChanged) {
1497 applyUserRestrictionsForAllUsersLR();
1498 } else if (localChanged) {
1499 applyUserRestrictionsLR(userId);
1500 }
1501 }
1502 }
1503
Pavel Grafov6a40f092016-10-25 15:46:51 +01001504 /**
1505 * Updates restriction bundle for a given user in a given restriction array. If new bundle is
1506 * empty, record is removed from the array.
1507 * @return whether restrictions bundle is different from the old one.
1508 */
Bookatzf56f2582019-09-04 16:06:41 -07001509 private boolean updateRestrictionsIfNeededLR(@UserIdInt int userId,
1510 @Nullable Bundle restrictions, SparseArray<Bundle> restrictionsArray) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001511 final boolean changed =
1512 !UserRestrictionsUtils.areEqual(restrictionsArray.get(userId), restrictions);
1513 if (changed) {
1514 if (!UserRestrictionsUtils.isEmpty(restrictions)) {
1515 restrictionsArray.put(userId, restrictions);
1516 } else {
1517 restrictionsArray.delete(userId);
1518 }
1519 }
1520 return changed;
1521 }
1522
Makoto Onuki068c54a2015-10-13 14:34:03 -07001523 @GuardedBy("mRestrictionsLock")
Bookatzf56f2582019-09-04 16:06:41 -07001524 private Bundle computeEffectiveUserRestrictionsLR(@UserIdInt int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001525 final Bundle baseRestrictions =
1526 UserRestrictionsUtils.nonNull(mBaseUserRestrictions.get(userId));
Pavel Grafov6a40f092016-10-25 15:46:51 +01001527 final Bundle global = UserRestrictionsUtils.mergeAll(mDevicePolicyGlobalUserRestrictions);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001528 final Bundle local = mDevicePolicyLocalUserRestrictions.get(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001529
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001530 if (UserRestrictionsUtils.isEmpty(global) && UserRestrictionsUtils.isEmpty(local)) {
1531 // Common case first.
1532 return baseRestrictions;
Makoto Onuki068c54a2015-10-13 14:34:03 -07001533 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001534 final Bundle effective = UserRestrictionsUtils.clone(baseRestrictions);
1535 UserRestrictionsUtils.merge(effective, global);
1536 UserRestrictionsUtils.merge(effective, local);
1537
Makoto Onuki068c54a2015-10-13 14:34:03 -07001538 return effective;
1539 }
1540
1541 @GuardedBy("mRestrictionsLock")
Bookatzf56f2582019-09-04 16:06:41 -07001542 private void invalidateEffectiveUserRestrictionsLR(@UserIdInt int userId) {
Makoto Onuki068c54a2015-10-13 14:34:03 -07001543 if (DBG) {
1544 Log.d(LOG_TAG, "invalidateEffectiveUserRestrictions userId=" + userId);
1545 }
1546 mCachedEffectiveUserRestrictions.remove(userId);
1547 }
1548
Bookatzf56f2582019-09-04 16:06:41 -07001549 private Bundle getEffectiveUserRestrictions(@UserIdInt int userId) {
Makoto Onuki068c54a2015-10-13 14:34:03 -07001550 synchronized (mRestrictionsLock) {
1551 Bundle restrictions = mCachedEffectiveUserRestrictions.get(userId);
1552 if (restrictions == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001553 restrictions = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001554 mCachedEffectiveUserRestrictions.put(userId, restrictions);
1555 }
1556 return restrictions;
Amith Yamasani8cd28b52014-06-08 17:54:27 -07001557 }
1558 }
1559
Makoto Onuki068c54a2015-10-13 14:34:03 -07001560 /** @return a specific user restriction that's in effect currently. */
1561 @Override
Bookatzf56f2582019-09-04 16:06:41 -07001562 public boolean hasUserRestriction(String restrictionKey, @UserIdInt int userId) {
Patrick Baumann2f2fd712019-07-31 15:18:53 -07001563 return mLocalService.hasUserRestriction(restrictionKey, userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001564 }
1565
Makoto Onukiacc50462018-02-14 14:13:49 -08001566 /** @return if any user has the given restriction. */
1567 @Override
1568 public boolean hasUserRestrictionOnAnyUser(String restrictionKey) {
1569 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1570 return false;
1571 }
1572 final List<UserInfo> users = getUsers(/* excludeDying= */ true);
1573 for (int i = 0; i < users.size(); i++) {
1574 final int userId = users.get(i).id;
1575 Bundle restrictions = getEffectiveUserRestrictions(userId);
1576 if (restrictions != null && restrictions.getBoolean(restrictionKey)) {
1577 return true;
1578 }
1579 }
1580 return false;
1581 }
1582
Makoto Onuki068c54a2015-10-13 14:34:03 -07001583 /**
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001584 * @hide
1585 *
1586 * Returns who set a user restriction on a user.
1587 * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
1588 * @param restrictionKey the string key representing the restriction
1589 * @param userId the id of the user for whom to retrieve the restrictions.
1590 * @return The source of user restriction. Any combination of
1591 * {@link UserManager#RESTRICTION_NOT_SET},
1592 * {@link UserManager#RESTRICTION_SOURCE_SYSTEM},
1593 * {@link UserManager#RESTRICTION_SOURCE_DEVICE_OWNER}
1594 * and {@link UserManager#RESTRICTION_SOURCE_PROFILE_OWNER}
1595 */
1596 @Override
Bookatzf56f2582019-09-04 16:06:41 -07001597 public int getUserRestrictionSource(String restrictionKey, @UserIdInt int userId) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001598 List<EnforcingUser> enforcingUsers = getUserRestrictionSources(restrictionKey, userId);
1599 // Get "bitwise or" of restriction sources for all enforcing users.
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001600 int result = UserManager.RESTRICTION_NOT_SET;
Pavel Grafov6a40f092016-10-25 15:46:51 +01001601 for (int i = enforcingUsers.size() - 1; i >= 0; i--) {
1602 result |= enforcingUsers.get(i).getUserRestrictionSource();
1603 }
1604 return result;
1605 }
1606
1607 @Override
1608 public List<EnforcingUser> getUserRestrictionSources(
1609 String restrictionKey, @UserIdInt int userId) {
1610 checkManageUsersPermission("getUserRestrictionSource");
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001611
1612 // Shortcut for the most common case
1613 if (!hasUserRestriction(restrictionKey, userId)) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001614 return Collections.emptyList();
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001615 }
1616
Pavel Grafov6a40f092016-10-25 15:46:51 +01001617 final List<EnforcingUser> result = new ArrayList<>();
1618
1619 // Check if it is base restriction.
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001620 if (hasBaseUserRestriction(restrictionKey, userId)) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001621 result.add(new EnforcingUser(
1622 UserHandle.USER_NULL, UserManager.RESTRICTION_SOURCE_SYSTEM));
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001623 }
1624
Pavel Grafov6a40f092016-10-25 15:46:51 +01001625 synchronized (mRestrictionsLock) {
1626 // Check if it is set by profile owner.
1627 Bundle profileOwnerRestrictions = mDevicePolicyLocalUserRestrictions.get(userId);
1628 if (UserRestrictionsUtils.contains(profileOwnerRestrictions, restrictionKey)) {
1629 result.add(getEnforcingUserLocked(userId));
1630 }
1631
1632 // Iterate over all users who enforce global restrictions.
1633 for (int i = mDevicePolicyGlobalUserRestrictions.size() - 1; i >= 0; i--) {
1634 Bundle globalRestrictions = mDevicePolicyGlobalUserRestrictions.valueAt(i);
1635 int profileUserId = mDevicePolicyGlobalUserRestrictions.keyAt(i);
1636 if (UserRestrictionsUtils.contains(globalRestrictions, restrictionKey)) {
1637 result.add(getEnforcingUserLocked(profileUserId));
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001638 }
1639 }
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001640 }
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001641 return result;
1642 }
1643
Andreas Gampea36dc622018-02-05 17:19:22 -08001644 @GuardedBy("mRestrictionsLock")
Pavel Grafov6a40f092016-10-25 15:46:51 +01001645 private EnforcingUser getEnforcingUserLocked(@UserIdInt int userId) {
1646 int source = mDeviceOwnerUserId == userId ? UserManager.RESTRICTION_SOURCE_DEVICE_OWNER
1647 : UserManager.RESTRICTION_SOURCE_PROFILE_OWNER;
1648 return new EnforcingUser(userId, source);
1649 }
1650
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001651 /**
Makoto Onuki068c54a2015-10-13 14:34:03 -07001652 * @return UserRestrictions that are in effect currently. This always returns a new
1653 * {@link Bundle}.
1654 */
Amith Yamasani8cd28b52014-06-08 17:54:27 -07001655 @Override
Bookatzf56f2582019-09-04 16:06:41 -07001656 public Bundle getUserRestrictions(@UserIdInt int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001657 return UserRestrictionsUtils.clone(getEffectiveUserRestrictions(userId));
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001658 }
1659
1660 @Override
Bookatzf56f2582019-09-04 16:06:41 -07001661 public boolean hasBaseUserRestriction(String restrictionKey, @UserIdInt int userId) {
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +00001662 checkManageUsersPermission("hasBaseUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001663 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1664 return false;
1665 }
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +00001666 synchronized (mRestrictionsLock) {
1667 Bundle bundle = mBaseUserRestrictions.get(userId);
1668 return (bundle != null && bundle.getBoolean(restrictionKey, false));
1669 }
1670 }
1671
1672 @Override
Bookatzf56f2582019-09-04 16:06:41 -07001673 public void setUserRestriction(String key, boolean value, @UserIdInt int userId) {
Fyodor Kupolovd4b26042015-07-27 14:30:59 -07001674 checkManageUsersPermission("setUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001675 if (!UserRestrictionsUtils.isValidRestriction(key)) {
1676 return;
1677 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001678 synchronized (mRestrictionsLock) {
1679 // Note we can't modify Bundles stored in mBaseUserRestrictions directly, so create
1680 // a copy.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001681 final Bundle newRestrictions = UserRestrictionsUtils.clone(
1682 mBaseUserRestrictions.get(userId));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001683 newRestrictions.putBoolean(key, value);
1684
Fyodor Kupolov82402752015-10-28 14:54:51 -07001685 updateUserRestrictionsInternalLR(newRestrictions, userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001686 }
1687 }
1688
Makoto Onuki068c54a2015-10-13 14:34:03 -07001689 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001690 * Optionally updating user restrictions, calculate the effective user restrictions and also
1691 * propagate to other services and system settings.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001692 *
Pavel Grafov6a40f092016-10-25 15:46:51 +01001693 * @param newBaseRestrictions User restrictions to set.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001694 * If null, will not update user restrictions and only does the propagation.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001695 * @param userId target user ID.
1696 */
1697 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001698 private void updateUserRestrictionsInternalLR(
Bookatzf56f2582019-09-04 16:06:41 -07001699 @Nullable Bundle newBaseRestrictions, @UserIdInt int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001700 final Bundle prevAppliedRestrictions = UserRestrictionsUtils.nonNull(
1701 mAppliedUserRestrictions.get(userId));
1702
1703 // Update base restrictions.
Pavel Grafov6a40f092016-10-25 15:46:51 +01001704 if (newBaseRestrictions != null) {
1705 // If newBaseRestrictions == the current one, it's probably a bug.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001706 final Bundle prevBaseRestrictions = mBaseUserRestrictions.get(userId);
1707
Pavel Grafov6a40f092016-10-25 15:46:51 +01001708 Preconditions.checkState(prevBaseRestrictions != newBaseRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001709 Preconditions.checkState(mCachedEffectiveUserRestrictions.get(userId)
Pavel Grafov6a40f092016-10-25 15:46:51 +01001710 != newBaseRestrictions);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001711
Pavel Grafov6a40f092016-10-25 15:46:51 +01001712 if (updateRestrictionsIfNeededLR(userId, newBaseRestrictions, mBaseUserRestrictions)) {
Amith Yamasani12747872015-12-07 14:19:49 -08001713 scheduleWriteUser(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001714 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001715 }
1716
Fyodor Kupolov82402752015-10-28 14:54:51 -07001717 final Bundle effective = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001718
Makoto Onuki759a7632015-10-28 16:43:10 -07001719 mCachedEffectiveUserRestrictions.put(userId, effective);
1720
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001721 // Apply the new restrictions.
Makoto Onuki4f160732015-10-27 17:15:38 -07001722 if (DBG) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001723 debug("Applying user restrictions: userId=" + userId
1724 + " new=" + effective + " prev=" + prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001725 }
1726
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001727 if (mAppOpsService != null) { // We skip it until system-ready.
Fyodor Kupolovec30ca32016-06-16 15:09:29 -07001728 mHandler.post(new Runnable() {
1729 @Override
1730 public void run() {
1731 try {
1732 mAppOpsService.setUserRestrictions(effective, mUserRestriconToken, userId);
1733 } catch (RemoteException e) {
1734 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
1735 }
1736 }
1737 });
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001738 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001739
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001740 propagateUserRestrictionsLR(userId, effective, prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001741
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001742 mAppliedUserRestrictions.put(userId, new Bundle(effective));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001743 }
1744
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001745 private void propagateUserRestrictionsLR(final int userId,
Makoto Onukid45a4a22015-11-02 17:17:38 -08001746 Bundle newRestrictions, Bundle prevRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001747 // Note this method doesn't touch any state, meaning it doesn't require mRestrictionsLock
1748 // actually, but we still need some kind of synchronization otherwise we might end up
1749 // calling listeners out-of-order, thus "LR".
1750
1751 if (UserRestrictionsUtils.areEqual(newRestrictions, prevRestrictions)) {
1752 return;
1753 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08001754
1755 final Bundle newRestrictionsFinal = new Bundle(newRestrictions);
1756 final Bundle prevRestrictionsFinal = new Bundle(prevRestrictions);
1757
1758 mHandler.post(new Runnable() {
1759 @Override
1760 public void run() {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07001761 UserRestrictionsUtils.applyUserRestrictions(
1762 mContext, userId, newRestrictionsFinal, prevRestrictionsFinal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001763
Makoto Onukid45a4a22015-11-02 17:17:38 -08001764 final UserRestrictionsListener[] listeners;
1765 synchronized (mUserRestrictionsListeners) {
1766 listeners = new UserRestrictionsListener[mUserRestrictionsListeners.size()];
1767 mUserRestrictionsListeners.toArray(listeners);
1768 }
1769 for (int i = 0; i < listeners.length; i++) {
1770 listeners[i].onUserRestrictionsChanged(userId,
1771 newRestrictionsFinal, prevRestrictionsFinal);
1772 }
Makoto Onukie72f81b2017-03-16 14:08:19 -07001773
1774 final Intent broadcast = new Intent(UserManager.ACTION_USER_RESTRICTIONS_CHANGED)
1775 .setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
1776 mContext.sendBroadcastAsUser(broadcast, UserHandle.of(userId));
Makoto Onukid45a4a22015-11-02 17:17:38 -08001777 }
1778 });
1779 }
1780
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001781 // Package private for the inner class.
Andreas Gampe2e8c7672018-07-20 13:01:08 -07001782 @GuardedBy("mRestrictionsLock")
Bookatzf56f2582019-09-04 16:06:41 -07001783 void applyUserRestrictionsLR(@UserIdInt int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001784 updateUserRestrictionsInternalLR(null, userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001785 }
1786
1787 @GuardedBy("mRestrictionsLock")
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001788 // Package private for the inner class.
1789 void applyUserRestrictionsForAllUsersLR() {
1790 if (DBG) {
1791 debug("applyUserRestrictionsForAllUsersLR");
1792 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001793 // First, invalidate all cached values.
Makoto Onuki4f160732015-10-27 17:15:38 -07001794 mCachedEffectiveUserRestrictions.clear();
1795
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001796 // We don't want to call into ActivityManagerService while taking a lock, so we'll call
Makoto Onuki068c54a2015-10-13 14:34:03 -07001797 // it on a handler.
1798 final Runnable r = new Runnable() {
1799 @Override
1800 public void run() {
1801 // Then get the list of running users.
1802 final int[] runningUsers;
1803 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001804 runningUsers = ActivityManager.getService().getRunningUserIds();
Makoto Onuki068c54a2015-10-13 14:34:03 -07001805 } catch (RemoteException e) {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001806 Log.w(LOG_TAG, "Unable to access ActivityManagerService");
Makoto Onuki068c54a2015-10-13 14:34:03 -07001807 return;
1808 }
1809 // Then re-calculate the effective restrictions and apply, only for running users.
1810 // It's okay if a new user has started after the getRunningUserIds() call,
1811 // because we'll do the same thing (re-calculate the restrictions and apply)
1812 // when we start a user.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001813 synchronized (mRestrictionsLock) {
1814 for (int i = 0; i < runningUsers.length; i++) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001815 applyUserRestrictionsLR(runningUsers[i]);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001816 }
1817 }
1818 }
1819 };
1820 mHandler.post(r);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001821 }
1822
Amith Yamasani258848d2012-08-10 17:06:33 -07001823 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001824 * Check if we've hit the limit of how many users can be created.
1825 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001826 private boolean isUserLimitReached() {
1827 int count;
1828 synchronized (mUsersLock) {
1829 count = getAliveUsersExcludingGuestsCountLU();
1830 }
1831 return count >= UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001832 }
1833
1834 @Override
Bookatzf56f2582019-09-04 16:06:41 -07001835 public boolean canAddMoreManagedProfiles(@UserIdInt int userId, boolean allowedToRemoveOne) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001836 checkManageUsersPermission("check if more managed profiles can be added.");
1837 if (ActivityManager.isLowRamDeviceStatic()) {
1838 return false;
1839 }
Fyodor Kupolovb6157992015-06-05 15:32:28 -07001840 if (!mContext.getPackageManager().hasSystemFeature(
1841 PackageManager.FEATURE_MANAGED_USERS)) {
1842 return false;
1843 }
Nicolas Prevotb8186812015-08-06 15:00:03 +01001844 // Limit number of managed profiles that can be created
Benjamin Franzc8776152017-01-06 14:16:41 +00001845 final int managedProfilesCount = getProfiles(userId, false).size() - 1;
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001846 final int profilesRemovedCount = managedProfilesCount > 0 && allowedToRemoveOne ? 1 : 0;
Kenny Guy02c89902016-11-15 19:36:38 +00001847 if (managedProfilesCount - profilesRemovedCount >= getMaxManagedProfiles()) {
Nicolas Prevotb8186812015-08-06 15:00:03 +01001848 return false;
1849 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001850 synchronized(mUsersLock) {
1851 UserInfo userInfo = getUserInfoLU(userId);
yuanhao47f9f7c2017-01-18 09:54:45 +08001852 if (userInfo == null || !userInfo.canHaveProfile()) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001853 return false;
1854 }
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001855 int usersCountAfterRemoving = getAliveUsersExcludingGuestsCountLU()
1856 - profilesRemovedCount;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001857 // We allow creating a managed profile in the special case where there is only one user.
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001858 return usersCountAfterRemoving == 1
1859 || usersCountAfterRemoving < UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001860 }
1861 }
1862
Andreas Gampe2e8c7672018-07-20 13:01:08 -07001863 @GuardedBy("mUsersLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001864 private int getAliveUsersExcludingGuestsCountLU() {
Amith Yamasanif584f012014-05-19 17:57:25 -07001865 int aliveUserCount = 0;
1866 final int totalUserCount = mUsers.size();
1867 // Skip over users being removed
1868 for (int i = 0; i < totalUserCount; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001869 UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov6e99d3f2016-11-01 17:18:41 -07001870 if (!mRemovingUserIds.get(user.id) && !user.isGuest()) {
Amith Yamasanif584f012014-05-19 17:57:25 -07001871 aliveUserCount++;
1872 }
1873 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001874 return aliveUserCount;
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001875 }
1876
1877 /**
Amith Yamasani195263742012-08-21 15:40:12 -07001878 * Enforces that only the system UID or root's UID or apps that have the
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001879 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} and
1880 * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL INTERACT_ACROSS_USERS_FULL}
1881 * permissions can make certain calls to the UserManager.
1882 *
1883 * @param message used as message if SecurityException is thrown
1884 * @throws SecurityException if the caller does not have enough privilege.
1885 */
1886 private static final void checkManageUserAndAcrossUsersFullPermission(String message) {
1887 final int uid = Binder.getCallingUid();
jovanakf24ad492018-05-18 12:15:59 -07001888
1889 if (uid == Process.SYSTEM_UID || uid == 0) {
1890 // System UID or root's UID are granted privilege.
1891 return;
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001892 }
jovanakf24ad492018-05-18 12:15:59 -07001893
1894 if (hasPermissionGranted(Manifest.permission.MANAGE_USERS, uid)
1895 && hasPermissionGranted(Manifest.permission.INTERACT_ACROSS_USERS_FULL, uid)) {
1896 // Apps with both permissions are granted privilege.
1897 return;
1898 }
1899
1900 throw new SecurityException(
1901 "You need MANAGE_USERS and INTERACT_ACROSS_USERS_FULL permission to: " + message);
1902 }
1903
1904 private static boolean hasPermissionGranted(String permission, int uid) {
1905 return ActivityManager.checkComponentPermission(
1906 permission, uid, /* owningUid = */-1, /* exported = */ true) ==
1907 PackageManager.PERMISSION_GRANTED;
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001908 }
1909
1910 /**
1911 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001912 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -07001913 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -07001914 *
1915 * @param message used as message if SecurityException is thrown
1916 * @throws SecurityException if the caller is not system or root
Tony Mak4dc008c2016-03-16 10:46:49 +00001917 * @see #hasManageUsersPermission()
Amith Yamasani258848d2012-08-10 17:06:33 -07001918 */
Amith Yamasanibe465322014-04-24 13:45:17 -07001919 private static final void checkManageUsersPermission(String message) {
Tony Mak4dc008c2016-03-16 10:46:49 +00001920 if (!hasManageUsersPermission()) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001921 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
1922 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -04001923 }
1924
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001925 /**
Sudheer Shankaf5cea032016-06-08 17:13:24 -07001926 * Enforces that only the system UID or root's UID or apps that have the
1927 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or
1928 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS}
1929 * can make certain calls to the UserManager.
1930 *
1931 * @param message used as message if SecurityException is thrown
1932 * @throws SecurityException if the caller is not system or root
1933 * @see #hasManageOrCreateUsersPermission()
1934 */
1935 private static final void checkManageOrCreateUsersPermission(String message) {
1936 if (!hasManageOrCreateUsersPermission()) {
1937 throw new SecurityException(
1938 "You either need MANAGE_USERS or CREATE_USERS permission to: " + message);
1939 }
1940 }
1941
1942 /**
1943 * Similar to {@link #checkManageOrCreateUsersPermission(String)} but when the caller is tries
1944 * to create user/profiles other than what is allowed for
1945 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS} permission, then it will only
1946 * allow callers with {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} permission.
1947 */
1948 private static final void checkManageOrCreateUsersPermission(int creationFlags) {
1949 if ((creationFlags & ~ALLOWED_FLAGS_FOR_CREATE_USERS_PERMISSION) == 0) {
1950 if (!hasManageOrCreateUsersPermission()) {
1951 throw new SecurityException("You either need MANAGE_USERS or CREATE_USERS "
1952 + "permission to create an user with flags: " + creationFlags);
1953 }
1954 } else if (!hasManageUsersPermission()) {
1955 throw new SecurityException("You need MANAGE_USERS permission to create an user "
1956 + " with flags: " + creationFlags);
1957 }
1958 }
1959
1960 /**
Tony Mak4dc008c2016-03-16 10:46:49 +00001961 * @return whether the calling UID is system UID or root's UID or the calling app has the
1962 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}.
1963 */
1964 private static final boolean hasManageUsersPermission() {
1965 final int callingUid = Binder.getCallingUid();
1966 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
1967 || callingUid == Process.ROOT_UID
jovanakf24ad492018-05-18 12:15:59 -07001968 || hasPermissionGranted(android.Manifest.permission.MANAGE_USERS, callingUid);
Tony Mak4dc008c2016-03-16 10:46:49 +00001969 }
1970
1971 /**
Sudheer Shankaf5cea032016-06-08 17:13:24 -07001972 * @return whether the calling UID is system UID or root's UID or the calling app has the
Bookatzcde3d922019-03-08 14:30:00 -08001973 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or the provided permission.
Sudheer Shankaf5cea032016-06-08 17:13:24 -07001974 */
Bookatzcde3d922019-03-08 14:30:00 -08001975 private static final boolean hasManageUsersOrPermission(String alternativePermission) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07001976 final int callingUid = Binder.getCallingUid();
1977 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
1978 || callingUid == Process.ROOT_UID
jovanakf24ad492018-05-18 12:15:59 -07001979 || hasPermissionGranted(android.Manifest.permission.MANAGE_USERS, callingUid)
Bookatzcde3d922019-03-08 14:30:00 -08001980 || hasPermissionGranted(alternativePermission, callingUid);
1981 }
1982
1983 /**
1984 * @return whether the calling UID is system UID or root's UID or the calling app has the
1985 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or
1986 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS}.
1987 */
1988 private static final boolean hasManageOrCreateUsersPermission() {
1989 return hasManageUsersOrPermission(android.Manifest.permission.CREATE_USERS);
Sudheer Shankaf5cea032016-06-08 17:13:24 -07001990 }
1991
1992 /**
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001993 * Enforces that only the system UID or root's UID (on any user) can make certain calls to the
1994 * UserManager.
1995 *
1996 * @param message used as message if SecurityException is thrown
1997 * @throws SecurityException if the caller is not system or root
1998 */
1999 private static void checkSystemOrRoot(String message) {
2000 final int uid = Binder.getCallingUid();
2001 if (!UserHandle.isSameApp(uid, Process.SYSTEM_UID) && uid != Process.ROOT_UID) {
2002 throw new SecurityException("Only system may: " + message);
2003 }
2004 }
2005
Fyodor Kupolov82402752015-10-28 14:54:51 -07002006 private void writeBitmapLP(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002007 try {
2008 File dir = new File(mUsersDir, Integer.toString(info.id));
2009 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +01002010 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002011 if (!dir.exists()) {
2012 dir.mkdir();
2013 FileUtils.setPermissions(
2014 dir.getPath(),
2015 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
2016 -1, -1);
2017 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07002018 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +01002019 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01002020 && tmp.renameTo(file) && SELinux.restorecon(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -07002021 info.iconPath = file.getAbsolutePath();
2022 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07002023 try {
2024 os.close();
2025 } catch (IOException ioe) {
2026 // What the ... !
2027 }
Adrian Roos1bdff912015-02-17 15:51:35 +01002028 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002029 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002030 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002031 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002032 }
2033
Amith Yamasani0b285492011-04-14 17:35:23 -07002034 /**
2035 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
2036 * cache it elsewhere.
2037 * @return the array of user ids.
2038 */
Dianne Hackborn1676c852012-09-10 14:52:30 -07002039 public int[] getUserIds() {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002040 synchronized (mUsersLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07002041 return mUserIds;
2042 }
Amith Yamasani0b285492011-04-14 17:35:23 -07002043 }
2044
Andreas Gampe2e8c7672018-07-20 13:01:08 -07002045 @GuardedBy({"mRestrictionsLock", "mPackagesLock"})
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002046 private void readUserListLP() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002047 if (!mUserListFile.exists()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002048 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002049 return;
2050 }
2051 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07002052 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002053 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07002054 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002055 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002056 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002057 int type;
2058 while ((type = parser.next()) != XmlPullParser.START_TAG
2059 && type != XmlPullParser.END_DOCUMENT) {
Amith Yamasani12747872015-12-07 14:19:49 -08002060 // Skip
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002061 }
2062
2063 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07002064 Slog.e(LOG_TAG, "Unable to read user list");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002065 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002066 return;
2067 }
2068
Amith Yamasani2a003292012-08-14 18:25:45 -07002069 mNextSerialNumber = -1;
2070 if (parser.getName().equals(TAG_USERS)) {
2071 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
2072 if (lastSerialNumber != null) {
2073 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
2074 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07002075 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
2076 if (versionNumber != null) {
2077 mUserVersion = Integer.parseInt(versionNumber);
2078 }
Amith Yamasani2a003292012-08-14 18:25:45 -07002079 }
2080
Pavel Grafov6a40f092016-10-25 15:46:51 +01002081 // Pre-O global user restriction were stored as a single bundle (as opposed to per-user
2082 // currently), take care of it in case of upgrade.
2083 Bundle oldDevicePolicyGlobalUserRestrictions = null;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002084
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002085 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05302086 if (type == XmlPullParser.START_TAG) {
2087 final String name = parser.getName();
2088 if (name.equals(TAG_USER)) {
2089 String id = parser.getAttributeValue(null, ATTR_ID);
Amith Yamasani6f34b412012-10-22 18:19:27 -07002090
Amith Yamasani12747872015-12-07 14:19:49 -08002091 UserData userData = readUserLP(Integer.parseInt(id));
2092
2093 if (userData != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002094 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002095 mUsers.put(userData.info.id, userData);
2096 if (mNextSerialNumber < 0
2097 || mNextSerialNumber <= userData.info.id) {
2098 mNextSerialNumber = userData.info.id + 1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002099 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05302100 }
Amith Yamasani2a003292012-08-14 18:25:45 -07002101 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05302102 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -08002103 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2104 && type != XmlPullParser.END_TAG) {
2105 if (type == XmlPullParser.START_TAG) {
2106 if (parser.getName().equals(TAG_RESTRICTIONS)) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002107 synchronized (mGuestRestrictions) {
Fyodor Kupoloveafee022017-03-15 17:09:04 -07002108 UserRestrictionsUtils
2109 .readRestrictions(parser, mGuestRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002110 }
Amith Yamasanida0b1682014-11-21 12:58:17 -08002111 }
2112 break;
2113 }
2114 }
Pavel Grafov6a40f092016-10-25 15:46:51 +01002115 } else if (name.equals(TAG_DEVICE_OWNER_USER_ID)
2116 // Legacy name, should only be encountered when upgrading from pre-O.
2117 || name.equals(TAG_GLOBAL_RESTRICTION_OWNER_ID)) {
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01002118 String ownerUserId = parser.getAttributeValue(null, ATTR_ID);
2119 if (ownerUserId != null) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01002120 mDeviceOwnerUserId = Integer.parseInt(ownerUserId);
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01002121 }
Pavel Grafov6a40f092016-10-25 15:46:51 +01002122 } else if (name.equals(TAG_DEVICE_POLICY_RESTRICTIONS)) {
2123 // Should only happen when upgrading from pre-O (version < 7).
2124 oldDevicePolicyGlobalUserRestrictions =
2125 UserRestrictionsUtils.readRestrictions(parser);
Amith Yamasani258848d2012-08-10 17:06:33 -07002126 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002127 }
2128 }
Pavel Grafov6a40f092016-10-25 15:46:51 +01002129
Fyodor Kupolov82402752015-10-28 14:54:51 -07002130 updateUserIds();
Pavel Grafov6a40f092016-10-25 15:46:51 +01002131 upgradeIfNecessaryLP(oldDevicePolicyGlobalUserRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002132 } catch (IOException | XmlPullParserException e) {
2133 fallbackToSingleUserLP();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08002134 } finally {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002135 IoUtils.closeQuietly(fis);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002136 }
2137 }
2138
Amith Yamasani6f34b412012-10-22 18:19:27 -07002139 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -08002140 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Pavel Grafov6a40f092016-10-25 15:46:51 +01002141 * @param oldGlobalUserRestrictions Pre-O global device policy restrictions.
Amith Yamasani6f34b412012-10-22 18:19:27 -07002142 */
Andreas Gampe2e8c7672018-07-20 13:01:08 -07002143 @GuardedBy({"mRestrictionsLock", "mPackagesLock"})
Pavel Grafov6a40f092016-10-25 15:46:51 +01002144 private void upgradeIfNecessaryLP(Bundle oldGlobalUserRestrictions) {
Bookatz75f0a072019-08-05 14:12:16 -07002145 Set<Integer> userIdsToWrite = new ArraySet<>();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002146 final int originalVersion = mUserVersion;
Amith Yamasani6f34b412012-10-22 18:19:27 -07002147 int userVersion = mUserVersion;
2148 if (userVersion < 1) {
2149 // Assign a proper name for the owner, if not initialized correctly before
Amith Yamasani12747872015-12-07 14:19:49 -08002150 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
2151 if ("Primary".equals(userData.info.name)) {
2152 userData.info.name =
2153 mContext.getResources().getString(com.android.internal.R.string.owner_name);
Bookatz75f0a072019-08-05 14:12:16 -07002154 userIdsToWrite.add(userData.info.id);
Amith Yamasani6f34b412012-10-22 18:19:27 -07002155 }
2156 userVersion = 1;
2157 }
2158
Amith Yamasanibc9625052012-11-15 14:39:18 -08002159 if (userVersion < 2) {
2160 // Owner should be marked as initialized
Amith Yamasani12747872015-12-07 14:19:49 -08002161 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
2162 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
2163 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
Bookatz75f0a072019-08-05 14:12:16 -07002164 userIdsToWrite.add(userData.info.id);
Amith Yamasanibc9625052012-11-15 14:39:18 -08002165 }
2166 userVersion = 2;
2167 }
2168
Amith Yamasani350962c2013-08-06 11:18:53 -07002169
Amith Yamasani5e486f52013-08-07 11:06:44 -07002170 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -07002171 userVersion = 4;
2172 }
2173
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07002174 if (userVersion < 5) {
2175 initDefaultGuestRestrictions();
2176 userVersion = 5;
2177 }
2178
Fyodor Kupolov1c363152015-09-02 13:27:21 -07002179 if (userVersion < 6) {
2180 final boolean splitSystemUser = UserManager.isSplitSystemUser();
Fyodor Kupolov82402752015-10-28 14:54:51 -07002181 synchronized (mUsersLock) {
2182 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002183 UserData userData = mUsers.valueAt(i);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002184 // In non-split mode, only user 0 can have restricted profiles
Amith Yamasani12747872015-12-07 14:19:49 -08002185 if (!splitSystemUser && userData.info.isRestricted()
2186 && (userData.info.restrictedProfileParentId
2187 == UserInfo.NO_PROFILE_GROUP_ID)) {
2188 userData.info.restrictedProfileParentId = UserHandle.USER_SYSTEM;
Bookatz75f0a072019-08-05 14:12:16 -07002189 userIdsToWrite.add(userData.info.id);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002190 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07002191 }
2192 }
2193 userVersion = 6;
2194 }
2195
Pavel Grafov6a40f092016-10-25 15:46:51 +01002196 if (userVersion < 7) {
2197 // Previously only one user could enforce global restrictions, now it is per-user.
2198 synchronized (mRestrictionsLock) {
2199 if (!UserRestrictionsUtils.isEmpty(oldGlobalUserRestrictions)
2200 && mDeviceOwnerUserId != UserHandle.USER_NULL) {
2201 mDevicePolicyGlobalUserRestrictions.put(
2202 mDeviceOwnerUserId, oldGlobalUserRestrictions);
2203 }
2204 // ENSURE_VERIFY_APPS is now enforced globally even if put by profile owner, so move
2205 // it from local to global bundle for all users who set it.
2206 UserRestrictionsUtils.moveRestriction(UserManager.ENSURE_VERIFY_APPS,
2207 mDevicePolicyLocalUserRestrictions, mDevicePolicyGlobalUserRestrictions
2208 );
2209 }
2210 userVersion = 7;
2211 }
2212
Bookatz75f0a072019-08-05 14:12:16 -07002213 if (userVersion < 8) {
2214 // Added FLAG_FULL and FLAG_SYSTEM flags.
2215 synchronized (mUsersLock) {
2216 UserData userData = mUsers.get(UserHandle.USER_SYSTEM);
2217 userData.info.flags |= UserInfo.FLAG_SYSTEM;
2218 if (!UserManager.isHeadlessSystemUserMode()) {
2219 userData.info.flags |= UserInfo.FLAG_FULL;
2220 }
2221 userIdsToWrite.add(userData.info.id);
2222
2223 // Mark FULL all non-profile users except USER_SYSTEM.
2224 // Start index at 1 since USER_SYSTEM is the smallest userId and we're skipping it.
2225 for (int i = 1; i < mUsers.size(); i++) {
2226 userData = mUsers.valueAt(i);
2227 if ((userData.info.flags & UserInfo.FLAG_MANAGED_PROFILE) == 0) {
2228 userData.info.flags |= UserInfo.FLAG_FULL;
2229 userIdsToWrite.add(userData.info.id);
2230 }
2231 }
2232 }
2233 userVersion = 8;
2234 }
2235
Amith Yamasani6f34b412012-10-22 18:19:27 -07002236 if (userVersion < USER_VERSION) {
2237 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
2238 + USER_VERSION);
2239 } else {
2240 mUserVersion = userVersion;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002241
2242 if (originalVersion < mUserVersion) {
Bookatz75f0a072019-08-05 14:12:16 -07002243 for (int userId : userIdsToWrite) {
2244 UserData userData = getUserDataNoChecks(userId);
2245 if (userData != null) {
2246 writeUserLP(userData);
2247 }
2248 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002249 writeUserListLP();
2250 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07002251 }
2252 }
2253
Andreas Gampe2e8c7672018-07-20 13:01:08 -07002254 @GuardedBy({"mPackagesLock", "mRestrictionsLock"})
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002255 private void fallbackToSingleUserLP() {
Ying Zheng215116f2019-09-11 12:50:09 -07002256 int flags = UserInfo.FLAG_SYSTEM | UserInfo.FLAG_INITIALIZED | UserInfo.FLAG_ADMIN
2257 | UserInfo.FLAG_PRIMARY;
2258 // In headless system user mode, headless system user is not a full user.
Bookatz75f0a072019-08-05 14:12:16 -07002259 if (!UserManager.isHeadlessSystemUserMode()) {
Ying Zheng215116f2019-09-11 12:50:09 -07002260 flags |= UserInfo.FLAG_FULL;
Bookatz75f0a072019-08-05 14:12:16 -07002261 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -07002262 // Create the system user
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07002263 UserInfo system = new UserInfo(UserHandle.USER_SYSTEM, null, null, flags);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002264 UserData userData = putUserInfo(system);
Amith Yamasani634cf312012-10-04 17:34:21 -07002265 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -04002266 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -08002267
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05002268 Bundle restrictions = new Bundle();
Mahaver Chopra3d9805d2016-07-07 16:25:05 +01002269 try {
2270 final String[] defaultFirstUserRestrictions = mContext.getResources().getStringArray(
2271 com.android.internal.R.array.config_defaultFirstUserRestrictions);
2272 for (String userRestriction : defaultFirstUserRestrictions) {
2273 if (UserRestrictionsUtils.isValidRestriction(userRestriction)) {
2274 restrictions.putBoolean(userRestriction, true);
2275 }
2276 }
2277 } catch (Resources.NotFoundException e) {
2278 Log.e(LOG_TAG, "Couldn't find resource: config_defaultFirstUserRestrictions", e);
2279 }
2280
Pavel Grafov6a40f092016-10-25 15:46:51 +01002281 if (!restrictions.isEmpty()) {
2282 synchronized (mRestrictionsLock) {
2283 mBaseUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions);
2284 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07002285 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08002286
Fyodor Kupolov82402752015-10-28 14:54:51 -07002287 updateUserIds();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07002288 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002289
Amith Yamasani12747872015-12-07 14:19:49 -08002290 writeUserLP(userData);
Jeff Sharkeycd575992016-03-29 14:12:49 -06002291 writeUserListLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002292 }
2293
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07002294 private String getOwnerName() {
2295 return mContext.getResources().getString(com.android.internal.R.string.owner_name);
2296 }
2297
Bookatz75f0a072019-08-05 14:12:16 -07002298 private void scheduleWriteUser(UserData userData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002299 if (DBG) {
2300 debug("scheduleWriteUser");
2301 }
Makoto Onuki9e935a32015-11-06 14:24:24 -08002302 // No need to wrap it within a lock -- worst case, we'll just post the same message
2303 // twice.
Bookatz75f0a072019-08-05 14:12:16 -07002304 if (!mHandler.hasMessages(WRITE_USER_MSG, userData)) {
2305 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, userData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002306 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
2307 }
2308 }
2309
Amith Yamasani12747872015-12-07 14:19:49 -08002310 private void writeUserLP(UserData userData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002311 if (DBG) {
Amith Yamasani12747872015-12-07 14:19:49 -08002312 debug("writeUserLP " + userData);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002313 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002314 FileOutputStream fos = null;
Amith Yamasani12747872015-12-07 14:19:49 -08002315 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userData.info.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002316 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07002317 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002318 final BufferedOutputStream bos = new BufferedOutputStream(fos);
Kenny Guy02c89902016-11-15 19:36:38 +00002319 writeUserLP(userData, bos);
Amith Yamasani2a003292012-08-14 18:25:45 -07002320 userFile.finishWrite(fos);
2321 } catch (Exception ioe) {
Jeff Sharkeycd575992016-03-29 14:12:49 -06002322 Slog.e(LOG_TAG, "Error writing user info " + userData.info.id, ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -07002323 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002324 }
2325 }
2326
2327 /*
Kenny Guy02c89902016-11-15 19:36:38 +00002328 * Writes the user file in this format:
2329 *
2330 * <user flags="20039023" id="0">
2331 * <name>Primary</name>
2332 * </user>
2333 */
2334 @VisibleForTesting
2335 void writeUserLP(UserData userData, OutputStream os)
2336 throws IOException, XmlPullParserException {
2337 // XmlSerializer serializer = XmlUtils.serializerInstance();
2338 final XmlSerializer serializer = new FastXmlSerializer();
2339 serializer.setOutput(os, StandardCharsets.UTF_8.name());
2340 serializer.startDocument(null, true);
2341 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2342
2343 final UserInfo userInfo = userData.info;
2344 serializer.startTag(null, TAG_USER);
2345 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
2346 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
2347 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
2348 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
2349 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
2350 Long.toString(userInfo.lastLoggedInTime));
2351 if (userInfo.lastLoggedInFingerprint != null) {
2352 serializer.attribute(null, ATTR_LAST_LOGGED_IN_FINGERPRINT,
2353 userInfo.lastLoggedInFingerprint);
2354 }
2355 if (userInfo.iconPath != null) {
2356 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
2357 }
2358 if (userInfo.partial) {
2359 serializer.attribute(null, ATTR_PARTIAL, "true");
2360 }
2361 if (userInfo.guestToRemove) {
2362 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
2363 }
2364 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
2365 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
2366 Integer.toString(userInfo.profileGroupId));
2367 }
2368 serializer.attribute(null, ATTR_PROFILE_BADGE,
2369 Integer.toString(userInfo.profileBadge));
2370 if (userInfo.restrictedProfileParentId != UserInfo.NO_PROFILE_GROUP_ID) {
2371 serializer.attribute(null, ATTR_RESTRICTED_PROFILE_PARENT_ID,
2372 Integer.toString(userInfo.restrictedProfileParentId));
2373 }
2374 // Write seed data
2375 if (userData.persistSeedData) {
2376 if (userData.seedAccountName != null) {
2377 serializer.attribute(null, ATTR_SEED_ACCOUNT_NAME, userData.seedAccountName);
2378 }
2379 if (userData.seedAccountType != null) {
2380 serializer.attribute(null, ATTR_SEED_ACCOUNT_TYPE, userData.seedAccountType);
2381 }
2382 }
2383 if (userInfo.name != null) {
2384 serializer.startTag(null, TAG_NAME);
2385 serializer.text(userInfo.name);
2386 serializer.endTag(null, TAG_NAME);
2387 }
2388 synchronized (mRestrictionsLock) {
2389 UserRestrictionsUtils.writeRestrictions(serializer,
2390 mBaseUserRestrictions.get(userInfo.id), TAG_RESTRICTIONS);
2391 UserRestrictionsUtils.writeRestrictions(serializer,
2392 mDevicePolicyLocalUserRestrictions.get(userInfo.id),
2393 TAG_DEVICE_POLICY_RESTRICTIONS);
Pavel Grafov6a40f092016-10-25 15:46:51 +01002394 UserRestrictionsUtils.writeRestrictions(serializer,
2395 mDevicePolicyGlobalUserRestrictions.get(userInfo.id),
2396 TAG_DEVICE_POLICY_GLOBAL_RESTRICTIONS);
Kenny Guy02c89902016-11-15 19:36:38 +00002397 }
2398
2399 if (userData.account != null) {
2400 serializer.startTag(null, TAG_ACCOUNT);
2401 serializer.text(userData.account);
2402 serializer.endTag(null, TAG_ACCOUNT);
2403 }
2404
2405 if (userData.persistSeedData && userData.seedAccountOptions != null) {
2406 serializer.startTag(null, TAG_SEED_ACCOUNT_OPTIONS);
2407 userData.seedAccountOptions.saveToXml(serializer);
2408 serializer.endTag(null, TAG_SEED_ACCOUNT_OPTIONS);
2409 }
2410
arangelov9b632d72018-12-07 23:21:22 +00002411 if (userData.getLastRequestQuietModeEnabledMillis() != 0L) {
2412 serializer.startTag(/* namespace */ null, TAG_LAST_REQUEST_QUIET_MODE_ENABLED_CALL);
2413 serializer.text(String.valueOf(userData.getLastRequestQuietModeEnabledMillis()));
2414 serializer.endTag(/* namespace */ null, TAG_LAST_REQUEST_QUIET_MODE_ENABLED_CALL);
2415 }
2416
Kenny Guy02c89902016-11-15 19:36:38 +00002417 serializer.endTag(null, TAG_USER);
2418
2419 serializer.endDocument();
2420 }
2421
2422 /*
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002423 * Writes the user list file in this format:
2424 *
Amith Yamasani2a003292012-08-14 18:25:45 -07002425 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002426 * <user id="0"></user>
2427 * <user id="2"></user>
2428 * </users>
2429 */
Andreas Gampe2e8c7672018-07-20 13:01:08 -07002430 @GuardedBy({"mRestrictionsLock", "mPackagesLock"})
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002431 private void writeUserListLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002432 if (DBG) {
2433 debug("writeUserList");
2434 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002435 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07002436 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002437 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07002438 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002439 final BufferedOutputStream bos = new BufferedOutputStream(fos);
2440
2441 // XmlSerializer serializer = XmlUtils.serializerInstance();
2442 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002443 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002444 serializer.startDocument(null, true);
2445 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2446
2447 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -07002448 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -07002449 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002450
Adam Lesinskieddeb492014-09-08 17:50:03 -07002451 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002452 synchronized (mGuestRestrictions) {
2453 UserRestrictionsUtils
2454 .writeRestrictions(serializer, mGuestRestrictions, TAG_RESTRICTIONS);
2455 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05302456 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Pavel Grafov6a40f092016-10-25 15:46:51 +01002457 serializer.startTag(null, TAG_DEVICE_OWNER_USER_ID);
2458 serializer.attribute(null, ATTR_ID, Integer.toString(mDeviceOwnerUserId));
2459 serializer.endTag(null, TAG_DEVICE_OWNER_USER_ID);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002460 int[] userIdsToWrite;
2461 synchronized (mUsersLock) {
2462 userIdsToWrite = new int[mUsers.size()];
2463 for (int i = 0; i < userIdsToWrite.length; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002464 UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002465 userIdsToWrite[i] = user.id;
2466 }
2467 }
2468 for (int id : userIdsToWrite) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002469 serializer.startTag(null, TAG_USER);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002470 serializer.attribute(null, ATTR_ID, Integer.toString(id));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002471 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002472 }
2473
2474 serializer.endTag(null, TAG_USERS);
2475
2476 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07002477 userListFile.finishWrite(fos);
2478 } catch (Exception e) {
2479 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -07002480 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002481 }
2482 }
2483
Amith Yamasani12747872015-12-07 14:19:49 -08002484 private UserData readUserLP(int id) {
Kenny Guy02c89902016-11-15 19:36:38 +00002485 FileInputStream fis = null;
2486 try {
2487 AtomicFile userFile =
2488 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
2489 fis = userFile.openRead();
2490 return readUserLP(id, fis);
2491 } catch (IOException ioe) {
2492 Slog.e(LOG_TAG, "Error reading user list");
2493 } catch (XmlPullParserException pe) {
2494 Slog.e(LOG_TAG, "Error reading user list");
2495 } finally {
2496 IoUtils.closeQuietly(fis);
2497 }
2498 return null;
2499 }
2500
2501 @VisibleForTesting
2502 UserData readUserLP(int id, InputStream is) throws IOException,
2503 XmlPullParserException {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002504 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -07002505 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002506 String name = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -08002507 String account = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002508 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -07002509 long creationTime = 0L;
2510 long lastLoggedInTime = 0L;
arangelov9b632d72018-12-07 23:21:22 +00002511 long lastRequestQuietModeEnabledTimestamp = 0L;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002512 String lastLoggedInFingerprint = null;
Kenny Guy2a764942014-04-02 13:29:20 +01002513 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Kenny Guy02c89902016-11-15 19:36:38 +00002514 int profileBadge = 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002515 int restrictedProfileParentId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002516 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -07002517 boolean guestToRemove = false;
Amith Yamasani12747872015-12-07 14:19:49 -08002518 boolean persistSeedData = false;
2519 String seedAccountName = null;
2520 String seedAccountType = null;
2521 PersistableBundle seedAccountOptions = null;
Pavel Grafov6a40f092016-10-25 15:46:51 +01002522 Bundle baseRestrictions = null;
2523 Bundle localRestrictions = null;
2524 Bundle globalRestrictions = null;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002525
Kenny Guy02c89902016-11-15 19:36:38 +00002526 XmlPullParser parser = Xml.newPullParser();
2527 parser.setInput(is, StandardCharsets.UTF_8.name());
2528 int type;
2529 while ((type = parser.next()) != XmlPullParser.START_TAG
2530 && type != XmlPullParser.END_DOCUMENT) {
2531 // Skip
2532 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002533
Kenny Guy02c89902016-11-15 19:36:38 +00002534 if (type != XmlPullParser.START_TAG) {
2535 Slog.e(LOG_TAG, "Unable to read user " + id);
2536 return null;
2537 }
2538
2539 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
2540 int storedId = readIntAttribute(parser, ATTR_ID, -1);
2541 if (storedId != id) {
2542 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002543 return null;
2544 }
Kenny Guy02c89902016-11-15 19:36:38 +00002545 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
2546 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
2547 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
2548 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
2549 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
2550 lastLoggedInFingerprint = parser.getAttributeValue(null,
2551 ATTR_LAST_LOGGED_IN_FINGERPRINT);
2552 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
2553 UserInfo.NO_PROFILE_GROUP_ID);
2554 profileBadge = readIntAttribute(parser, ATTR_PROFILE_BADGE, 0);
2555 restrictedProfileParentId = readIntAttribute(parser,
2556 ATTR_RESTRICTED_PROFILE_PARENT_ID, UserInfo.NO_PROFILE_GROUP_ID);
2557 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
2558 if ("true".equals(valueString)) {
2559 partial = true;
2560 }
2561 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
2562 if ("true".equals(valueString)) {
2563 guestToRemove = true;
2564 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002565
Kenny Guy02c89902016-11-15 19:36:38 +00002566 seedAccountName = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_NAME);
2567 seedAccountType = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_TYPE);
2568 if (seedAccountName != null || seedAccountType != null) {
2569 persistSeedData = true;
2570 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002571
Kenny Guy02c89902016-11-15 19:36:38 +00002572 int outerDepth = parser.getDepth();
2573 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2574 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2575 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2576 continue;
2577 }
2578 String tag = parser.getName();
2579 if (TAG_NAME.equals(tag)) {
2580 type = parser.next();
2581 if (type == XmlPullParser.TEXT) {
2582 name = parser.getText();
2583 }
2584 } else if (TAG_RESTRICTIONS.equals(tag)) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01002585 baseRestrictions = UserRestrictionsUtils.readRestrictions(parser);
Kenny Guy02c89902016-11-15 19:36:38 +00002586 } else if (TAG_DEVICE_POLICY_RESTRICTIONS.equals(tag)) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01002587 localRestrictions = UserRestrictionsUtils.readRestrictions(parser);
2588 } else if (TAG_DEVICE_POLICY_GLOBAL_RESTRICTIONS.equals(tag)) {
2589 globalRestrictions = UserRestrictionsUtils.readRestrictions(parser);
Kenny Guy02c89902016-11-15 19:36:38 +00002590 } else if (TAG_ACCOUNT.equals(tag)) {
2591 type = parser.next();
2592 if (type == XmlPullParser.TEXT) {
2593 account = parser.getText();
2594 }
2595 } else if (TAG_SEED_ACCOUNT_OPTIONS.equals(tag)) {
2596 seedAccountOptions = PersistableBundle.restoreFromXml(parser);
Amith Yamasani12747872015-12-07 14:19:49 -08002597 persistSeedData = true;
arangelov9b632d72018-12-07 23:21:22 +00002598 } else if (TAG_LAST_REQUEST_QUIET_MODE_ENABLED_CALL.equals(tag)) {
2599 type = parser.next();
2600 if (type == XmlPullParser.TEXT) {
2601 lastRequestQuietModeEnabledTimestamp = Long.parseLong(parser.getText());
2602 }
Amith Yamasani12747872015-12-07 14:19:49 -08002603 }
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08002604 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002605 }
Kenny Guy02c89902016-11-15 19:36:38 +00002606
2607 // Create the UserInfo object that gets passed around
2608 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
2609 userInfo.serialNumber = serialNumber;
2610 userInfo.creationTime = creationTime;
2611 userInfo.lastLoggedInTime = lastLoggedInTime;
2612 userInfo.lastLoggedInFingerprint = lastLoggedInFingerprint;
2613 userInfo.partial = partial;
2614 userInfo.guestToRemove = guestToRemove;
2615 userInfo.profileGroupId = profileGroupId;
2616 userInfo.profileBadge = profileBadge;
2617 userInfo.restrictedProfileParentId = restrictedProfileParentId;
2618
2619 // Create the UserData object that's internal to this class
2620 UserData userData = new UserData();
2621 userData.info = userInfo;
2622 userData.account = account;
2623 userData.seedAccountName = seedAccountName;
2624 userData.seedAccountType = seedAccountType;
2625 userData.persistSeedData = persistSeedData;
2626 userData.seedAccountOptions = seedAccountOptions;
arangelov9b632d72018-12-07 23:21:22 +00002627 userData.setLastRequestQuietModeEnabledMillis(lastRequestQuietModeEnabledTimestamp);
Kenny Guy02c89902016-11-15 19:36:38 +00002628
2629 synchronized (mRestrictionsLock) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01002630 if (baseRestrictions != null) {
2631 mBaseUserRestrictions.put(id, baseRestrictions);
2632 }
2633 if (localRestrictions != null) {
2634 mDevicePolicyLocalUserRestrictions.put(id, localRestrictions);
2635 }
2636 if (globalRestrictions != null) {
2637 mDevicePolicyGlobalUserRestrictions.put(id, globalRestrictions);
2638 }
Kenny Guy02c89902016-11-15 19:36:38 +00002639 }
2640 return userData;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002641 }
2642
Amith Yamasani920ace02012-09-20 22:15:37 -07002643 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
2644 String valueString = parser.getAttributeValue(null, attr);
2645 if (valueString == null) return defaultValue;
2646 try {
2647 return Integer.parseInt(valueString);
2648 } catch (NumberFormatException nfe) {
2649 return defaultValue;
2650 }
2651 }
2652
2653 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
2654 String valueString = parser.getAttributeValue(null, attr);
2655 if (valueString == null) return defaultValue;
2656 try {
2657 return Long.parseLong(valueString);
2658 } catch (NumberFormatException nfe) {
2659 return defaultValue;
2660 }
2661 }
2662
Amith Yamasanib82add22013-07-09 11:24:44 -07002663 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002664 * Removes the app restrictions file for a specific package and user id, if it exists.
2665 */
Bookatzf56f2582019-09-04 16:06:41 -07002666 private static void cleanAppRestrictionsForPackageLAr(String pkg, @UserIdInt int userId) {
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07002667 File dir = Environment.getUserSystemDirectory(userId);
2668 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
2669 if (resFile.exists()) {
2670 resFile.delete();
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002671 }
2672 }
2673
Kenny Guya52dc3e2014-02-11 15:33:14 +00002674 @Override
Bookatzf56f2582019-09-04 16:06:41 -07002675 public UserInfo createProfileForUser(String name, int flags, @UserIdInt int userId,
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002676 String[] disallowedPackages) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002677 checkManageOrCreateUsersPermission(flags);
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002678 return createUserInternal(name, flags, userId, disallowedPackages);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002679 }
2680
Amith Yamasani258848d2012-08-10 17:06:33 -07002681 @Override
Bookatzf56f2582019-09-04 16:06:41 -07002682 public UserInfo createProfileForUserEvenWhenDisallowed(String name, int flags,
2683 @UserIdInt int userId, String[] disallowedPackages) {
Tony Mak6dc428f2016-10-10 15:48:27 +01002684 checkManageOrCreateUsersPermission(flags);
2685 return createUserInternalUnchecked(name, flags, userId, disallowedPackages);
2686 }
2687
2688 @Override
Bookatzf56f2582019-09-04 16:06:41 -07002689 public boolean removeUserEvenWhenDisallowed(@UserIdInt int userId) {
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00002690 checkManageOrCreateUsersPermission("Only the system can remove users");
Bookatzf56f2582019-09-04 16:06:41 -07002691 return removeUserUnchecked(userId);
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00002692 }
2693
2694 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07002695 public UserInfo createUser(String name, int flags) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002696 checkManageOrCreateUsersPermission(flags);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00002697 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002698 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07002699
Jessica Hummelbe81c802014-04-22 15:49:22 +01002700 private UserInfo createUserInternal(String name, int flags, int parentId) {
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002701 return createUserInternal(name, flags, parentId, null);
2702 }
2703
2704 private UserInfo createUserInternal(String name, int flags, int parentId,
2705 String[] disallowedPackages) {
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002706 String restriction = ((flags & UserInfo.FLAG_MANAGED_PROFILE) != 0)
2707 ? UserManager.DISALLOW_ADD_MANAGED_PROFILE
2708 : UserManager.DISALLOW_ADD_USER;
2709 if (hasUserRestriction(restriction, UserHandle.getCallingUserId())) {
2710 Log.w(LOG_TAG, "Cannot add user. " + restriction + " is enabled.");
Julia Reynolds75175022014-06-26 16:35:00 -04002711 return null;
2712 }
Tony Mak6dc428f2016-10-10 15:48:27 +01002713 return createUserInternalUnchecked(name, flags, parentId, disallowedPackages);
2714 }
2715
jovanakdd7e4752019-09-04 12:35:45 -07002716 private UserInfo createUserInternalUnchecked(@Nullable String name, int flags,
2717 int parentId, @Nullable String[] disallowedPackages) {
2718 TimingsTraceAndSlog t = new TimingsTraceAndSlog();
2719 t.traceBegin("createUser");
2720 UserInfo userInfo =
2721 createUserInternalUncheckedNoTracing(name, flags, parentId, disallowedPackages, t);
2722 t.traceEnd();
2723 return userInfo;
2724 }
2725
2726 private UserInfo createUserInternalUncheckedNoTracing(@Nullable String name, int flags,
2727 int parentId, @Nullable String[] disallowedPackages, @NonNull TimingsTraceAndSlog t) {
Suprabh Shuklac5e057c2016-08-08 16:22:44 -07002728 DeviceStorageMonitorInternal dsm = LocalServices
2729 .getService(DeviceStorageMonitorInternal.class);
2730 if (dsm.isMemoryLow()) {
2731 Log.w(LOG_TAG, "Cannot add user. Not enough space on disk.");
2732 return null;
2733 }
jovanakdd7e4752019-09-04 12:35:45 -07002734
Amith Yamasani95ab7842014-08-11 17:09:26 -07002735 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Nicolas Prevot12678a92015-05-13 12:15:03 -07002736 final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002737 final boolean isRestricted = (flags & UserInfo.FLAG_RESTRICTED) != 0;
Amith Yamasani52c21e32016-05-31 09:12:20 -07002738 final boolean isDemo = (flags & UserInfo.FLAG_DEMO) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002739 final long ident = Binder.clearCallingIdentity();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002740 UserInfo userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08002741 UserData userData;
Amith Yamasanibb054c92015-07-09 14:16:27 -07002742 final int userId;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002743 try {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002744 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002745 UserData parent = null;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002746 if (parentId != UserHandle.USER_NULL) {
2747 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002748 parent = getUserDataLU(parentId);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00002749 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002750 if (parent == null) return null;
2751 }
2752 if (isManagedProfile && !canAddMoreManagedProfiles(parentId, false)) {
2753 Log.e(LOG_TAG, "Cannot add more managed profiles for user " + parentId);
2754 return null;
2755 }
Amith Yamasani52c21e32016-05-31 09:12:20 -07002756 if (!isGuest && !isManagedProfile && !isDemo && isUserLimitReached()) {
2757 // If we're not adding a guest/demo user or a managed profile and the limit has
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002758 // been reached, cannot add a user.
jovanaka6763a32018-12-03 17:23:20 -08002759 Log.e(LOG_TAG, "Cannot add user. Maximum user limit is reached.");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002760 return null;
2761 }
2762 // If we're adding a guest and there already exists one, bail.
2763 if (isGuest && findCurrentGuestUser() != null) {
jovanaka6763a32018-12-03 17:23:20 -08002764 Log.e(LOG_TAG, "Cannot add guest user. Guest user already exists.");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002765 return null;
2766 }
2767 // In legacy mode, restricted profile's parent can only be the owner user
2768 if (isRestricted && !UserManager.isSplitSystemUser()
2769 && (parentId != UserHandle.USER_SYSTEM)) {
2770 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
2771 return null;
2772 }
2773 if (isRestricted && UserManager.isSplitSystemUser()) {
2774 if (parent == null) {
2775 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be "
2776 + "specified");
Nicolas Prevot12678a92015-05-13 12:15:03 -07002777 return null;
2778 }
Amith Yamasani12747872015-12-07 14:19:49 -08002779 if (!parent.info.canHaveProfile()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002780 Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be "
2781 + "created for the specified parent user id " + parentId);
Amith Yamasani95ab7842014-08-11 17:09:26 -07002782 return null;
2783 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002784 }
Ying Zheng215116f2019-09-11 12:50:09 -07002785
Bookatz75f0a072019-08-05 14:12:16 -07002786 if (!isManagedProfile) {
2787 // New users cannot be system, and it's not a profile, so per-force it's FULL.
2788 flags |= UserInfo.FLAG_FULL;
2789 }
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002790
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002791 userId = getNextAvailableId();
2792 Environment.getUserSystemDirectory(userId).mkdirs();
Lenka Trochtova02fee152015-12-22 14:26:18 +01002793 boolean ephemeralGuests = Resources.getSystem()
2794 .getBoolean(com.android.internal.R.bool.config_guestUserEphemeral);
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002795
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002796 synchronized (mUsersLock) {
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002797 // Add ephemeral flag to guests/users if required. Also inherit it from parent.
2798 if ((isGuest && ephemeralGuests) || mForceEphemeralUsers
2799 || (parent != null && parent.info.isEphemeral())) {
2800 flags |= UserInfo.FLAG_EPHEMERAL;
2801 }
2802
2803 userInfo = new UserInfo(userId, name, null, flags);
2804 userInfo.serialNumber = mNextSerialNumber++;
2805 long now = System.currentTimeMillis();
2806 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
2807 userInfo.partial = true;
Fyodor Kupolov83c24242016-03-31 13:30:42 -07002808 userInfo.lastLoggedInFingerprint = Build.FINGERPRINT;
Kenny Guy02c89902016-11-15 19:36:38 +00002809 if (isManagedProfile && parentId != UserHandle.USER_NULL) {
2810 userInfo.profileBadge = getFreeProfileBadgeLU(parentId);
2811 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002812 userData = new UserData();
2813 userData.info = userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08002814 mUsers.put(userId, userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002815 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06002816 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002817 writeUserListLP();
2818 if (parent != null) {
2819 if (isManagedProfile) {
Amith Yamasani12747872015-12-07 14:19:49 -08002820 if (parent.info.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
2821 parent.info.profileGroupId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002822 writeUserLP(parent);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002823 }
Amith Yamasani12747872015-12-07 14:19:49 -08002824 userInfo.profileGroupId = parent.info.profileGroupId;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002825 } else if (isRestricted) {
Amith Yamasani12747872015-12-07 14:19:49 -08002826 if (parent.info.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) {
2827 parent.info.restrictedProfileParentId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002828 writeUserLP(parent);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002829 }
Amith Yamasani12747872015-12-07 14:19:49 -08002830 userInfo.restrictedProfileParentId = parent.info.restrictedProfileParentId;
Makoto Onuki068c54a2015-10-13 14:34:03 -07002831 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002832 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07002833 }
jovanakdd7e4752019-09-04 12:35:45 -07002834
2835 t.traceBegin("createUserKey");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002836 final StorageManager storage = mContext.getSystemService(StorageManager.class);
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002837 storage.createUserKey(userId, userInfo.serialNumber, userInfo.isEphemeral());
jovanakdd7e4752019-09-04 12:35:45 -07002838 t.traceEnd();
2839
2840 t.traceBegin("prepareUserData");
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -08002841 mUserDataPreparer.prepareUserData(userId, userInfo.serialNumber,
Jeff Sharkey47f71082016-02-01 17:03:54 -07002842 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
jovanakdd7e4752019-09-04 12:35:45 -07002843 t.traceEnd();
2844
2845 t.traceBegin("PM.createNewUser");
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002846 mPm.createNewUser(userId, disallowedPackages);
jovanakdd7e4752019-09-04 12:35:45 -07002847 t.traceEnd();
2848
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002849 userInfo.partial = false;
2850 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002851 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002852 }
2853 updateUserIds();
2854 Bundle restrictions = new Bundle();
Fyodor Kupolove04462c2015-11-30 15:02:53 -08002855 if (isGuest) {
2856 synchronized (mGuestRestrictions) {
2857 restrictions.putAll(mGuestRestrictions);
2858 }
2859 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002860 synchronized (mRestrictionsLock) {
2861 mBaseUserRestrictions.append(userId, restrictions);
2862 }
jovanakdd7e4752019-09-04 12:35:45 -07002863
2864 t.traceBegin("PM.onNewUserCreated");
Fyodor Kupolov5fd967d2016-07-12 14:46:19 -07002865 mPm.onNewUserCreated(userId);
jovanakdd7e4752019-09-04 12:35:45 -07002866 t.traceEnd();
2867
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002868 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
2869 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
2870 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
2871 android.Manifest.permission.MANAGE_USERS);
Christine Franks88220562017-05-24 11:11:21 -07002872 MetricsLogger.count(mContext, isGuest ? TRON_GUEST_CREATED
2873 : (isDemo ? TRON_DEMO_CREATED : TRON_USER_CREATED), 1);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002874 } finally {
2875 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07002876 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002877 return userInfo;
2878 }
2879
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002880 @VisibleForTesting
2881 UserData putUserInfo(UserInfo userInfo) {
2882 final UserData userData = new UserData();
2883 userData.info = userInfo;
2884 synchronized (mUsers) {
2885 mUsers.put(userInfo.id, userData);
2886 }
2887 return userData;
2888 }
2889
2890 @VisibleForTesting
Bookatzf56f2582019-09-04 16:06:41 -07002891 void removeUserInfo(@UserIdInt int userId) {
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002892 synchronized (mUsers) {
2893 mUsers.remove(userId);
2894 }
2895 }
2896
Amith Yamasani0b285492011-04-14 17:35:23 -07002897 /**
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002898 * @hide
2899 */
Amith Yamasani12747872015-12-07 14:19:49 -08002900 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002901 public UserInfo createRestrictedProfile(String name, int parentUserId) {
Sudheer Shanka53d41472016-06-16 09:11:08 -07002902 checkManageOrCreateUsersPermission("setupRestrictedProfile");
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002903 final UserInfo user = createProfileForUser(
2904 name, UserInfo.FLAG_RESTRICTED, parentUserId, null);
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002905 if (user == null) {
2906 return null;
2907 }
Fyodor Kupolov9e912ba2016-02-09 18:29:43 -08002908 long identity = Binder.clearCallingIdentity();
2909 try {
2910 setUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, true, user.id);
2911 // Change the setting before applying the DISALLOW_SHARE_LOCATION restriction, otherwise
2912 // the putIntForUser() will fail.
2913 android.provider.Settings.Secure.putIntForUser(mContext.getContentResolver(),
2914 android.provider.Settings.Secure.LOCATION_MODE,
2915 android.provider.Settings.Secure.LOCATION_MODE_OFF, user.id);
2916 setUserRestriction(UserManager.DISALLOW_SHARE_LOCATION, true, user.id);
2917 } finally {
2918 Binder.restoreCallingIdentity(identity);
2919 }
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002920 return user;
2921 }
2922
2923 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07002924 * Find the current guest user. If the Guest user is partial,
2925 * then do not include it in the results as it is about to die.
Adam Lesinskieddeb492014-09-08 17:50:03 -07002926 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002927 private UserInfo findCurrentGuestUser() {
2928 synchronized (mUsersLock) {
2929 final int size = mUsers.size();
2930 for (int i = 0; i < size; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002931 final UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002932 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
2933 return user;
2934 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002935 }
2936 }
2937 return null;
2938 }
2939
2940 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07002941 * Mark this guest user for deletion to allow us to create another guest
2942 * and switch to that user before actually removing this guest.
Bookatzf56f2582019-09-04 16:06:41 -07002943 * @param userId the userid of the current guest
Amith Yamasani1df14732014-08-29 21:37:27 -07002944 * @return whether the user could be marked for deletion
2945 */
Amith Yamasani12747872015-12-07 14:19:49 -08002946 @Override
Bookatzf56f2582019-09-04 16:06:41 -07002947 public boolean markGuestForDeletion(@UserIdInt int userId) {
Amith Yamasani1df14732014-08-29 21:37:27 -07002948 checkManageUsersPermission("Only the system can remove users");
2949 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
2950 UserManager.DISALLOW_REMOVE_USER, false)) {
2951 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
2952 return false;
2953 }
2954
2955 long ident = Binder.clearCallingIdentity();
2956 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002957 final UserData userData;
Amith Yamasani1df14732014-08-29 21:37:27 -07002958 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002959 synchronized (mUsersLock) {
Bookatzf56f2582019-09-04 16:06:41 -07002960 userData = mUsers.get(userId);
2961 if (userId == 0 || userData == null || mRemovingUserIds.get(userId)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002962 return false;
2963 }
Amith Yamasani1df14732014-08-29 21:37:27 -07002964 }
Amith Yamasani12747872015-12-07 14:19:49 -08002965 if (!userData.info.isGuest()) {
Amith Yamasani1df14732014-08-29 21:37:27 -07002966 return false;
2967 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002968 // We set this to a guest user that is to be removed. This is a temporary state
2969 // where we are allowed to add new Guest users, even if this one is still not
2970 // removed. This user will still show up in getUserInfo() calls.
2971 // If we don't get around to removing this Guest user, it will be purged on next
2972 // startup.
Amith Yamasani12747872015-12-07 14:19:49 -08002973 userData.info.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07002974 // Mark it as disabled, so that it isn't returned any more when
2975 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002976 userData.info.flags |= UserInfo.FLAG_DISABLED;
2977 writeUserLP(userData);
Amith Yamasani1df14732014-08-29 21:37:27 -07002978 }
2979 } finally {
2980 Binder.restoreCallingIdentity(ident);
2981 }
2982 return true;
2983 }
2984
2985 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002986 * Removes a user and all data directories created for that user. This method should be called
2987 * after the user's processes have been terminated.
Bookatzf56f2582019-09-04 16:06:41 -07002988 * @param userId the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07002989 */
Amith Yamasani12747872015-12-07 14:19:49 -08002990 @Override
Bookatzf56f2582019-09-04 16:06:41 -07002991 public boolean removeUser(@UserIdInt int userId) {
2992 Slog.i(LOG_TAG, "removeUser u" + userId);
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002993 checkManageOrCreateUsersPermission("Only the system can remove users");
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002994
2995 final boolean isManagedProfile;
2996 synchronized (mUsersLock) {
Bookatzf56f2582019-09-04 16:06:41 -07002997 UserInfo userInfo = getUserInfoLU(userId);
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002998 isManagedProfile = userInfo != null && userInfo.isManagedProfile();
2999 }
3000 String restriction = isManagedProfile
3001 ? UserManager.DISALLOW_REMOVE_MANAGED_PROFILE : UserManager.DISALLOW_REMOVE_USER;
3002 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(restriction, false)) {
3003 Log.w(LOG_TAG, "Cannot remove user. " + restriction + " is enabled.");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04003004 return false;
3005 }
Bookatzf56f2582019-09-04 16:06:41 -07003006 return removeUserUnchecked(userId);
Nicolas Prevotdf1b87d2016-10-25 13:57:08 +01003007 }
Julia Reynolds4ac5f852014-06-23 17:38:51 -04003008
Bookatzf56f2582019-09-04 16:06:41 -07003009 private boolean removeUserUnchecked(@UserIdInt int userId) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01003010 long ident = Binder.clearCallingIdentity();
3011 try {
Amith Yamasani12747872015-12-07 14:19:49 -08003012 final UserData userData;
Fyodor Kupolov0df68cd2015-10-01 13:54:22 -07003013 int currentUser = ActivityManager.getCurrentUser();
Bookatzf56f2582019-09-04 16:06:41 -07003014 if (currentUser == userId) {
jovanaka6763a32018-12-03 17:23:20 -08003015 Log.w(LOG_TAG, "Current user cannot be removed.");
Fyodor Kupolov0df68cd2015-10-01 13:54:22 -07003016 return false;
3017 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01003018 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003019 synchronized (mUsersLock) {
Bookatzf56f2582019-09-04 16:06:41 -07003020 userData = mUsers.get(userId);
3021 if (userId == UserHandle.USER_SYSTEM) {
jovanaka6763a32018-12-03 17:23:20 -08003022 Log.e(LOG_TAG, "System user cannot be removed.");
3023 return false;
3024 }
3025
3026 if (userData == null) {
3027 Log.e(LOG_TAG, String.format(
Bookatzf56f2582019-09-04 16:06:41 -07003028 "Cannot remove user %d, invalid user id provided.", userId));
jovanaka6763a32018-12-03 17:23:20 -08003029 return false;
3030 }
3031
Bookatzf56f2582019-09-04 16:06:41 -07003032 if (mRemovingUserIds.get(userId)) {
jovanaka6763a32018-12-03 17:23:20 -08003033 Log.e(LOG_TAG, String.format(
Bookatzf56f2582019-09-04 16:06:41 -07003034 "User %d is already scheduled for removal.", userId));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003035 return false;
3036 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08003037
Bookatzf56f2582019-09-04 16:06:41 -07003038 addRemovingUserIdLocked(userId);
Fyodor Kupolov82402752015-10-28 14:54:51 -07003039 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08003040
Kenny Guyee58b4f2014-05-23 15:19:53 +01003041 // Set this to a partially created user, so that the user will be purged
3042 // on next startup, in case the runtime stops now before stopping and
3043 // removing the user completely.
Amith Yamasani12747872015-12-07 14:19:49 -08003044 userData.info.partial = true;
Kenny Guyee58b4f2014-05-23 15:19:53 +01003045 // Mark it as disabled, so that it isn't returned any more when
3046 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08003047 userData.info.flags |= UserInfo.FLAG_DISABLED;
3048 writeUserLP(userData);
Kenny Guyee58b4f2014-05-23 15:19:53 +01003049 }
Fyodor Kupolov6c96f7f2017-06-28 18:22:59 -07003050 try {
Bookatzf56f2582019-09-04 16:06:41 -07003051 mAppOpsService.removeUser(userId);
Fyodor Kupolov6c96f7f2017-06-28 18:22:59 -07003052 } catch (RemoteException e) {
jovanaka6763a32018-12-03 17:23:20 -08003053 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user.", e);
Fyodor Kupolov6c96f7f2017-06-28 18:22:59 -07003054 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01003055
Amith Yamasani12747872015-12-07 14:19:49 -08003056 if (userData.info.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
3057 && userData.info.isManagedProfile()) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01003058 // Send broadcast to notify system that the user removed was a
3059 // managed user.
Amith Yamasani12747872015-12-07 14:19:49 -08003060 sendProfileRemovedBroadcast(userData.info.profileGroupId, userData.info.id);
Kenny Guyee58b4f2014-05-23 15:19:53 +01003061 }
3062
Bookatzf56f2582019-09-04 16:06:41 -07003063 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userId);
Kenny Guyee58b4f2014-05-23 15:19:53 +01003064 int res;
3065 try {
Bookatzf56f2582019-09-04 16:06:41 -07003066 res = ActivityManager.getService().stopUser(userId, /* force= */ true,
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07003067 new IStopUserCallback.Stub() {
Kenny Guyee58b4f2014-05-23 15:19:53 +01003068 @Override
Bookatzf56f2582019-09-04 16:06:41 -07003069 public void userStopped(int userIdParam) {
3070 finishRemoveUser(userIdParam);
Kenny Guyee58b4f2014-05-23 15:19:53 +01003071 }
3072 @Override
Bookatzf56f2582019-09-04 16:06:41 -07003073 public void userStopAborted(int userIdParam) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01003074 }
3075 });
3076 } catch (RemoteException e) {
jovanaka6763a32018-12-03 17:23:20 -08003077 Log.w(LOG_TAG, "Failed to stop user during removal.", e);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003078 return false;
3079 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01003080 return res == ActivityManager.USER_OP_SUCCESS;
3081 } finally {
3082 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003083 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003084 }
3085
Andreas Gampea36dc622018-02-05 17:19:22 -08003086 @GuardedBy("mUsersLock")
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003087 @VisibleForTesting
Bookatzf56f2582019-09-04 16:06:41 -07003088 void addRemovingUserIdLocked(@UserIdInt int userId) {
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003089 // We remember deleted user IDs to prevent them from being
3090 // reused during the current boot; they can still be reused
3091 // after a reboot or recycling of userIds.
3092 mRemovingUserIds.put(userId, true);
3093 mRecentlyRemovedIds.add(userId);
3094 // Keep LRU queue of recently removed IDs for recycling
3095 if (mRecentlyRemovedIds.size() > MAX_RECENTLY_REMOVED_IDS_SIZE) {
3096 mRecentlyRemovedIds.removeFirst();
3097 }
3098 }
3099
Bookatzf56f2582019-09-04 16:06:41 -07003100 void finishRemoveUser(final @UserIdInt int userId) {
3101 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userId);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07003102 // Let other services shutdown any activity and clean up their state before completely
3103 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07003104 long ident = Binder.clearCallingIdentity();
3105 try {
3106 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
Bookatzf56f2582019-09-04 16:06:41 -07003107 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07003108 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
3109 android.Manifest.permission.MANAGE_USERS,
3110
3111 new BroadcastReceiver() {
3112 @Override
3113 public void onReceive(Context context, Intent intent) {
3114 if (DBG) {
3115 Slog.i(LOG_TAG,
3116 "USER_REMOVED broadcast sent, cleaning up user data "
Bookatzf56f2582019-09-04 16:06:41 -07003117 + userId);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07003118 }
3119 new Thread() {
Amith Yamasani12747872015-12-07 14:19:49 -08003120 @Override
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07003121 public void run() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003122 // Clean up any ActivityTaskManager state
3123 LocalServices.getService(ActivityTaskManagerInternal.class)
Bookatzf56f2582019-09-04 16:06:41 -07003124 .onUserStopped(userId);
3125 removeUserState(userId);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07003126 }
3127 }.start();
3128 }
3129 },
3130
3131 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07003132 } finally {
3133 Binder.restoreCallingIdentity(ident);
3134 }
Amith Yamasani2a003292012-08-14 18:25:45 -07003135 }
3136
Bookatzf56f2582019-09-04 16:06:41 -07003137 private void removeUserState(final @UserIdInt int userId) {
Paul Crowley91293792016-03-25 15:23:07 -07003138 try {
Bookatzf56f2582019-09-04 16:06:41 -07003139 mContext.getSystemService(StorageManager.class).destroyUserKey(userId);
Paul Crowley91293792016-03-25 15:23:07 -07003140 } catch (IllegalStateException e) {
3141 // This may be simply because the user was partially created.
Bookatzf56f2582019-09-04 16:06:41 -07003142 Slog.i(LOG_TAG, "Destroying key for user " + userId + " failed, continuing anyway", e);
Paul Crowley91293792016-03-25 15:23:07 -07003143 }
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06003144
Amith Yamasanid04aaa32016-06-13 12:09:36 -07003145 // Cleanup gatekeeper secure user id
3146 try {
3147 final IGateKeeperService gk = GateKeeper.getService();
3148 if (gk != null) {
Bookatzf56f2582019-09-04 16:06:41 -07003149 gk.clearSecureUserId(userId);
Amith Yamasanid04aaa32016-06-13 12:09:36 -07003150 }
3151 } catch (Exception ex) {
3152 Slog.w(LOG_TAG, "unable to clear GK secure user id");
3153 }
3154
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003155 // Cleanup package manager settings
Bookatzf56f2582019-09-04 16:06:41 -07003156 mPm.cleanUpUser(this, userId);
Amith Yamasanid04aaa32016-06-13 12:09:36 -07003157
3158 // Clean up all data before removing metadata
Bookatzf56f2582019-09-04 16:06:41 -07003159 mUserDataPreparer.destroyUserData(userId,
Amith Yamasanid04aaa32016-06-13 12:09:36 -07003160 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
3161
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003162 // Remove this user from the list
Fyodor Kupolov82402752015-10-28 14:54:51 -07003163 synchronized (mUsersLock) {
Bookatzf56f2582019-09-04 16:06:41 -07003164 mUsers.remove(userId);
3165 mIsUserManaged.delete(userId);
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003166 }
3167 synchronized (mUserStates) {
Bookatzf56f2582019-09-04 16:06:41 -07003168 mUserStates.delete(userId);
Makoto Onukie7927da2015-11-25 10:05:17 -08003169 }
3170 synchronized (mRestrictionsLock) {
Bookatzf56f2582019-09-04 16:06:41 -07003171 mBaseUserRestrictions.remove(userId);
3172 mAppliedUserRestrictions.remove(userId);
3173 mCachedEffectiveUserRestrictions.remove(userId);
3174 mDevicePolicyLocalUserRestrictions.remove(userId);
3175 if (mDevicePolicyGlobalUserRestrictions.get(userId) != null) {
3176 mDevicePolicyGlobalUserRestrictions.remove(userId);
Pavel Grafov6a40f092016-10-25 15:46:51 +01003177 applyUserRestrictionsForAllUsersLR();
3178 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07003179 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003180 // Update the user list
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003181 synchronized (mPackagesLock) {
3182 writeUserListLP();
3183 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06003184 // Remove user file
Bookatzf56f2582019-09-04 16:06:41 -07003185 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userId + XML_SUFFIX));
Jeff Sharkeycd575992016-03-29 14:12:49 -06003186 userFile.delete();
Fyodor Kupolov82402752015-10-28 14:54:51 -07003187 updateUserIds();
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003188 if (RELEASE_DELETED_USER_ID) {
3189 synchronized (mUsers) {
Bookatzf56f2582019-09-04 16:06:41 -07003190 mRemovingUserIds.delete(userId);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003191 }
3192 }
Amith Yamasani61f57372012-08-31 12:12:28 -07003193 }
3194
Kenny Guyf8d3a232014-05-15 16:09:52 +01003195 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01003196 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01003197 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
3198 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01003199 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
Jeff Sharkeyaf6ec292015-12-17 11:19:00 -07003200 managedProfileIntent.putExtra(Intent.EXTRA_USER_HANDLE, removedUserId);
Kenny Guyf8d3a232014-05-15 16:09:52 +01003201 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01003202 }
3203
Amith Yamasani2a003292012-08-14 18:25:45 -07003204 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07003205 public Bundle getApplicationRestrictions(String packageName) {
3206 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
3207 }
3208
3209 @Override
Bookatzf56f2582019-09-04 16:06:41 -07003210 public Bundle getApplicationRestrictionsForUser(String packageName, @UserIdInt int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003211 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07003212 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07003213 checkSystemOrRoot("get application restrictions for other user/app " + packageName);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003214 }
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003215 synchronized (mAppRestrictionsLock) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003216 // Read the restrictions from XML
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003217 return readApplicationRestrictionsLAr(packageName, userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003218 }
3219 }
3220
3221 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07003222 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Bookatzf56f2582019-09-04 16:06:41 -07003223 @UserIdInt int userId) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00003224 checkSystemOrRoot("set application restrictions");
Fyodor Kupolov0d88d542016-04-19 11:37:22 -07003225 if (restrictions != null) {
3226 restrictions.setDefusable(true);
3227 }
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003228 synchronized (mAppRestrictionsLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01003229 if (restrictions == null || restrictions.isEmpty()) {
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003230 cleanAppRestrictionsForPackageLAr(packageName, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01003231 } else {
3232 // Write the restrictions to XML
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003233 writeApplicationRestrictionsLAr(packageName, restrictions, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01003234 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003235 }
Robin Lee66e5d962014-04-09 16:44:21 +01003236
Fyodor Kupolovd2846122016-02-11 18:06:34 -08003237 // Notify package of changes via an intent - only sent to explicitly registered receivers.
3238 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
3239 changeIntent.setPackage(packageName);
3240 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3241 mContext.sendBroadcastAsUser(changeIntent, UserHandle.of(userId));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003242 }
3243
3244 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07003245 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003246 try {
3247 return mContext.getPackageManager().getApplicationInfo(packageName,
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07003248 PackageManager.MATCH_ANY_USER).uid;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003249 } catch (NameNotFoundException nnfe) {
3250 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07003251 } finally {
3252 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003253 }
3254 }
3255
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003256 @GuardedBy("mAppRestrictionsLock")
Bookatzf56f2582019-09-04 16:06:41 -07003257 private static Bundle readApplicationRestrictionsLAr(String packageName,
3258 @UserIdInt int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003259 AtomicFile restrictionsFile =
3260 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
3261 packageToRestrictionsFileName(packageName)));
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003262 return readApplicationRestrictionsLAr(restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003263 }
3264
3265 @VisibleForTesting
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003266 @GuardedBy("mAppRestrictionsLock")
3267 static Bundle readApplicationRestrictionsLAr(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07003268 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003269 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07003270 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07003271 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07003272 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003273
3274 FileInputStream fis = null;
3275 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003276 fis = restrictionsFile.openRead();
3277 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01003278 parser.setInput(fis, StandardCharsets.UTF_8.name());
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003279 XmlUtils.nextElement(parser);
3280 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003281 Slog.e(LOG_TAG, "Unable to read restrictions file "
3282 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07003283 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003284 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003285 while (parser.next() != XmlPullParser.END_DOCUMENT) {
3286 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003287 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003288 } catch (IOException|XmlPullParserException e) {
3289 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003290 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003291 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003292 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07003293 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003294 }
3295
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003296 private static void readEntry(Bundle restrictions, ArrayList<String> values,
3297 XmlPullParser parser) throws XmlPullParserException, IOException {
3298 int type = parser.getEventType();
3299 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
3300 String key = parser.getAttributeValue(null, ATTR_KEY);
3301 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
3302 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
3303 if (multiple != null) {
3304 values.clear();
3305 int count = Integer.parseInt(multiple);
3306 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
3307 if (type == XmlPullParser.START_TAG
3308 && parser.getName().equals(TAG_VALUE)) {
3309 values.add(parser.nextText().trim());
3310 count--;
3311 }
3312 }
3313 String [] valueStrings = new String[values.size()];
3314 values.toArray(valueStrings);
3315 restrictions.putStringArray(key, valueStrings);
3316 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
3317 restrictions.putBundle(key, readBundleEntry(parser, values));
3318 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
3319 final int outerDepth = parser.getDepth();
3320 ArrayList<Bundle> bundleList = new ArrayList<>();
3321 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
3322 Bundle childBundle = readBundleEntry(parser, values);
3323 bundleList.add(childBundle);
3324 }
3325 restrictions.putParcelableArray(key,
3326 bundleList.toArray(new Bundle[bundleList.size()]));
3327 } else {
3328 String value = parser.nextText().trim();
3329 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
3330 restrictions.putBoolean(key, Boolean.parseBoolean(value));
3331 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
3332 restrictions.putInt(key, Integer.parseInt(value));
3333 } else {
3334 restrictions.putString(key, value);
3335 }
3336 }
3337 }
3338 }
3339
3340 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
3341 throws IOException, XmlPullParserException {
3342 Bundle childBundle = new Bundle();
3343 final int outerDepth = parser.getDepth();
3344 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
3345 readEntry(childBundle, values, parser);
3346 }
3347 return childBundle;
3348 }
3349
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003350 @GuardedBy("mAppRestrictionsLock")
3351 private static void writeApplicationRestrictionsLAr(String packageName,
Bookatzf56f2582019-09-04 16:06:41 -07003352 Bundle restrictions, @UserIdInt int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003353 AtomicFile restrictionsFile = new AtomicFile(
3354 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07003355 packageToRestrictionsFileName(packageName)));
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003356 writeApplicationRestrictionsLAr(restrictions, restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003357 }
3358
3359 @VisibleForTesting
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003360 @GuardedBy("mAppRestrictionsLock")
3361 static void writeApplicationRestrictionsLAr(Bundle restrictions, AtomicFile restrictionsFile) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003362 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003363 try {
3364 fos = restrictionsFile.startWrite();
3365 final BufferedOutputStream bos = new BufferedOutputStream(fos);
3366
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003367 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01003368 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003369 serializer.startDocument(null, true);
3370 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
3371
3372 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003373 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003374 serializer.endTag(null, TAG_RESTRICTIONS);
3375
3376 serializer.endDocument();
3377 restrictionsFile.finishWrite(fos);
3378 } catch (Exception e) {
3379 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003380 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
3381 }
3382 }
3383
3384 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
3385 throws IOException {
3386 for (String key : restrictions.keySet()) {
3387 Object value = restrictions.get(key);
3388 serializer.startTag(null, TAG_ENTRY);
3389 serializer.attribute(null, ATTR_KEY, key);
3390
3391 if (value instanceof Boolean) {
3392 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
3393 serializer.text(value.toString());
3394 } else if (value instanceof Integer) {
3395 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
3396 serializer.text(value.toString());
3397 } else if (value == null || value instanceof String) {
3398 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
3399 serializer.text(value != null ? (String) value : "");
3400 } else if (value instanceof Bundle) {
3401 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
3402 writeBundle((Bundle) value, serializer);
3403 } else if (value instanceof Parcelable[]) {
3404 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
3405 Parcelable[] array = (Parcelable[]) value;
3406 for (Parcelable parcelable : array) {
3407 if (!(parcelable instanceof Bundle)) {
3408 throw new IllegalArgumentException("bundle-array can only hold Bundles");
3409 }
3410 serializer.startTag(null, TAG_ENTRY);
3411 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
3412 writeBundle((Bundle) parcelable, serializer);
3413 serializer.endTag(null, TAG_ENTRY);
3414 }
3415 } else {
3416 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
3417 String[] values = (String[]) value;
3418 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
3419 for (String choice : values) {
3420 serializer.startTag(null, TAG_VALUE);
3421 serializer.text(choice != null ? choice : "");
3422 serializer.endTag(null, TAG_VALUE);
3423 }
3424 }
3425 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003426 }
3427 }
3428
3429 @Override
Bookatzf56f2582019-09-04 16:06:41 -07003430 public int getUserSerialNumber(@UserIdInt int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003431 synchronized (mUsersLock) {
Bookatzf56f2582019-09-04 16:06:41 -07003432 final UserInfo userInfo = getUserInfoLU(userId);
Pavel Grafov9c295d42019-03-26 19:42:08 +00003433 return userInfo != null ? userInfo.serialNumber : -1;
Amith Yamasani2a003292012-08-14 18:25:45 -07003434 }
3435 }
3436
3437 @Override
Bookatzf56f2582019-09-04 16:06:41 -07003438 public boolean isUserNameSet(@UserIdInt int userId) {
Fyodor Kupolov605b12a2017-05-10 15:58:09 -07003439 synchronized (mUsersLock) {
Bookatzf56f2582019-09-04 16:06:41 -07003440 final UserInfo userInfo = getUserInfoLU(userId);
Fyodor Kupolov605b12a2017-05-10 15:58:09 -07003441 return userInfo != null && userInfo.name != null;
3442 }
3443 }
3444
3445 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07003446 public int getUserHandle(int userSerialNumber) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003447 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07003448 for (int userId : mUserIds) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003449 UserInfo info = getUserInfoLU(userId);
Kenny Guy945f8832015-02-10 15:17:26 +00003450 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07003451 }
3452 // Not found
3453 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07003454 }
3455 }
3456
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003457 @Override
Bookatzf56f2582019-09-04 16:06:41 -07003458 public long getUserCreationTime(@UserIdInt int userId) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003459 int callingUserId = UserHandle.getCallingUserId();
3460 UserInfo userInfo = null;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003461 synchronized (mUsersLock) {
Bookatzf56f2582019-09-04 16:06:41 -07003462 if (callingUserId == userId) {
3463 userInfo = getUserInfoLU(userId);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003464 } else {
Bookatzf56f2582019-09-04 16:06:41 -07003465 UserInfo parent = getProfileParentLU(userId);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003466 if (parent != null && parent.id == callingUserId) {
Bookatzf56f2582019-09-04 16:06:41 -07003467 userInfo = getUserInfoLU(userId);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003468 }
3469 }
3470 }
3471 if (userInfo == null) {
Bookatzf56f2582019-09-04 16:06:41 -07003472 throw new SecurityException("userId can only be the calling user or a managed "
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003473 + "profile associated with this user");
3474 }
3475 return userInfo.creationTime;
3476 }
3477
Amith Yamasani0b285492011-04-14 17:35:23 -07003478 /**
3479 * Caches the list of user ids in an array, adjusting the array size when necessary.
3480 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07003481 private void updateUserIds() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003482 int num = 0;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003483 synchronized (mUsersLock) {
3484 final int userSize = mUsers.size();
3485 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003486 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003487 num++;
3488 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003489 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07003490 final int[] newUsers = new int[num];
3491 int n = 0;
3492 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003493 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003494 newUsers[n++] = mUsers.keyAt(i);
3495 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003496 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07003497 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07003498 }
3499 }
3500
3501 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003502 * Called right before a user is started. This gives us a chance to prepare
3503 * app storage and apply any user restrictions.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003504 */
Bookatzf56f2582019-09-04 16:06:41 -07003505 public void onBeforeStartUser(@UserIdInt int userId) {
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003506 UserInfo userInfo = getUserInfo(userId);
3507 if (userInfo == null) {
3508 return;
3509 }
Felipe Leme3aad1be2019-05-31 11:43:12 -07003510 TimingsTraceAndSlog t = new TimingsTraceAndSlog();
3511 t.traceBegin("onBeforeStartUser-" + userId);
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003512 final int userSerial = userInfo.serialNumber;
3513 // Migrate only if build fingerprints mismatch
3514 boolean migrateAppsData = !Build.FINGERPRINT.equals(userInfo.lastLoggedInFingerprint);
Felipe Leme3aad1be2019-05-31 11:43:12 -07003515 t.traceBegin("prepareUserData");
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -08003516 mUserDataPreparer.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_DE);
Felipe Leme3aad1be2019-05-31 11:43:12 -07003517 t.traceEnd();
3518 t.traceBegin("reconcileAppsData");
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003519 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_DE, migrateAppsData);
Felipe Leme3aad1be2019-05-31 11:43:12 -07003520 t.traceEnd();
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003521
3522 if (userId != UserHandle.USER_SYSTEM) {
Felipe Leme3aad1be2019-05-31 11:43:12 -07003523 t.traceBegin("applyUserRestrictions");
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003524 synchronized (mRestrictionsLock) {
3525 applyUserRestrictionsLR(userId);
3526 }
Felipe Leme3aad1be2019-05-31 11:43:12 -07003527 t.traceEnd();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003528 }
Felipe Leme3aad1be2019-05-31 11:43:12 -07003529 t.traceEnd(); // onBeforeStartUser
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003530 }
3531
3532 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003533 * Called right before a user is unlocked. This gives us a chance to prepare
3534 * app storage.
3535 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003536 public void onBeforeUnlockUser(@UserIdInt int userId) {
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003537 UserInfo userInfo = getUserInfo(userId);
3538 if (userInfo == null) {
3539 return;
3540 }
3541 final int userSerial = userInfo.serialNumber;
3542 // Migrate only if build fingerprints mismatch
3543 boolean migrateAppsData = !Build.FINGERPRINT.equals(userInfo.lastLoggedInFingerprint);
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -08003544 mUserDataPreparer.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_CE);
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003545 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_CE, migrateAppsData);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003546 }
3547
3548 /**
Fyodor Kupolov50979d12017-01-27 17:36:32 -08003549 * Examine all users present on given mounted volume, and destroy data
3550 * belonging to users that are no longer valid, or whose user ID has been
3551 * recycled.
3552 */
3553 void reconcileUsers(String volumeUuid) {
3554 mUserDataPreparer.reconcileUsers(volumeUuid, getUsers(true /* excludeDying */));
3555 }
3556
3557 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07003558 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasanieb437d42016-04-29 09:31:25 -07003559 * This is called with ActivityManagerService lock held.
Amith Yamasani920ace02012-09-20 22:15:37 -07003560 * @param userId the user that was just foregrounded
3561 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003562 public void onUserLoggedIn(@UserIdInt int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -08003563 UserData userData = getUserDataNoChecks(userId);
3564 if (userData == null || userData.info.partial) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003565 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
3566 return;
3567 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003568
3569 final long now = System.currentTimeMillis();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003570 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani12747872015-12-07 14:19:49 -08003571 userData.info.lastLoggedInTime = now;
Amith Yamasani920ace02012-09-20 22:15:37 -07003572 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003573 userData.info.lastLoggedInFingerprint = Build.FINGERPRINT;
3574 scheduleWriteUser(userData);
Amith Yamasani920ace02012-09-20 22:15:37 -07003575 }
3576
3577 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07003578 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani0b285492011-04-14 17:35:23 -07003579 */
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003580 @VisibleForTesting
3581 int getNextAvailableId() {
3582 int nextId;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003583 synchronized (mUsersLock) {
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003584 nextId = scanNextAvailableIdLocked();
3585 if (nextId >= 0) {
3586 return nextId;
3587 }
3588 // All ids up to MAX_USER_ID were used. Remove all mRemovingUserIds,
3589 // except most recently removed
3590 if (mRemovingUserIds.size() > 0) {
3591 Slog.i(LOG_TAG, "All available IDs are used. Recycling LRU ids.");
3592 mRemovingUserIds.clear();
3593 for (Integer recentlyRemovedId : mRecentlyRemovedIds) {
3594 mRemovingUserIds.put(recentlyRemovedId, true);
Amith Yamasani195263742012-08-21 15:40:12 -07003595 }
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003596 nextId = scanNextAvailableIdLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003597 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003598 }
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003599 if (nextId < 0) {
3600 throw new IllegalStateException("No user id available!");
3601 }
3602 return nextId;
3603 }
3604
Andreas Gampea36dc622018-02-05 17:19:22 -08003605 @GuardedBy("mUsersLock")
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003606 private int scanNextAvailableIdLocked() {
3607 for (int i = MIN_USER_ID; i < MAX_USER_ID; i++) {
3608 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
3609 return i;
3610 }
3611 }
3612 return -1;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003613 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003614
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003615 private static String packageToRestrictionsFileName(String packageName) {
Amith Yamasanifc95e702013-09-26 13:20:17 -07003616 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
3617 }
3618
Amith Yamasani920ace02012-09-20 22:15:37 -07003619 @Override
Bookatzf56f2582019-09-04 16:06:41 -07003620 public void setSeedAccountData(@UserIdInt int userId, String accountName, String accountType,
Amith Yamasani12747872015-12-07 14:19:49 -08003621 PersistableBundle accountOptions, boolean persist) {
3622 checkManageUsersPermission("Require MANAGE_USERS permission to set user seed data");
3623 synchronized (mPackagesLock) {
3624 final UserData userData;
3625 synchronized (mUsersLock) {
3626 userData = getUserDataLU(userId);
3627 if (userData == null) {
3628 Slog.e(LOG_TAG, "No such user for settings seed data u=" + userId);
3629 return;
3630 }
3631 userData.seedAccountName = accountName;
3632 userData.seedAccountType = accountType;
3633 userData.seedAccountOptions = accountOptions;
3634 userData.persistSeedData = persist;
3635 }
3636 if (persist) {
3637 writeUserLP(userData);
3638 }
3639 }
3640 }
3641
3642 @Override
3643 public String getSeedAccountName() throws RemoteException {
3644 checkManageUsersPermission("Cannot get seed account information");
3645 synchronized (mUsersLock) {
3646 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3647 return userData.seedAccountName;
3648 }
3649 }
3650
3651 @Override
3652 public String getSeedAccountType() throws RemoteException {
3653 checkManageUsersPermission("Cannot get seed account information");
3654 synchronized (mUsersLock) {
3655 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3656 return userData.seedAccountType;
3657 }
3658 }
3659
3660 @Override
3661 public PersistableBundle getSeedAccountOptions() throws RemoteException {
3662 checkManageUsersPermission("Cannot get seed account information");
3663 synchronized (mUsersLock) {
3664 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3665 return userData.seedAccountOptions;
3666 }
3667 }
3668
3669 @Override
3670 public void clearSeedAccountData() throws RemoteException {
3671 checkManageUsersPermission("Cannot clear seed account information");
3672 synchronized (mPackagesLock) {
3673 UserData userData;
3674 synchronized (mUsersLock) {
3675 userData = getUserDataLU(UserHandle.getCallingUserId());
3676 if (userData == null) return;
3677 userData.clearSeedAccountData();
3678 }
3679 writeUserLP(userData);
3680 }
3681 }
3682
3683 @Override
3684 public boolean someUserHasSeedAccount(String accountName, String accountType)
3685 throws RemoteException {
3686 checkManageUsersPermission("Cannot check seed account information");
3687 synchronized (mUsersLock) {
3688 final int userSize = mUsers.size();
3689 for (int i = 0; i < userSize; i++) {
3690 final UserData data = mUsers.valueAt(i);
3691 if (data.info.isInitialized()) continue;
3692 if (data.seedAccountName == null || !data.seedAccountName.equals(accountName)) {
3693 continue;
3694 }
3695 if (data.seedAccountType == null || !data.seedAccountType.equals(accountType)) {
3696 continue;
3697 }
3698 return true;
3699 }
3700 }
3701 return false;
3702 }
3703
3704 @Override
Todd Kennedy60459ab2015-10-30 11:32:16 -07003705 public void onShellCommand(FileDescriptor in, FileDescriptor out,
Dianne Hackborn354736e2016-08-22 17:00:05 -07003706 FileDescriptor err, String[] args, ShellCallback callback,
3707 ResultReceiver resultReceiver) {
3708 (new Shell()).exec(this, in, out, err, args, callback, resultReceiver);
Todd Kennedy60459ab2015-10-30 11:32:16 -07003709 }
3710
3711 int onShellCommand(Shell shell, String cmd) {
3712 if (cmd == null) {
3713 return shell.handleDefaultCommands(cmd);
3714 }
3715
3716 final PrintWriter pw = shell.getOutPrintWriter();
3717 try {
3718 switch(cmd) {
3719 case "list":
3720 return runList(pw);
Hui Yu8ba65972018-04-16 18:45:48 -07003721 default:
3722 return shell.handleDefaultCommands(cmd);
Todd Kennedy60459ab2015-10-30 11:32:16 -07003723 }
3724 } catch (RemoteException e) {
3725 pw.println("Remote exception: " + e);
3726 }
3727 return -1;
3728 }
3729
3730 private int runList(PrintWriter pw) throws RemoteException {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003731 final IActivityManager am = ActivityManager.getService();
Todd Kennedy60459ab2015-10-30 11:32:16 -07003732 final List<UserInfo> users = getUsers(false);
3733 if (users == null) {
3734 pw.println("Error: couldn't get users");
3735 return 1;
3736 } else {
3737 pw.println("Users:");
3738 for (int i = 0; i < users.size(); i++) {
Jeff Sharkeye17ac152015-11-06 22:40:29 -08003739 String running = am.isUserRunning(users.get(i).id, 0) ? " running" : "";
Todd Kennedy60459ab2015-10-30 11:32:16 -07003740 pw.println("\t" + users.get(i).toString() + running);
3741 }
3742 return 0;
3743 }
3744 }
3745
3746 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -07003747 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06003748 if (!DumpUtils.checkDumpPermission(mContext, LOG_TAG, pw)) return;
Amith Yamasani920ace02012-09-20 22:15:37 -07003749
3750 long now = System.currentTimeMillis();
Makoto Onuki73dded22017-12-20 13:14:48 +09003751 final long nowRealtime = SystemClock.elapsedRealtime();
Felipe Lemed7b88382019-06-12 17:40:53 -07003752
3753 final int currentUser = LocalServices.getService(ActivityManagerInternal.class)
3754 .getCurrentUserId();
3755 pw.print("Current user: "); pw.println(currentUser);
3756
Amith Yamasani920ace02012-09-20 22:15:37 -07003757 StringBuilder sb = new StringBuilder();
3758 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003759 synchronized (mUsersLock) {
3760 pw.println("Users:");
3761 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003762 UserData userData = mUsers.valueAt(i);
3763 if (userData == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003764 continue;
3765 }
Amith Yamasani12747872015-12-07 14:19:49 -08003766 UserInfo userInfo = userData.info;
3767 final int userId = userInfo.id;
3768 pw.print(" "); pw.print(userInfo);
3769 pw.print(" serialNo="); pw.print(userInfo.serialNumber);
Felipe Lemed7b88382019-06-12 17:40:53 -07003770 pw.print(" isPrimary="); pw.print(userInfo.isPrimary());
Makoto Onukie7927da2015-11-25 10:05:17 -08003771 if (mRemovingUserIds.get(userId)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003772 pw.print(" <removing> ");
3773 }
Amith Yamasani12747872015-12-07 14:19:49 -08003774 if (userInfo.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003775 pw.print(" <partial>");
3776 }
3777 pw.println();
Felipe Lemee5434c32019-08-13 09:28:33 -07003778 pw.print(" Flags: "); pw.print(userInfo.flags); pw.print(" (");
3779 pw.print(UserInfo.flagsToString(userInfo.flags)); pw.println(")");
Makoto Onuki88aef752017-03-29 16:52:03 -07003780 pw.print(" State: ");
3781 final int state;
3782 synchronized (mUserStates) {
3783 state = mUserStates.get(userId, -1);
3784 }
3785 pw.println(UserState.stateToString(state));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003786 pw.print(" Created: ");
Makoto Onuki73dded22017-12-20 13:14:48 +09003787 dumpTimeAgo(pw, sb, now, userInfo.creationTime);
3788
Fyodor Kupolov82402752015-10-28 14:54:51 -07003789 pw.print(" Last logged in: ");
Makoto Onuki73dded22017-12-20 13:14:48 +09003790 dumpTimeAgo(pw, sb, now, userInfo.lastLoggedInTime);
3791
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003792 pw.print(" Last logged in fingerprint: ");
3793 pw.println(userInfo.lastLoggedInFingerprint);
Makoto Onuki73dded22017-12-20 13:14:48 +09003794
3795 pw.print(" Start time: ");
3796 dumpTimeAgo(pw, sb, nowRealtime, userData.startRealtime);
3797
3798 pw.print(" Unlock time: ");
3799 dumpTimeAgo(pw, sb, nowRealtime, userData.unlockRealtime);
3800
Makoto Onukie7927da2015-11-25 10:05:17 -08003801 pw.print(" Has profile owner: ");
3802 pw.println(mIsUserManaged.get(userId));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003803 pw.println(" Restrictions:");
3804 synchronized (mRestrictionsLock) {
3805 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003806 pw, " ", mBaseUserRestrictions.get(userInfo.id));
Pavel Grafov6a40f092016-10-25 15:46:51 +01003807 pw.println(" Device policy global restrictions:");
3808 UserRestrictionsUtils.dumpRestrictions(
3809 pw, " ", mDevicePolicyGlobalUserRestrictions.get(userInfo.id));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003810 pw.println(" Device policy local restrictions:");
3811 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003812 pw, " ", mDevicePolicyLocalUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003813 pw.println(" Effective restrictions:");
3814 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003815 pw, " ", mCachedEffectiveUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003816 }
Amith Yamasani12747872015-12-07 14:19:49 -08003817
3818 if (userData.account != null) {
3819 pw.print(" Account name: " + userData.account);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08003820 pw.println();
3821 }
Amith Yamasani12747872015-12-07 14:19:49 -08003822
3823 if (userData.seedAccountName != null) {
3824 pw.print(" Seed account name: " + userData.seedAccountName);
3825 pw.println();
3826 if (userData.seedAccountType != null) {
3827 pw.print(" account type: " + userData.seedAccountType);
3828 pw.println();
3829 }
3830 if (userData.seedAccountOptions != null) {
3831 pw.print(" account options exist");
3832 pw.println();
3833 }
3834 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003835 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003836 }
Amith Yamasani12747872015-12-07 14:19:49 -08003837 pw.println();
Pavel Grafov6a40f092016-10-25 15:46:51 +01003838 pw.println(" Device owner id:" + mDeviceOwnerUserId);
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01003839 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003840 pw.println(" Guest restrictions:");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003841 synchronized (mGuestRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003842 UserRestrictionsUtils.dumpRestrictions(pw, " ", mGuestRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003843 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003844 synchronized (mUsersLock) {
3845 pw.println();
3846 pw.println(" Device managed: " + mIsDeviceManaged);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003847 if (mRemovingUserIds.size() > 0) {
3848 pw.println();
3849 pw.println(" Recently removed userIds: " + mRecentlyRemovedIds);
3850 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003851 }
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003852 synchronized (mUserStates) {
3853 pw.println(" Started users state: " + mUserStates);
3854 }
Felipe Lemed7b88382019-06-12 17:40:53 -07003855 } // synchronized (mPackagesLock)
3856
3857 // Dump some capabilities
3858 pw.println();
3859 pw.println(" Max users: " + UserManager.getMaxSupportedUsers());
3860 pw.println(" Supports switchable users: " + UserManager.supportsMultipleUsers());
3861 pw.println(" All guests ephemeral: " + Resources.getSystem().getBoolean(
3862 com.android.internal.R.bool.config_guestUserEphemeral));
3863 pw.println(" Is split-system user: " + UserManager.isSplitSystemUser());
Felipe Lemee5434c32019-08-13 09:28:33 -07003864 pw.println(" Is headless-system mode: " + UserManager.isHeadlessSystemUserMode());
3865 pw.println(" User version: " + mUserVersion);
Amith Yamasani920ace02012-09-20 22:15:37 -07003866 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08003867
Makoto Onuki73dded22017-12-20 13:14:48 +09003868 private static void dumpTimeAgo(PrintWriter pw, StringBuilder sb, long nowTime, long time) {
3869 if (time == 0) {
3870 pw.println("<unknown>");
3871 } else {
3872 sb.setLength(0);
3873 TimeUtils.formatDuration(nowTime - time, sb);
3874 sb.append(" ago");
3875 pw.println(sb);
3876 }
3877 }
3878
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08003879 final class MainHandler extends Handler {
3880
3881 @Override
3882 public void handleMessage(Message msg) {
3883 switch (msg.what) {
3884 case WRITE_USER_MSG:
3885 removeMessages(WRITE_USER_MSG, msg.obj);
3886 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08003887 int userId = ((UserData) msg.obj).info.id;
3888 UserData userData = getUserDataNoChecks(userId);
3889 if (userData != null) {
3890 writeUserLP(userData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08003891 }
3892 }
3893 }
3894 }
3895 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07003896
3897 /**
3898 * @param userId
3899 * @return whether the user has been initialized yet
3900 */
Bookatzf56f2582019-09-04 16:06:41 -07003901 boolean isUserInitialized(@UserIdInt int userId) {
Todd Kennedy0eb97382017-10-03 16:57:22 -07003902 return mLocalService.isUserInitialized(userId);
Amith Yamasanibb054c92015-07-09 14:16:27 -07003903 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003904
3905 private class LocalService extends UserManagerInternal {
Makoto Onuki068c54a2015-10-13 14:34:03 -07003906 @Override
Bookatzf56f2582019-09-04 16:06:41 -07003907 public void setDevicePolicyUserRestrictions(@UserIdInt int userId,
3908 @Nullable Bundle restrictions, boolean isDeviceOwner, int cameraRestrictionScope) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01003909 UserManagerService.this.setDevicePolicyUserRestrictionsInner(userId, restrictions,
3910 isDeviceOwner, cameraRestrictionScope);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003911 }
3912
3913 @Override
Bookatzf56f2582019-09-04 16:06:41 -07003914 public Bundle getBaseUserRestrictions(@UserIdInt int userId) {
Makoto Onuki068c54a2015-10-13 14:34:03 -07003915 synchronized (mRestrictionsLock) {
3916 return mBaseUserRestrictions.get(userId);
3917 }
3918 }
3919
3920 @Override
3921 public void setBaseUserRestrictionsByDpmsForMigration(
Bookatzf56f2582019-09-04 16:06:41 -07003922 @UserIdInt int userId, Bundle baseRestrictions) {
Makoto Onuki068c54a2015-10-13 14:34:03 -07003923 synchronized (mRestrictionsLock) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01003924 if (updateRestrictionsIfNeededLR(
3925 userId, new Bundle(baseRestrictions), mBaseUserRestrictions)) {
3926 invalidateEffectiveUserRestrictionsLR(userId);
3927 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003928 }
3929
Amith Yamasani12747872015-12-07 14:19:49 -08003930 final UserData userData = getUserDataNoChecks(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003931 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08003932 if (userData != null) {
3933 writeUserLP(userData);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003934 } else {
3935 Slog.w(LOG_TAG, "UserInfo not found for " + userId);
3936 }
3937 }
3938 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08003939
3940 @Override
Bookatzf56f2582019-09-04 16:06:41 -07003941 public boolean getUserRestriction(@UserIdInt int userId, String key) {
Makoto Onukid45a4a22015-11-02 17:17:38 -08003942 return getUserRestrictions(userId).getBoolean(key);
3943 }
3944
3945 @Override
3946 public void addUserRestrictionsListener(UserRestrictionsListener listener) {
3947 synchronized (mUserRestrictionsListeners) {
3948 mUserRestrictionsListeners.add(listener);
3949 }
3950 }
3951
3952 @Override
3953 public void removeUserRestrictionsListener(UserRestrictionsListener listener) {
3954 synchronized (mUserRestrictionsListeners) {
3955 mUserRestrictionsListeners.remove(listener);
3956 }
3957 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003958
3959 @Override
3960 public void setDeviceManaged(boolean isManaged) {
3961 synchronized (mUsersLock) {
3962 mIsDeviceManaged = isManaged;
3963 }
3964 }
3965
3966 @Override
Bookatzf56f2582019-09-04 16:06:41 -07003967 public void setUserManaged(@UserIdInt int userId, boolean isManaged) {
Makoto Onukie7927da2015-11-25 10:05:17 -08003968 synchronized (mUsersLock) {
3969 mIsUserManaged.put(userId, isManaged);
3970 }
3971 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01003972
3973 @Override
Bookatzf56f2582019-09-04 16:06:41 -07003974 public void setUserIcon(@UserIdInt int userId, Bitmap bitmap) {
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01003975 long ident = Binder.clearCallingIdentity();
3976 try {
3977 synchronized (mPackagesLock) {
3978 UserData userData = getUserDataNoChecks(userId);
3979 if (userData == null || userData.info.partial) {
3980 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
3981 return;
3982 }
3983 writeBitmapLP(userData.info, bitmap);
3984 writeUserLP(userData);
3985 }
3986 sendUserInfoChangedBroadcast(userId);
3987 } finally {
3988 Binder.restoreCallingIdentity(ident);
3989 }
3990 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01003991
3992 @Override
3993 public void setForceEphemeralUsers(boolean forceEphemeralUsers) {
3994 synchronized (mUsersLock) {
3995 mForceEphemeralUsers = forceEphemeralUsers;
3996 }
3997 }
3998
3999 @Override
4000 public void removeAllUsers() {
4001 if (UserHandle.USER_SYSTEM == ActivityManager.getCurrentUser()) {
4002 // Remove the non-system users straight away.
4003 removeNonSystemUsers();
4004 } else {
4005 // Switch to the system user first and then remove the other users.
4006 BroadcastReceiver userSwitchedReceiver = new BroadcastReceiver() {
4007 @Override
4008 public void onReceive(Context context, Intent intent) {
4009 int userId =
4010 intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
4011 if (userId != UserHandle.USER_SYSTEM) {
4012 return;
4013 }
4014 mContext.unregisterReceiver(this);
4015 removeNonSystemUsers();
4016 }
4017 };
4018 IntentFilter userSwitchedFilter = new IntentFilter();
4019 userSwitchedFilter.addAction(Intent.ACTION_USER_SWITCHED);
4020 mContext.registerReceiver(
4021 userSwitchedReceiver, userSwitchedFilter, null, mHandler);
4022
4023 // Switch to the system user.
4024 ActivityManager am =
4025 (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
4026 am.switchUser(UserHandle.USER_SYSTEM);
4027 }
4028 }
phweisse9c44062016-02-10 12:57:38 +01004029
4030 @Override
Bookatzf56f2582019-09-04 16:06:41 -07004031 public void onEphemeralUserStop(@UserIdInt int userId) {
Lenka Trochtova1ddda472016-02-12 10:42:12 +01004032 synchronized (mUsersLock) {
4033 UserInfo userInfo = getUserInfoLU(userId);
4034 if (userInfo != null && userInfo.isEphemeral()) {
4035 // Do not allow switching back to the ephemeral user again as the user is going
4036 // to be deleted.
4037 userInfo.flags |= UserInfo.FLAG_DISABLED;
4038 if (userInfo.isGuest()) {
4039 // Indicate that the guest will be deleted after it stops.
4040 userInfo.guestToRemove = true;
4041 }
4042 }
4043 }
4044 }
4045
4046 @Override
Alex Chaub6a9f942017-11-07 11:28:56 +08004047 public UserInfo createUserEvenWhenDisallowed(String name, int flags,
4048 String[] disallowedPackages) {
4049 UserInfo user = createUserInternalUnchecked(name, flags, UserHandle.USER_NULL,
4050 disallowedPackages);
phweisse9c44062016-02-10 12:57:38 +01004051 // Keep this in sync with UserManager.createUser
Christine Franks97a54802017-08-09 10:06:43 -07004052 if (user != null && !user.isAdmin() && !user.isDemo()) {
phweisse9c44062016-02-10 12:57:38 +01004053 setUserRestriction(UserManager.DISALLOW_SMS, true, user.id);
4054 setUserRestriction(UserManager.DISALLOW_OUTGOING_CALLS, true, user.id);
4055 }
4056 return user;
4057 }
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07004058
4059 @Override
Bookatzf56f2582019-09-04 16:06:41 -07004060 public boolean removeUserEvenWhenDisallowed(@UserIdInt int userId) {
Nicolas Prevotdf1b87d2016-10-25 13:57:08 +01004061 return removeUserUnchecked(userId);
4062 }
4063
4064 @Override
Bookatzf56f2582019-09-04 16:06:41 -07004065 public boolean isUserRunning(@UserIdInt int userId) {
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00004066 synchronized (mUserStates) {
4067 return mUserStates.get(userId, -1) >= 0;
4068 }
4069 }
4070
4071 @Override
Bookatzf56f2582019-09-04 16:06:41 -07004072 public void setUserState(@UserIdInt int userId, int userState) {
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00004073 synchronized (mUserStates) {
4074 mUserStates.put(userId, userState);
4075 }
4076 }
4077
4078 @Override
Bookatzf56f2582019-09-04 16:06:41 -07004079 public void removeUserState(@UserIdInt int userId) {
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00004080 synchronized (mUserStates) {
4081 mUserStates.delete(userId);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07004082 }
4083 }
4084
4085 @Override
Michael Wachenschwanz3f2b6552017-05-15 13:53:09 -07004086 public int[] getUserIds() {
4087 return UserManagerService.this.getUserIds();
4088 }
4089
4090 @Override
Bookatzf56f2582019-09-04 16:06:41 -07004091 public boolean isUserUnlockingOrUnlocked(@UserIdInt int userId) {
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07004092 int state;
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00004093 synchronized (mUserStates) {
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07004094 state = mUserStates.get(userId, -1);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07004095 }
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07004096 // Special case, in the stopping/shutdown state user key can still be unlocked
4097 if (state == UserState.STATE_STOPPING || state == UserState.STATE_SHUTDOWN) {
4098 return StorageManager.isUserKeyUnlocked(userId);
4099 }
4100 return (state == UserState.STATE_RUNNING_UNLOCKING)
4101 || (state == UserState.STATE_RUNNING_UNLOCKED);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07004102 }
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08004103
4104 @Override
Bookatzf56f2582019-09-04 16:06:41 -07004105 public boolean isUserUnlocked(@UserIdInt int userId) {
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07004106 int state;
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08004107 synchronized (mUserStates) {
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07004108 state = mUserStates.get(userId, -1);
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08004109 }
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07004110 // Special case, in the stopping/shutdown state user key can still be unlocked
4111 if (state == UserState.STATE_STOPPING || state == UserState.STATE_SHUTDOWN) {
4112 return StorageManager.isUserKeyUnlocked(userId);
4113 }
4114 return state == UserState.STATE_RUNNING_UNLOCKED;
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08004115 }
Todd Kennedy0eb97382017-10-03 16:57:22 -07004116
4117 @Override
Bookatzf56f2582019-09-04 16:06:41 -07004118 public boolean isUserInitialized(@UserIdInt int userId) {
Todd Kennedy0eb97382017-10-03 16:57:22 -07004119 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
4120 }
4121
4122 @Override
Bookatzf56f2582019-09-04 16:06:41 -07004123 public boolean exists(@UserIdInt int userId) {
Todd Kennedy0eb97382017-10-03 16:57:22 -07004124 return getUserInfoNoChecks(userId) != null;
4125 }
Sunny Goyal145c8f82018-02-15 14:27:09 -08004126
4127 @Override
4128 public boolean isProfileAccessible(int callingUserId, int targetUserId, String debugMsg,
4129 boolean throwSecurityException) {
4130 if (targetUserId == callingUserId) {
4131 return true;
4132 }
4133 synchronized (mUsersLock) {
4134 UserInfo callingUserInfo = getUserInfoLU(callingUserId);
4135 if (callingUserInfo == null || callingUserInfo.isManagedProfile()) {
4136 if (throwSecurityException) {
4137 throw new SecurityException(
4138 debugMsg + " for another profile "
4139 + targetUserId + " from " + callingUserId);
4140 }
4141 }
4142
4143 UserInfo targetUserInfo = getUserInfoLU(targetUserId);
4144 if (targetUserInfo == null || !targetUserInfo.isEnabled()) {
4145 // Do not throw any exception here as this could happen due to race conditions
4146 // between the system updating its state and the client getting notified.
4147 if (throwSecurityException) {
4148 Slog.w(LOG_TAG, debugMsg + " for disabled profile "
4149 + targetUserId + " from " + callingUserId);
4150 }
4151 return false;
4152 }
4153
4154 if (targetUserInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID ||
4155 targetUserInfo.profileGroupId != callingUserInfo.profileGroupId) {
4156 if (throwSecurityException) {
4157 throw new SecurityException(
4158 debugMsg + " for unrelated profile " + targetUserId);
4159 }
4160 return false;
4161 }
4162 }
4163 return true;
4164 }
4165
4166 @Override
Bookatzf56f2582019-09-04 16:06:41 -07004167 public int getProfileParentId(@UserIdInt int userId) {
Sunny Goyal145c8f82018-02-15 14:27:09 -08004168 synchronized (mUsersLock) {
4169 UserInfo profileParent = getProfileParentLU(userId);
4170 if (profileParent == null) {
4171 return userId;
4172 }
4173 return profileParent.id;
4174 }
4175 }
yuemingw1d13eae2018-01-30 17:27:54 +00004176
4177 @Override
4178 public boolean isSettingRestrictedForUser(String setting, @UserIdInt int userId,
4179 String value, int callingUid) {
4180 return UserRestrictionsUtils.isSettingRestrictedForUser(mContext, setting, userId,
4181 value, callingUid);
4182 }
Patrick Baumann2f2fd712019-07-31 15:18:53 -07004183
4184 @Override
Bookatzf56f2582019-09-04 16:06:41 -07004185 public boolean hasUserRestriction(String restrictionKey, @UserIdInt int userId) {
Patrick Baumann2f2fd712019-07-31 15:18:53 -07004186 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
4187 return false;
4188 }
4189 Bundle restrictions = getEffectiveUserRestrictions(userId);
4190 return restrictions != null && restrictions.getBoolean(restrictionKey);
4191 }
Felipe Lemee5434c32019-08-13 09:28:33 -07004192
4193 public @Nullable UserInfo getUserInfo(@UserIdInt int userId) {
4194 UserData userData;
4195 synchronized (mUsersLock) {
4196 userData = mUsers.get(userId);
4197 }
4198 return userData == null ? null : userData.info;
4199 }
Felipe Leme987655d2019-08-26 10:45:24 -07004200
4201 public @NonNull UserInfo[] getUserInfos() {
4202 synchronized (mUsersLock) {
4203 int userSize = mUsers.size();
4204 UserInfo[] allInfos = new UserInfo[userSize];
4205 for (int i = 0; i < userSize; i++) {
4206 allInfos[i] = mUsers.valueAt(i).info;
4207 }
4208 return allInfos;
4209 }
4210 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01004211 }
4212
4213 /* Remove all the users except of the system one. */
4214 private void removeNonSystemUsers() {
4215 ArrayList<UserInfo> usersToRemove = new ArrayList<>();
4216 synchronized (mUsersLock) {
4217 final int userSize = mUsers.size();
4218 for (int i = 0; i < userSize; i++) {
4219 UserInfo ui = mUsers.valueAt(i).info;
4220 if (ui.id != UserHandle.USER_SYSTEM) {
4221 usersToRemove.add(ui);
4222 }
4223 }
4224 }
4225 for (UserInfo ui: usersToRemove) {
4226 removeUser(ui.id);
4227 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07004228 }
Todd Kennedy60459ab2015-10-30 11:32:16 -07004229
4230 private class Shell extends ShellCommand {
4231 @Override
4232 public int onCommand(String cmd) {
4233 return onShellCommand(this, cmd);
4234 }
4235
4236 @Override
4237 public void onHelp() {
4238 final PrintWriter pw = getOutPrintWriter();
4239 pw.println("User manager (user) commands:");
4240 pw.println(" help");
4241 pw.println(" Print this help text.");
4242 pw.println("");
4243 pw.println(" list");
4244 pw.println(" Prints all users on the system.");
4245 }
4246 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08004247
4248 private static void debug(String message) {
4249 Log.d(LOG_TAG, message +
4250 (DBG_WITH_STACKTRACE ? " called at\n" + Debug.getCallers(10, " ") : ""));
4251 }
Kenny Guy02c89902016-11-15 19:36:38 +00004252
4253 @VisibleForTesting
4254 static int getMaxManagedProfiles() {
4255 // Allow overriding max managed profiles on debuggable builds for testing
4256 // of multiple profiles.
4257 if (!Build.IS_DEBUGGABLE) {
4258 return MAX_MANAGED_PROFILES;
4259 } else {
4260 return SystemProperties.getInt("persist.sys.max_profiles",
4261 MAX_MANAGED_PROFILES);
4262 }
4263 }
4264
Andreas Gampe2e8c7672018-07-20 13:01:08 -07004265 @GuardedBy("mUsersLock")
Kenny Guy02c89902016-11-15 19:36:38 +00004266 @VisibleForTesting
4267 int getFreeProfileBadgeLU(int parentUserId) {
4268 int maxManagedProfiles = getMaxManagedProfiles();
4269 boolean[] usedBadges = new boolean[maxManagedProfiles];
4270 final int userSize = mUsers.size();
4271 for (int i = 0; i < userSize; i++) {
4272 UserInfo ui = mUsers.valueAt(i).info;
4273 // Check which badge indexes are already used by this profile group.
4274 if (ui.isManagedProfile()
4275 && ui.profileGroupId == parentUserId
4276 && !mRemovingUserIds.get(ui.id)
4277 && ui.profileBadge < maxManagedProfiles) {
4278 usedBadges[ui.profileBadge] = true;
4279 }
4280 }
4281 for (int i = 0; i < maxManagedProfiles; i++) {
4282 if (!usedBadges[i]) {
4283 return i;
4284 }
4285 }
4286 return 0;
4287 }
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07004288
4289 /**
4290 * Checks if the given user has a managed profile associated with it.
4291 * @param userId The parent user
4292 * @return
4293 */
Bookatzf56f2582019-09-04 16:06:41 -07004294 boolean hasManagedProfile(@UserIdInt int userId) {
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07004295 synchronized (mUsersLock) {
4296 UserInfo userInfo = getUserInfoLU(userId);
4297 final int userSize = mUsers.size();
4298 for (int i = 0; i < userSize; i++) {
4299 UserInfo profile = mUsers.valueAt(i).info;
4300 if (userId != profile.id && isProfileOf(userInfo, profile)) {
4301 return true;
4302 }
4303 }
4304 return false;
4305 }
4306 }
Tony Makd390ae92017-12-28 13:23:10 +00004307
4308 /**
4309 * Check if the calling package name matches with the calling UID, throw
4310 * {@link SecurityException} if not.
4311 */
4312 private void verifyCallingPackage(String callingPackage, int callingUid) {
4313 int packageUid = mPm.getPackageUid(callingPackage, 0, UserHandle.getUserId(callingUid));
4314 if (packageUid != callingUid) {
4315 throw new SecurityException("Specified package " + callingPackage
4316 + " does not match the calling uid " + callingUid);
4317 }
4318 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07004319}