blob: fe371250ac17e3f75f5663e843bb3d4958a552d7 [file] [log] [blame]
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
Benjamin Franzf02420c2016-04-04 18:52:21 +010019import static android.content.Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS;
20import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
21
Xiaohui Chenb3b92582015-12-07 11:22:13 -080022import android.Manifest;
Xiaohui Chen594f2082015-08-18 11:04:20 -070023import android.annotation.NonNull;
Makoto Onuki068c54a2015-10-13 14:34:03 -070024import android.annotation.Nullable;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -060025import android.annotation.UserIdInt;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070026import android.app.Activity;
Amith Yamasani2a003292012-08-14 18:25:45 -070027import android.app.ActivityManager;
Amith Yamasani515d4062015-09-28 11:30:06 -070028import android.app.ActivityManagerInternal;
Andrew Scull85a63bc2016-10-24 13:47:47 +010029import android.app.ActivityManagerNative;
Todd Kennedy60459ab2015-10-30 11:32:16 -070030import android.app.IActivityManager;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070031import android.app.IStopUserCallback;
Benjamin Franzf02420c2016-04-04 18:52:21 +010032import android.app.KeyguardManager;
Ricky Waib1dd80b2016-06-07 18:00:55 +010033import android.app.PendingIntent;
arangelov9b632d72018-12-07 23:21:22 +000034import android.app.admin.DevicePolicyEventLogger;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070035import android.content.BroadcastReceiver;
Amith Yamasani258848d2012-08-10 17:06:33 -070036import android.content.Context;
37import android.content.Intent;
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +010038import android.content.IntentFilter;
Benjamin Franzf02420c2016-04-04 18:52:21 +010039import android.content.IntentSender;
Amith Yamasani0b285492011-04-14 17:35:23 -070040import android.content.pm.PackageManager;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -080041import android.content.pm.PackageManager.NameNotFoundException;
Tony Make3d1f652017-12-12 11:00:37 +000042import android.content.pm.ShortcutServiceInternal;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070043import android.content.pm.UserInfo;
Felipe Lemec1ca4412019-09-11 09:23:26 -070044import android.content.pm.UserInfo.UserInfoFlag;
Lenka Trochtova02fee152015-12-22 14:26:18 +010045import android.content.res.Resources;
Amith Yamasanie928d7d2012-09-17 21:46:51 -070046import android.graphics.Bitmap;
Amith Yamasani258848d2012-08-10 17:06:33 -070047import android.os.Binder;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -060048import android.os.Build;
Amith Yamasanie4cf7342012-12-17 11:12:09 -080049import android.os.Bundle;
Makoto Onuki1a2cd742015-11-16 13:51:27 -080050import android.os.Debug;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070051import android.os.Environment;
52import android.os.FileUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080053import android.os.Handler;
Svet Ganov9cea80cd2016-02-16 11:47:00 -080054import android.os.IBinder;
Tony Mak64fd8c02017-12-01 19:11:59 +000055import android.os.IProgressListener;
Amith Yamasani258848d2012-08-10 17:06:33 -070056import android.os.IUserManager;
Christopher Tate65fb2e42019-10-11 17:00:23 -070057import android.os.IUserRestrictionsListener;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -080058import android.os.Message;
Adrian Roos1bdff912015-02-17 15:51:35 +010059import android.os.ParcelFileDescriptor;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070060import android.os.Parcelable;
Amith Yamasani12747872015-12-07 14:19:49 -080061import android.os.PersistableBundle;
Amith Yamasani258848d2012-08-10 17:06:33 -070062import android.os.Process;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070063import android.os.RemoteException;
Todd Kennedy60459ab2015-10-30 11:32:16 -070064import android.os.ResultReceiver;
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +010065import android.os.SELinux;
Jason Monk62062992014-05-06 09:55:28 -040066import android.os.ServiceManager;
Dianne Hackborn354736e2016-08-22 17:00:05 -070067import android.os.ShellCallback;
Todd Kennedy60459ab2015-10-30 11:32:16 -070068import android.os.ShellCommand;
Makoto Onuki73dded22017-12-20 13:14:48 +090069import android.os.SystemClock;
Kenny Guy02c89902016-11-15 19:36:38 +000070import android.os.SystemProperties;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070071import android.os.UserHandle;
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070072import android.os.UserManager;
Pavel Grafov6a40f092016-10-25 15:46:51 +010073import android.os.UserManager.EnforcingUser;
Makoto Onuki068c54a2015-10-13 14:34:03 -070074import android.os.UserManagerInternal;
Makoto Onukid45a4a22015-11-02 17:17:38 -080075import android.os.UserManagerInternal.UserRestrictionsListener;
Paul Crowley85e4e812015-05-19 12:42:00 +010076import android.os.storage.StorageManager;
Amith Yamasanid04aaa32016-06-13 12:09:36 -070077import android.security.GateKeeper;
78import android.service.gatekeeper.IGateKeeperService;
arangelov9b632d72018-12-07 23:21:22 +000079import android.stats.devicepolicy.DevicePolicyEnums;
Bookatz75f0a072019-08-05 14:12:16 -070080import android.util.ArraySet;
Amith Yamasani2a003292012-08-14 18:25:45 -070081import android.util.AtomicFile;
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -070082import android.util.IntArray;
Amith Yamasani655d0e22013-06-12 14:19:10 -070083import android.util.Log;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070084import android.util.Slog;
85import android.util.SparseArray;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080086import android.util.SparseBooleanArray;
Amith Yamasaniea1b9d72016-05-27 15:57:38 +000087import android.util.SparseIntArray;
Amith Yamasani920ace02012-09-20 22:15:37 -070088import android.util.TimeUtils;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070089import android.util.Xml;
90
Makoto Onuki068c54a2015-10-13 14:34:03 -070091import com.android.internal.annotations.GuardedBy;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070092import com.android.internal.annotations.VisibleForTesting;
Jason Monk62062992014-05-06 09:55:28 -040093import com.android.internal.app.IAppOpsService;
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -080094import com.android.internal.logging.MetricsLogger;
Fyodor Kupolova68a2862018-01-30 18:22:00 -080095import com.android.internal.os.BackgroundThread;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -060096import com.android.internal.util.DumpUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080097import com.android.internal.util.FastXmlSerializer;
Makoto Onuki068c54a2015-10-13 14:34:03 -070098import com.android.internal.util.Preconditions;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070099import com.android.internal.util.XmlUtils;
Clara Bayarri10ad84a2015-12-01 17:38:05 +0000100import com.android.internal.widget.LockPatternUtils;
Amith Yamasani515d4062015-09-28 11:30:06 -0700101import com.android.server.LocalServices;
Jeff Sharkey5f3e9342017-03-13 14:53:11 -0600102import com.android.server.LockGuard;
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700103import com.android.server.SystemService;
Amith Yamasaniea1b9d72016-05-27 15:57:38 +0000104import com.android.server.am.UserState;
Suprabh Shuklac5e057c2016-08-08 16:22:44 -0700105import com.android.server.storage.DeviceStorageMonitorInternal;
Felipe Leme3aad1be2019-05-31 11:43:12 -0700106import com.android.server.utils.TimingsTraceAndSlog;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700107import com.android.server.wm.ActivityTaskManagerInternal;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800108
arangelov9b632d72018-12-07 23:21:22 +0000109import libcore.io.IoUtils;
110
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800111import org.xmlpull.v1.XmlPullParser;
112import org.xmlpull.v1.XmlPullParserException;
113import org.xmlpull.v1.XmlSerializer;
114
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700115import java.io.BufferedOutputStream;
116import java.io.File;
Amith Yamasani920ace02012-09-20 22:15:37 -0700117import java.io.FileDescriptor;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700118import java.io.FileInputStream;
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700119import java.io.FileNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700120import java.io.FileOutputStream;
Tony Mak64fd8c02017-12-01 19:11:59 +0000121import java.io.IOException;
Kenny Guy02c89902016-11-15 19:36:38 +0000122import java.io.InputStream;
123import java.io.OutputStream;
Amith Yamasani920ace02012-09-20 22:15:37 -0700124import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100125import java.nio.charset.StandardCharsets;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700126import java.util.ArrayList;
Pavel Grafov6a40f092016-10-25 15:46:51 +0100127import java.util.Collections;
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700128import java.util.LinkedList;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700129import java.util.List;
Narayan Kamath607223f2018-02-19 14:09:02 +0000130import java.util.Objects;
Bookatz75f0a072019-08-05 14:12:16 -0700131import java.util.Set;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700132
Makoto Onuki068c54a2015-10-13 14:34:03 -0700133/**
134 * Service for {@link UserManager}.
135 *
136 * Method naming convention:
Fyodor Kupolov82402752015-10-28 14:54:51 -0700137 * <ul>
Fyodor Kupolovd31cee92017-09-05 16:31:08 -0700138 * <li> Methods suffixed with "LAr" should be called within the {@link #mAppRestrictionsLock} lock.
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800139 * <li> Methods suffixed with "LP" should be called within the {@link #mPackagesLock} lock.
Fyodor Kupolov82402752015-10-28 14:54:51 -0700140 * <li> Methods suffixed with "LR" should be called within the {@link #mRestrictionsLock} lock.
141 * <li> Methods suffixed with "LU" should be called within the {@link #mUsersLock} lock.
142 * </ul>
Makoto Onuki068c54a2015-10-13 14:34:03 -0700143 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700144public class UserManagerService extends IUserManager.Stub {
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700145
Amith Yamasani2a003292012-08-14 18:25:45 -0700146 private static final String LOG_TAG = "UserManagerService";
Makoto Onuki81c61ea2016-01-22 11:22:26 -0800147 static final boolean DBG = false; // DO NOT SUBMIT WITH TRUE
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800148 private static final boolean DBG_WITH_STACKTRACE = false; // DO NOT SUBMIT WITH TRUE
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700149 // Can be used for manual testing of id recycling
150 private static final boolean RELEASE_DELETED_USER_ID = false; // DO NOT SUBMIT WITH TRUE
Amith Yamasani16389312012-10-17 21:20:14 -0700151
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700152 private static final String TAG_NAME = "name";
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800153 private static final String TAG_ACCOUNT = "account";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700154 private static final String ATTR_FLAGS = "flags";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700155 private static final String ATTR_ICON_PATH = "icon";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700156 private static final String ATTR_ID = "id";
Amith Yamasani920ace02012-09-20 22:15:37 -0700157 private static final String ATTR_CREATION_TIME = "created";
158 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -0600159 private static final String ATTR_LAST_LOGGED_IN_FINGERPRINT = "lastLoggedInFingerprint";
Amith Yamasani2a003292012-08-14 18:25:45 -0700160 private static final String ATTR_SERIAL_NO = "serialNumber";
161 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700162 private static final String ATTR_PARTIAL = "partial";
Felipe Lemec1ca4412019-09-11 09:23:26 -0700163 private static final String ATTR_PRE_CREATED = "preCreated";
Adam Lesinskieddeb492014-09-08 17:50:03 -0700164 private static final String ATTR_GUEST_TO_REMOVE = "guestToRemove";
Amith Yamasani6f34b412012-10-22 18:19:27 -0700165 private static final String ATTR_USER_VERSION = "version";
Kenny Guy2a764942014-04-02 13:29:20 +0100166 private static final String ATTR_PROFILE_GROUP_ID = "profileGroupId";
Kenny Guy02c89902016-11-15 19:36:38 +0000167 private static final String ATTR_PROFILE_BADGE = "profileBadge";
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700168 private static final String ATTR_RESTRICTED_PROFILE_PARENT_ID = "restrictedProfileParentId";
Amith Yamasani12747872015-12-07 14:19:49 -0800169 private static final String ATTR_SEED_ACCOUNT_NAME = "seedAccountName";
170 private static final String ATTR_SEED_ACCOUNT_TYPE = "seedAccountType";
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530171 private static final String TAG_GUEST_RESTRICTIONS = "guestRestrictions";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700172 private static final String TAG_USERS = "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700173 private static final String TAG_USER = "user";
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800174 private static final String TAG_RESTRICTIONS = "restrictions";
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800175 private static final String TAG_DEVICE_POLICY_RESTRICTIONS = "device_policy_restrictions";
Pavel Grafov6a40f092016-10-25 15:46:51 +0100176 private static final String TAG_DEVICE_POLICY_GLOBAL_RESTRICTIONS =
177 "device_policy_global_restrictions";
178 /** Legacy name for device owner id tag. */
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +0100179 private static final String TAG_GLOBAL_RESTRICTION_OWNER_ID = "globalRestrictionOwnerUserId";
Pavel Grafov6a40f092016-10-25 15:46:51 +0100180 private static final String TAG_DEVICE_OWNER_USER_ID = "deviceOwnerUserId";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800181 private static final String TAG_ENTRY = "entry";
182 private static final String TAG_VALUE = "value";
Amith Yamasani12747872015-12-07 14:19:49 -0800183 private static final String TAG_SEED_ACCOUNT_OPTIONS = "seedAccountOptions";
arangelov9b632d72018-12-07 23:21:22 +0000184 private static final String TAG_LAST_REQUEST_QUIET_MODE_ENABLED_CALL =
185 "lastRequestQuietModeEnabledCall";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800186 private static final String ATTR_KEY = "key";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700187 private static final String ATTR_VALUE_TYPE = "type";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800188 private static final String ATTR_MULTIPLE = "m";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700189
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700190 private static final String ATTR_TYPE_STRING_ARRAY = "sa";
191 private static final String ATTR_TYPE_STRING = "s";
192 private static final String ATTR_TYPE_BOOLEAN = "b";
Amith Yamasani5b5aa402014-06-01 20:10:14 -0700193 private static final String ATTR_TYPE_INTEGER = "i";
Fyodor Kupolov262f9952015-03-23 18:55:11 -0700194 private static final String ATTR_TYPE_BUNDLE = "B";
195 private static final String ATTR_TYPE_BUNDLE_ARRAY = "BA";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700196
Amith Yamasani0b285492011-04-14 17:35:23 -0700197 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700198 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700199 private static final String USER_PHOTO_FILENAME = "photo.png";
Adrian Roos1bdff912015-02-17 15:51:35 +0100200 private static final String USER_PHOTO_FILENAME_TMP = USER_PHOTO_FILENAME + ".tmp";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700201
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800202 private static final String RESTRICTIONS_FILE_PREFIX = "res_";
Amith Yamasanifc95e702013-09-26 13:20:17 -0700203 private static final String XML_SUFFIX = ".xml";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800204
Sudheer Shankaf5cea032016-06-08 17:13:24 -0700205 private static final int ALLOWED_FLAGS_FOR_CREATE_USERS_PERMISSION =
206 UserInfo.FLAG_MANAGED_PROFILE
207 | UserInfo.FLAG_EPHEMERAL
208 | UserInfo.FLAG_RESTRICTED
Sudheer Shanka234d1af2016-08-26 15:42:53 -0700209 | UserInfo.FLAG_GUEST
210 | UserInfo.FLAG_DEMO;
Sudheer Shankaf5cea032016-06-08 17:13:24 -0700211
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700212 @VisibleForTesting
Makoto Onukiacf38582019-10-04 11:53:42 -0700213 static final int MIN_USER_ID = UserHandle.MIN_SECONDARY_USER_ID;
214
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700215 // We need to keep process uid within Integer.MAX_VALUE.
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700216 @VisibleForTesting
217 static final int MAX_USER_ID = Integer.MAX_VALUE / UserHandle.PER_USER_RANGE;
218
219 // Max size of the queue of recently removed users
220 @VisibleForTesting
221 static final int MAX_RECENTLY_REMOVED_IDS_SIZE = 100;
Amith Yamasani634cf312012-10-04 17:34:21 -0700222
Bookatz75f0a072019-08-05 14:12:16 -0700223 private static final int USER_VERSION = 8;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700224
Amith Yamasani920ace02012-09-20 22:15:37 -0700225 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
226
Nicolas Prevotb8186812015-08-06 15:00:03 +0100227 // Maximum number of managed profiles permitted per user is 1. This cannot be increased
Amith Yamasani95ab7842014-08-11 17:09:26 -0700228 // without first making sure that the rest of the framework is prepared for it.
Kenny Guy02c89902016-11-15 19:36:38 +0000229 @VisibleForTesting
230 static final int MAX_MANAGED_PROFILES = 1;
Amith Yamasani95ab7842014-08-11 17:09:26 -0700231
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800232 static final int WRITE_USER_MSG = 1;
233 static final int WRITE_USER_DELAY = 2*1000; // 2 seconds
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530234
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -0800235 // Tron counters
236 private static final String TRON_GUEST_CREATED = "users_guest_created";
237 private static final String TRON_USER_CREATED = "users_user_created";
Christine Franks88220562017-05-24 11:11:21 -0700238 private static final String TRON_DEMO_CREATED = "users_demo_created";
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -0800239
Dianne Hackborn4428e172012-08-24 17:43:05 -0700240 private final Context mContext;
241 private final PackageManagerService mPm;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700242 private final Object mPackagesLock;
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800243 private final UserDataPreparer mUserDataPreparer;
Fyodor Kupolov82402752015-10-28 14:54:51 -0700244 // Short-term lock for internal state, when interaction/sync with PM is not required
Jeff Sharkey5f3e9342017-03-13 14:53:11 -0600245 private final Object mUsersLock = LockGuard.installNewLock(LockGuard.INDEX_USER);
Fyodor Kupolov82402752015-10-28 14:54:51 -0700246 private final Object mRestrictionsLock = new Object();
Fyodor Kupolovd31cee92017-09-05 16:31:08 -0700247 // Used for serializing access to app restriction files
248 private final Object mAppRestrictionsLock = new Object();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700249
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800250 private final Handler mHandler;
251
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700252 private final File mUsersDir;
253 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700254
Svet Ganov9cea80cd2016-02-16 11:47:00 -0800255 private static final IBinder mUserRestriconToken = new Binder();
256
Bookatz04d7ae52019-08-05 14:07:12 -0700257 /** Installs system packages based on user-type. */
258 private final UserSystemPackageInstaller mSystemPackageInstaller;
259
Makoto Onuki068c54a2015-10-13 14:34:03 -0700260 /**
Makoto Onuki73dded22017-12-20 13:14:48 +0900261 * Internal non-parcelable wrapper for UserInfo that is not exposed to other system apps.
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800262 */
Kenny Guy02c89902016-11-15 19:36:38 +0000263 @VisibleForTesting
264 static class UserData {
Amith Yamasani12747872015-12-07 14:19:49 -0800265 // Basic user information and properties
266 UserInfo info;
267 // Account name used when there is a strong association between a user and an account
268 String account;
269 // Account information for seeding into a newly created user. This could also be
270 // used for login validation for an existing user, for updating their credentials.
271 // In the latter case, data may not need to be persisted as it is only valid for the
272 // current login session.
273 String seedAccountName;
274 String seedAccountType;
275 PersistableBundle seedAccountOptions;
276 // Whether to perist the seed account information to be available after a boot
277 boolean persistSeedData;
278
Makoto Onuki73dded22017-12-20 13:14:48 +0900279 /** Elapsed realtime since boot when the user started. */
280 long startRealtime;
281
282 /** Elapsed realtime since boot when the user was unlocked. */
283 long unlockRealtime;
284
arangelov9b632d72018-12-07 23:21:22 +0000285 private long mLastRequestQuietModeEnabledMillis;
286
287 void setLastRequestQuietModeEnabledMillis(long millis) {
288 mLastRequestQuietModeEnabledMillis = millis;
289 }
290
291 long getLastRequestQuietModeEnabledMillis() {
292 return mLastRequestQuietModeEnabledMillis;
293 }
294
Amith Yamasani12747872015-12-07 14:19:49 -0800295 void clearSeedAccountData() {
296 seedAccountName = null;
297 seedAccountType = null;
298 seedAccountOptions = null;
299 persistSeedData = false;
300 }
301 }
302
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800303 @GuardedBy("mUsersLock")
Amith Yamasani12747872015-12-07 14:19:49 -0800304 private final SparseArray<UserData> mUsers = new SparseArray<>();
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800305
306 /**
Makoto Onuki068c54a2015-10-13 14:34:03 -0700307 * User restrictions set via UserManager. This doesn't include restrictions set by
Pavel Grafov6a40f092016-10-25 15:46:51 +0100308 * device owner / profile owners. Only non-empty restriction bundles are stored.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700309 *
310 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
311 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
312 * maybe shared between {@link #mBaseUserRestrictions} and
313 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
314 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700315 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700316 */
317 @GuardedBy("mRestrictionsLock")
318 private final SparseArray<Bundle> mBaseUserRestrictions = new SparseArray<>();
319
320 /**
321 * Cached user restrictions that are in effect -- i.e. {@link #mBaseUserRestrictions} combined
322 * with device / profile owner restrictions. We'll initialize it lazily; use
323 * {@link #getEffectiveUserRestrictions} to access it.
324 *
325 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
326 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
327 * maybe shared between {@link #mBaseUserRestrictions} and
328 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
329 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700330 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700331 */
332 @GuardedBy("mRestrictionsLock")
333 private final SparseArray<Bundle> mCachedEffectiveUserRestrictions = new SparseArray<>();
334
Makoto Onuki4f160732015-10-27 17:15:38 -0700335 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800336 * User restrictions that have already been applied in
337 * {@link #updateUserRestrictionsInternalLR(Bundle, int)}. We use it to detect restrictions
338 * that have changed since the last
339 * {@link #updateUserRestrictionsInternalLR(Bundle, int)} call.
Makoto Onuki4f160732015-10-27 17:15:38 -0700340 */
341 @GuardedBy("mRestrictionsLock")
342 private final SparseArray<Bundle> mAppliedUserRestrictions = new SparseArray<>();
343
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800344 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800345 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
Pavel Grafov6a40f092016-10-25 15:46:51 +0100346 * that should be applied to all users, including guests. Only non-empty restriction bundles are
347 * stored.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800348 */
349 @GuardedBy("mRestrictionsLock")
Pavel Grafov6a40f092016-10-25 15:46:51 +0100350 private final SparseArray<Bundle> mDevicePolicyGlobalUserRestrictions = new SparseArray<>();
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800351
352 /**
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +0100353 * Id of the user that set global restrictions.
354 */
355 @GuardedBy("mRestrictionsLock")
Pavel Grafov6a40f092016-10-25 15:46:51 +0100356 private int mDeviceOwnerUserId = UserHandle.USER_NULL;
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +0100357
358 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800359 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
Pavel Grafov6a40f092016-10-25 15:46:51 +0100360 * for each user. Only non-empty restriction bundles are stored.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800361 */
362 @GuardedBy("mRestrictionsLock")
363 private final SparseArray<Bundle> mDevicePolicyLocalUserRestrictions = new SparseArray<>();
364
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800365 @GuardedBy("mGuestRestrictions")
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530366 private final Bundle mGuestRestrictions = new Bundle();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800367
368 /**
369 * Set of user IDs being actively removed. Removed IDs linger in this set
370 * for several seconds to work around a VFS caching issue.
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700371 * Use {@link #addRemovingUserIdLocked(int)} to add elements to this array
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800372 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700373 @GuardedBy("mUsersLock")
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800374 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700375
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700376 /**
377 * Queue of recently removed userIds. Used for recycling of userIds
378 */
379 @GuardedBy("mUsersLock")
380 private final LinkedList<Integer> mRecentlyRemovedIds = new LinkedList<>();
381
Fyodor Kupolov82402752015-10-28 14:54:51 -0700382 @GuardedBy("mUsersLock")
Amith Yamasani0b285492011-04-14 17:35:23 -0700383 private int[] mUserIds;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800384 @GuardedBy("mPackagesLock")
Amith Yamasani2a003292012-08-14 18:25:45 -0700385 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700386 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700387
Jason Monk62062992014-05-06 09:55:28 -0400388 private IAppOpsService mAppOpsService;
389
Makoto Onuki068c54a2015-10-13 14:34:03 -0700390 private final LocalService mLocalService;
391
Makoto Onukie7927da2015-11-25 10:05:17 -0800392 @GuardedBy("mUsersLock")
393 private boolean mIsDeviceManaged;
394
395 @GuardedBy("mUsersLock")
396 private final SparseBooleanArray mIsUserManaged = new SparseBooleanArray();
397
Makoto Onukid45a4a22015-11-02 17:17:38 -0800398 @GuardedBy("mUserRestrictionsListeners")
399 private final ArrayList<UserRestrictionsListener> mUserRestrictionsListeners =
400 new ArrayList<>();
401
Clara Bayarria1771112015-12-18 16:29:18 +0000402 private final LockPatternUtils mLockPatternUtils;
403
Ricky Waib1dd80b2016-06-07 18:00:55 +0100404 private final String ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK =
405 "com.android.server.pm.DISABLE_QUIET_MODE_AFTER_UNLOCK";
406
407 private final BroadcastReceiver mDisableQuietModeCallback = new BroadcastReceiver() {
408 @Override
409 public void onReceive(Context context, Intent intent) {
Tony Mak64fd8c02017-12-01 19:11:59 +0000410 if (!ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK.equals(intent.getAction())) {
411 return;
Ricky Waib1dd80b2016-06-07 18:00:55 +0100412 }
Tony Mak64fd8c02017-12-01 19:11:59 +0000413 final IntentSender target = intent.getParcelableExtra(Intent.EXTRA_INTENT);
Bookatzf56f2582019-09-04 16:06:41 -0700414 final int userId = intent.getIntExtra(Intent.EXTRA_USER_ID, UserHandle.USER_NULL);
Fyodor Kupolova68a2862018-01-30 18:22:00 -0800415 // Call setQuietModeEnabled on bg thread to avoid ANR
arangelov9b632d72018-12-07 23:21:22 +0000416 BackgroundThread.getHandler().post(() ->
Bookatzf56f2582019-09-04 16:06:41 -0700417 setQuietModeEnabled(userId, false, target, /* callingPackage */ null));
Ricky Waib1dd80b2016-06-07 18:00:55 +0100418 }
419 };
420
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +0100421 /**
Tony Mak64fd8c02017-12-01 19:11:59 +0000422 * Start an {@link IntentSender} when user is unlocked after disabling quiet mode.
423 *
Tony Makbece85d2018-01-12 12:10:17 +0000424 * @see {@link #requestQuietModeEnabled(String, boolean, int, IntentSender)}
Tony Mak64fd8c02017-12-01 19:11:59 +0000425 */
426 private class DisableQuietModeUserUnlockedCallback extends IProgressListener.Stub {
427 private final IntentSender mTarget;
428
429 public DisableQuietModeUserUnlockedCallback(IntentSender target) {
430 Preconditions.checkNotNull(target);
431 mTarget = target;
432 }
433
434 @Override
435 public void onStarted(int id, Bundle extras) {}
436
437 @Override
438 public void onProgress(int id, int progress, Bundle extras) {}
439
440 @Override
441 public void onFinished(int id, Bundle extras) {
442 try {
443 mContext.startIntentSender(mTarget, null, 0, 0, 0);
444 } catch (IntentSender.SendIntentException e) {
445 Slog.e(LOG_TAG, "Failed to start the target in the callback", e);
446 }
447 }
448 }
449
450 /**
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +0100451 * Whether all users should be created ephemeral.
452 */
453 @GuardedBy("mUsersLock")
454 private boolean mForceEphemeralUsers;
455
Amith Yamasaniea1b9d72016-05-27 15:57:38 +0000456 @GuardedBy("mUserStates")
457 private final SparseIntArray mUserStates = new SparseIntArray();
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -0700458
Amith Yamasani258848d2012-08-10 17:06:33 -0700459 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700460
Dianne Hackborn4428e172012-08-24 17:43:05 -0700461 public static UserManagerService getInstance() {
462 synchronized (UserManagerService.class) {
463 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700464 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700465 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700466
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700467 public static class LifeCycle extends SystemService {
468
469 private UserManagerService mUms;
470
471 /**
472 * @param context
473 */
474 public LifeCycle(Context context) {
475 super(context);
476 }
477
478 @Override
479 public void onStart() {
480 mUms = UserManagerService.getInstance();
481 publishBinderService(Context.USER_SERVICE, mUms);
482 }
483
484 @Override
485 public void onBootPhase(int phase) {
486 if (phase == SystemService.PHASE_ACTIVITY_MANAGER_READY) {
487 mUms.cleanupPartialUsers();
488 }
489 }
Makoto Onuki73dded22017-12-20 13:14:48 +0900490
491 @Override
Bookatzf56f2582019-09-04 16:06:41 -0700492 public void onStartUser(@UserIdInt int userId) {
Makoto Onuki73dded22017-12-20 13:14:48 +0900493 synchronized (mUms.mUsersLock) {
Bookatzf56f2582019-09-04 16:06:41 -0700494 final UserData user = mUms.getUserDataLU(userId);
Makoto Onuki73dded22017-12-20 13:14:48 +0900495 if (user != null) {
496 user.startRealtime = SystemClock.elapsedRealtime();
497 }
498 }
499 }
500
501 @Override
Bookatzf56f2582019-09-04 16:06:41 -0700502 public void onUnlockUser(@UserIdInt int userId) {
Makoto Onuki73dded22017-12-20 13:14:48 +0900503 synchronized (mUms.mUsersLock) {
Bookatzf56f2582019-09-04 16:06:41 -0700504 final UserData user = mUms.getUserDataLU(userId);
Makoto Onuki73dded22017-12-20 13:14:48 +0900505 if (user != null) {
506 user.unlockRealtime = SystemClock.elapsedRealtime();
507 }
508 }
509 }
510
511 @Override
Bookatzf56f2582019-09-04 16:06:41 -0700512 public void onStopUser(@UserIdInt int userId) {
Makoto Onuki73dded22017-12-20 13:14:48 +0900513 synchronized (mUms.mUsersLock) {
Bookatzf56f2582019-09-04 16:06:41 -0700514 final UserData user = mUms.getUserDataLU(userId);
Makoto Onuki73dded22017-12-20 13:14:48 +0900515 if (user != null) {
516 user.startRealtime = 0;
517 user.unlockRealtime = 0;
518 }
519 }
520 }
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700521 }
522
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700523 // TODO b/28848102 Add support for test dependencies injection
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800524 @VisibleForTesting
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700525 UserManagerService(Context context) {
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800526 this(context, null, null, new Object(), context.getCacheDir());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700527 }
528
Dianne Hackborn4428e172012-08-24 17:43:05 -0700529 /**
530 * Called by package manager to create the service. This is closely
531 * associated with the package manager, and the given lock is the
532 * package manager's own lock.
533 */
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800534 UserManagerService(Context context, PackageManagerService pm, UserDataPreparer userDataPreparer,
535 Object packagesLock) {
536 this(context, pm, userDataPreparer, packagesLock, Environment.getDataDirectory());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700537 }
538
Dianne Hackborn4428e172012-08-24 17:43:05 -0700539 private UserManagerService(Context context, PackageManagerService pm,
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800540 UserDataPreparer userDataPreparer, Object packagesLock, File dataDir) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700541 mContext = context;
542 mPm = pm;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700543 mPackagesLock = packagesLock;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800544 mHandler = new MainHandler();
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800545 mUserDataPreparer = userDataPreparer;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800546 synchronized (mPackagesLock) {
547 mUsersDir = new File(dataDir, USER_INFO_DIR);
548 mUsersDir.mkdirs();
549 // Make zeroth user directory, for services to migrate their files to that location
550 File userZeroDir = new File(mUsersDir, String.valueOf(UserHandle.USER_SYSTEM));
551 userZeroDir.mkdirs();
552 FileUtils.setPermissions(mUsersDir.toString(),
553 FileUtils.S_IRWXU | FileUtils.S_IRWXG | FileUtils.S_IROTH | FileUtils.S_IXOTH,
554 -1, -1);
555 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
556 initDefaultGuestRestrictions();
557 readUserListLP();
558 sInstance = this;
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700559 }
Bookatz04d7ae52019-08-05 14:07:12 -0700560 mSystemPackageInstaller = new UserSystemPackageInstaller(this);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700561 mLocalService = new LocalService();
562 LocalServices.addService(UserManagerInternal.class, mLocalService);
Clara Bayarria1771112015-12-18 16:29:18 +0000563 mLockPatternUtils = new LockPatternUtils(mContext);
Amith Yamasaniea1b9d72016-05-27 15:57:38 +0000564 mUserStates.put(UserHandle.USER_SYSTEM, UserState.STATE_BOOTING);
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700565 }
566
567 void systemReady() {
Jason Monk62062992014-05-06 09:55:28 -0400568 mAppOpsService = IAppOpsService.Stub.asInterface(
569 ServiceManager.getService(Context.APP_OPS_SERVICE));
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800570
571 synchronized (mRestrictionsLock) {
572 applyUserRestrictionsLR(UserHandle.USER_SYSTEM);
Jason Monk62062992014-05-06 09:55:28 -0400573 }
Samuel Tand9453b82016-03-14 15:57:02 -0700574
575 UserInfo currentGuestUser = findCurrentGuestUser();
576 if (currentGuestUser != null && !hasUserRestriction(
577 UserManager.DISALLOW_CONFIG_WIFI, currentGuestUser.id)) {
578 // If a guest user currently exists, apply the DISALLOW_CONFIG_WIFI option
579 // to it, in case this guest was created in a previous version where this
580 // user restriction was not a default guest restriction.
581 setUserRestriction(UserManager.DISALLOW_CONFIG_WIFI, true, currentGuestUser.id);
582 }
Amith Yamasanieb437d42016-04-29 09:31:25 -0700583
Ricky Waib1dd80b2016-06-07 18:00:55 +0100584 mContext.registerReceiver(mDisableQuietModeCallback,
585 new IntentFilter(ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK),
586 null, mHandler);
Amith Yamasani258848d2012-08-10 17:06:33 -0700587 }
588
Patrick Baumann6ae7afc2019-07-30 13:11:28 -0700589 /**
590 * This method retrieves the {@link UserManagerInternal} only for the purpose of
591 * PackageManagerService construction.
592 */
593 UserManagerInternal getInternalForInjectorOnly() {
594 return mLocalService;
595 }
596
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700597 void cleanupPartialUsers() {
598 // Prune out any partially created, partially removed and ephemeral users.
599 ArrayList<UserInfo> partials = new ArrayList<>();
600 synchronized (mUsersLock) {
601 final int userSize = mUsers.size();
602 for (int i = 0; i < userSize; i++) {
603 UserInfo ui = mUsers.valueAt(i).info;
Felipe Lemec1ca4412019-09-11 09:23:26 -0700604 if ((ui.partial || ui.guestToRemove || (ui.isEphemeral() && !ui.preCreated))
605 && i != 0) {
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700606 partials.add(ui);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700607 addRemovingUserIdLocked(ui.id);
Amith Yamasaniae261892016-06-27 10:40:09 -0700608 ui.partial = true;
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700609 }
610 }
611 }
612 final int partialsSize = partials.size();
613 for (int i = 0; i < partialsSize; i++) {
614 UserInfo ui = partials.get(i);
615 Slog.w(LOG_TAG, "Removing partially created user " + ui.id
616 + " (name=" + ui.name + ")");
617 removeUserState(ui.id);
618 }
619 }
620
Amith Yamasani258848d2012-08-10 17:06:33 -0700621 @Override
Bookatzf56f2582019-09-04 16:06:41 -0700622 public String getUserAccount(@UserIdInt int userId) {
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800623 checkManageUserAndAcrossUsersFullPermission("get user account");
624 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800625 return mUsers.get(userId).account;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800626 }
627 }
628
629 @Override
Bookatzf56f2582019-09-04 16:06:41 -0700630 public void setUserAccount(@UserIdInt int userId, String accountName) {
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800631 checkManageUserAndAcrossUsersFullPermission("set user account");
Amith Yamasani12747872015-12-07 14:19:49 -0800632 UserData userToUpdate = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800633 synchronized (mPackagesLock) {
634 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800635 final UserData userData = mUsers.get(userId);
636 if (userData == null) {
637 Slog.e(LOG_TAG, "User not found for setting user account: u" + userId);
638 return;
639 }
640 String currentAccount = userData.account;
Narayan Kamath607223f2018-02-19 14:09:02 +0000641 if (!Objects.equals(currentAccount, accountName)) {
Amith Yamasani12747872015-12-07 14:19:49 -0800642 userData.account = accountName;
643 userToUpdate = userData;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800644 }
645 }
646
647 if (userToUpdate != null) {
648 writeUserLP(userToUpdate);
649 }
650 }
651 }
652
653 @Override
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700654 public UserInfo getPrimaryUser() {
655 checkManageUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700656 synchronized (mUsersLock) {
Amith Yamasani515d4062015-09-28 11:30:06 -0700657 final int userSize = mUsers.size();
658 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800659 UserInfo ui = mUsers.valueAt(i).info;
Xiaohui Chend3e9e182015-11-18 13:37:32 -0800660 if (ui.isPrimary() && !mRemovingUserIds.get(ui.id)) {
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700661 return ui;
662 }
663 }
664 }
665 return null;
666 }
667
Xiaohui Chen594f2082015-08-18 11:04:20 -0700668 public @NonNull List<UserInfo> getUsers(boolean excludeDying) {
Felipe Lemec1ca4412019-09-11 09:23:26 -0700669 return getUsers(/*excludePartial= */ true, excludeDying, /* excludePreCreated= */ true);
670 }
671
Felipe Leme09a7f2d2019-10-02 16:27:46 -0700672 @Override
673 public @NonNull List<UserInfo> getUsers(boolean excludePartial, boolean excludeDying,
Felipe Lemec1ca4412019-09-11 09:23:26 -0700674 boolean excludePreCreated) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -0700675 checkManageOrCreateUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700676 synchronized (mUsersLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700677 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasani515d4062015-09-28 11:30:06 -0700678 final int userSize = mUsers.size();
679 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800680 UserInfo ui = mUsers.valueAt(i).info;
Felipe Lemec1ca4412019-09-11 09:23:26 -0700681 if ((excludePartial && ui.partial)
682 || (excludeDying && mRemovingUserIds.get(ui.id))
683 || (excludePreCreated && ui.preCreated)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700684 continue;
685 }
Felipe Lemec1ca4412019-09-11 09:23:26 -0700686 users.add(userWithName(ui));
Amith Yamasani13593602012-03-22 16:16:17 -0700687 }
688 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700689 }
Amith Yamasani13593602012-03-22 16:16:17 -0700690 }
691
Amith Yamasani258848d2012-08-10 17:06:33 -0700692 @Override
Bookatzf56f2582019-09-04 16:06:41 -0700693 public List<UserInfo> getProfiles(@UserIdInt int userId, boolean enabledOnly) {
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700694 boolean returnFullInfo = true;
Amith Yamasani4f582632014-02-19 14:31:52 -0800695 if (userId != UserHandle.getCallingUserId()) {
Sudheer Shanka74680912016-07-29 11:03:37 -0700696 checkManageOrCreateUsersPermission("getting profiles related to user " + userId);
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700697 } else {
698 returnFullInfo = hasManageUsersPermission();
Amith Yamasani4f582632014-02-19 14:31:52 -0800699 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700700 final long ident = Binder.clearCallingIdentity();
701 try {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700702 synchronized (mUsersLock) {
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700703 return getProfilesLU(userId, enabledOnly, returnFullInfo);
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100704 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700705 } finally {
706 Binder.restoreCallingIdentity(ident);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000707 }
708 }
709
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700710 @Override
Bookatzf56f2582019-09-04 16:06:41 -0700711 public int[] getProfileIds(@UserIdInt int userId, boolean enabledOnly) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700712 if (userId != UserHandle.getCallingUserId()) {
bohu12d23a12016-09-26 16:20:07 -0700713 checkManageOrCreateUsersPermission("getting profiles related to user " + userId);
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700714 }
715 final long ident = Binder.clearCallingIdentity();
716 try {
717 synchronized (mUsersLock) {
718 return getProfileIdsLU(userId, enabledOnly).toArray();
719 }
720 } finally {
721 Binder.restoreCallingIdentity(ident);
722 }
723 }
724
Amith Yamasanibe465322014-04-24 13:45:17 -0700725 /** Assume permissions already checked and caller's identity cleared */
Andreas Gampe2e8c7672018-07-20 13:01:08 -0700726 @GuardedBy("mUsersLock")
Bookatzf56f2582019-09-04 16:06:41 -0700727 private List<UserInfo> getProfilesLU(@UserIdInt int userId, boolean enabledOnly,
728 boolean fullInfo) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700729 IntArray profileIds = getProfileIdsLU(userId, enabledOnly);
730 ArrayList<UserInfo> users = new ArrayList<>(profileIds.size());
731 for (int i = 0; i < profileIds.size(); i++) {
732 int profileId = profileIds.get(i);
733 UserInfo userInfo = mUsers.get(profileId).info;
734 // If full info is not required - clear PII data to prevent 3P apps from reading it
735 if (!fullInfo) {
736 userInfo = new UserInfo(userInfo);
737 userInfo.name = null;
738 userInfo.iconPath = null;
739 } else {
740 userInfo = userWithName(userInfo);
741 }
742 users.add(userInfo);
743 }
744 return users;
745 }
746
747 /**
748 * Assume permissions already checked and caller's identity cleared
749 */
Andreas Gampe2e8c7672018-07-20 13:01:08 -0700750 @GuardedBy("mUsersLock")
Bookatzf56f2582019-09-04 16:06:41 -0700751 private IntArray getProfileIdsLU(@UserIdInt int userId, boolean enabledOnly) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700752 UserInfo user = getUserInfoLU(userId);
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700753 IntArray result = new IntArray(mUsers.size());
Amith Yamasanidda003f2014-08-28 18:06:51 -0700754 if (user == null) {
755 // Probably a dying user
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700756 return result;
Amith Yamasanidda003f2014-08-28 18:06:51 -0700757 }
Amith Yamasani515d4062015-09-28 11:30:06 -0700758 final int userSize = mUsers.size();
759 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800760 UserInfo profile = mUsers.valueAt(i).info;
Amith Yamasanibe465322014-04-24 13:45:17 -0700761 if (!isProfileOf(user, profile)) {
762 continue;
763 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100764 if (enabledOnly && !profile.isEnabled()) {
765 continue;
Amith Yamasanibe465322014-04-24 13:45:17 -0700766 }
Amith Yamasani70fcf0c2014-07-11 08:40:19 -0700767 if (mRemovingUserIds.get(profile.id)) {
768 continue;
769 }
Tony Mak80189cd2016-04-05 17:21:42 +0100770 if (profile.partial) {
771 continue;
772 }
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700773 result.add(profile.id);
Amith Yamasanibe465322014-04-24 13:45:17 -0700774 }
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700775 return result;
Amith Yamasanibe465322014-04-24 13:45:17 -0700776 }
777
Jessica Hummelbe81c802014-04-22 15:49:22 +0100778 @Override
Bookatzf56f2582019-09-04 16:06:41 -0700779 public int getCredentialOwnerProfile(@UserIdInt int userId) {
Andres Moralesc5548c02015-08-05 10:23:12 -0700780 checkManageUsersPermission("get the credential owner");
Bookatzf56f2582019-09-04 16:06:41 -0700781 if (!mLockPatternUtils.isSeparateProfileChallengeEnabled(userId)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700782 synchronized (mUsersLock) {
Bookatzf56f2582019-09-04 16:06:41 -0700783 UserInfo profileParent = getProfileParentLU(userId);
Andres Moralesc5548c02015-08-05 10:23:12 -0700784 if (profileParent != null) {
785 return profileParent.id;
786 }
787 }
788 }
789
Bookatzf56f2582019-09-04 16:06:41 -0700790 return userId;
Andres Moralesc5548c02015-08-05 10:23:12 -0700791 }
792
793 @Override
Bookatzf56f2582019-09-04 16:06:41 -0700794 public boolean isSameProfileGroup(@UserIdInt int userId, int otherUserId) {
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700795 if (userId == otherUserId) return true;
796 checkManageUsersPermission("check if in the same profile group");
Fyodor Kupolov0fb772e2016-10-13 16:27:34 -0700797 return isSameProfileGroupNoChecks(userId, otherUserId);
798 }
799
Bookatzf56f2582019-09-04 16:06:41 -0700800 private boolean isSameProfileGroupNoChecks(@UserIdInt int userId, int otherUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700801 synchronized (mUsersLock) {
802 UserInfo userInfo = getUserInfoLU(userId);
803 if (userInfo == null || userInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
804 return false;
805 }
806 UserInfo otherUserInfo = getUserInfoLU(otherUserId);
807 if (otherUserInfo == null
808 || otherUserInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
809 return false;
810 }
811 return userInfo.profileGroupId == otherUserInfo.profileGroupId;
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700812 }
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700813 }
814
815 @Override
Bookatzf56f2582019-09-04 16:06:41 -0700816 public UserInfo getProfileParent(@UserIdInt int userId) {
Jessica Hummelbe81c802014-04-22 15:49:22 +0100817 checkManageUsersPermission("get the profile parent");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700818 synchronized (mUsersLock) {
Bookatzf56f2582019-09-04 16:06:41 -0700819 return getProfileParentLU(userId);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700820 }
821 }
822
Jakub Pawlowski0f1f5b72017-11-15 14:50:43 -0800823 @Override
Bookatzf56f2582019-09-04 16:06:41 -0700824 public int getProfileParentId(@UserIdInt int userId) {
Jakub Pawlowski0f1f5b72017-11-15 14:50:43 -0800825 checkManageUsersPermission("get the profile parent");
Bookatzf56f2582019-09-04 16:06:41 -0700826 return mLocalService.getProfileParentId(userId);
Jakub Pawlowski0f1f5b72017-11-15 14:50:43 -0800827 }
828
Andreas Gampe2e8c7672018-07-20 13:01:08 -0700829 @GuardedBy("mUsersLock")
Bookatzf56f2582019-09-04 16:06:41 -0700830 private UserInfo getProfileParentLU(@UserIdInt int userId) {
831 UserInfo profile = getUserInfoLU(userId);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700832 if (profile == null) {
833 return null;
834 }
835 int parentUserId = profile.profileGroupId;
Bookatzf56f2582019-09-04 16:06:41 -0700836 if (parentUserId == userId || parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700837 return null;
838 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700839 return getUserInfoLU(parentUserId);
Jessica Hummelbe81c802014-04-22 15:49:22 +0100840 }
841 }
842
Fyodor Kupolov82402752015-10-28 14:54:51 -0700843 private static boolean isProfileOf(UserInfo user, UserInfo profile) {
Kenny Guy2a764942014-04-02 13:29:20 +0100844 return user.id == profile.id ||
845 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
846 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000847 }
848
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000849 private void broadcastProfileAvailabilityChanges(UserHandle profileHandle,
Rubin Xuf13c9802016-01-21 18:06:00 +0000850 UserHandle parentHandle, boolean inQuietMode) {
Rubin Xue95057a2016-04-01 16:49:25 +0100851 Intent intent = new Intent();
852 if (inQuietMode) {
853 intent.setAction(Intent.ACTION_MANAGED_PROFILE_UNAVAILABLE);
854 } else {
855 intent.setAction(Intent.ACTION_MANAGED_PROFILE_AVAILABLE);
856 }
Rubin Xuf13c9802016-01-21 18:06:00 +0000857 intent.putExtra(Intent.EXTRA_QUIET_MODE, inQuietMode);
858 intent.putExtra(Intent.EXTRA_USER, profileHandle);
859 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileHandle.getIdentifier());
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000860 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Rubin Xuf13c9802016-01-21 18:06:00 +0000861 mContext.sendBroadcastAsUser(intent, parentHandle);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000862 }
863
864 @Override
Tony Makbece85d2018-01-12 12:10:17 +0000865 public boolean requestQuietModeEnabled(@NonNull String callingPackage, boolean enableQuietMode,
Bookatzf56f2582019-09-04 16:06:41 -0700866 @UserIdInt int userId, @Nullable IntentSender target) {
Tony Make3d1f652017-12-12 11:00:37 +0000867 Preconditions.checkNotNull(callingPackage);
868
Tony Makb7e6fd42017-12-05 19:40:28 +0000869 if (enableQuietMode && target != null) {
870 throw new IllegalArgumentException(
871 "target should only be specified when we are disabling quiet mode.");
872 }
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000873
Bookatz3cb67df2019-10-16 17:20:06 -0400874 ensureCanModifyQuietMode(callingPackage, Binder.getCallingUid(), userId, target != null);
Tony Makb7e6fd42017-12-05 19:40:28 +0000875 final long identity = Binder.clearCallingIdentity();
876 try {
arangelov9b632d72018-12-07 23:21:22 +0000877 boolean result = false;
Tony Makb7e6fd42017-12-05 19:40:28 +0000878 if (enableQuietMode) {
arangelov9b632d72018-12-07 23:21:22 +0000879 setQuietModeEnabled(
Bookatzf56f2582019-09-04 16:06:41 -0700880 userId, true /* enableQuietMode */, target, callingPackage);
arangelov9b632d72018-12-07 23:21:22 +0000881 result = true;
Tony Makb7e6fd42017-12-05 19:40:28 +0000882 } else {
883 boolean needToShowConfirmCredential =
Bookatzf56f2582019-09-04 16:06:41 -0700884 mLockPatternUtils.isSecure(userId)
885 && !StorageManager.isUserKeyUnlocked(userId);
Tony Makb7e6fd42017-12-05 19:40:28 +0000886 if (needToShowConfirmCredential) {
Bookatzf56f2582019-09-04 16:06:41 -0700887 showConfirmCredentialToDisableQuietMode(userId, target);
Tony Makb7e6fd42017-12-05 19:40:28 +0000888 } else {
arangelov9b632d72018-12-07 23:21:22 +0000889 setQuietModeEnabled(
Bookatzf56f2582019-09-04 16:06:41 -0700890 userId, false /* enableQuietMode */, target, callingPackage);
arangelov9b632d72018-12-07 23:21:22 +0000891 result = true;
Tony Makb7e6fd42017-12-05 19:40:28 +0000892 }
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000893 }
arangelov9b632d72018-12-07 23:21:22 +0000894 return result;
Tony Makb7e6fd42017-12-05 19:40:28 +0000895 } finally {
896 Binder.restoreCallingIdentity(identity);
897 }
898 }
899
Tony Make3d1f652017-12-12 11:00:37 +0000900 /**
Tony Makd390ae92017-12-28 13:23:10 +0000901 * The caller can modify quiet mode if it meets one of these conditions:
Tony Make3d1f652017-12-12 11:00:37 +0000902 * <ul>
903 * <li>Has system UID or root UID</li>
904 * <li>Has {@link Manifest.permission#MODIFY_QUIET_MODE}</li>
905 * <li>Has {@link Manifest.permission#MANAGE_USERS}</li>
Bookatz3cb67df2019-10-16 17:20:06 -0400906 * <li>Is the foreground default launcher app</li>
Tony Make3d1f652017-12-12 11:00:37 +0000907 * </ul>
Tony Makd390ae92017-12-28 13:23:10 +0000908 * <p>
Bookatz3cb67df2019-10-16 17:20:06 -0400909 * If caller wants to start an intent after disabling the quiet mode, or if it is targeting a
910 * user in a different profile group from the caller, it must have
Tony Makd390ae92017-12-28 13:23:10 +0000911 * {@link Manifest.permission#MANAGE_USERS}.
Tony Make3d1f652017-12-12 11:00:37 +0000912 */
Tony Makd390ae92017-12-28 13:23:10 +0000913 private void ensureCanModifyQuietMode(String callingPackage, int callingUid,
Bookatz3cb67df2019-10-16 17:20:06 -0400914 @UserIdInt int targetUserId, boolean startIntent) {
Tony Make3d1f652017-12-12 11:00:37 +0000915 if (hasManageUsersPermission()) {
Tony Makd390ae92017-12-28 13:23:10 +0000916 return;
Tony Make3d1f652017-12-12 11:00:37 +0000917 }
Tony Makd390ae92017-12-28 13:23:10 +0000918 if (startIntent) {
919 throw new SecurityException("MANAGE_USERS permission is required to start intent "
920 + "after disabling quiet mode.");
921 }
Bookatz3cb67df2019-10-16 17:20:06 -0400922 if (!isSameProfileGroupNoChecks(UserHandle.getUserId(callingUid), targetUserId)) {
923 throw new SecurityException("MANAGE_USERS permission is required to modify quiet mode "
924 + "for a different profile group.");
925 }
jovanakf24ad492018-05-18 12:15:59 -0700926 final boolean hasModifyQuietModePermission = hasPermissionGranted(
927 Manifest.permission.MODIFY_QUIET_MODE, callingUid);
Tony Make3d1f652017-12-12 11:00:37 +0000928 if (hasModifyQuietModePermission) {
Tony Makd390ae92017-12-28 13:23:10 +0000929 return;
Tony Make3d1f652017-12-12 11:00:37 +0000930 }
931
Tony Makd390ae92017-12-28 13:23:10 +0000932 verifyCallingPackage(callingPackage, callingUid);
Tony Make3d1f652017-12-12 11:00:37 +0000933 final ShortcutServiceInternal shortcutInternal =
934 LocalServices.getService(ShortcutServiceInternal.class);
935 if (shortcutInternal != null) {
936 boolean isForegroundLauncher =
937 shortcutInternal.isForegroundDefaultLauncher(callingPackage, callingUid);
938 if (isForegroundLauncher) {
Tony Makd390ae92017-12-28 13:23:10 +0000939 return;
Tony Make3d1f652017-12-12 11:00:37 +0000940 }
941 }
Tony Makd390ae92017-12-28 13:23:10 +0000942 throw new SecurityException("Can't modify quiet mode, caller is neither foreground "
943 + "default launcher nor has MANAGE_USERS/MODIFY_QUIET_MODE permission");
Tony Make3d1f652017-12-12 11:00:37 +0000944 }
945
Bookatzf56f2582019-09-04 16:06:41 -0700946 private void setQuietModeEnabled(@UserIdInt int userId, boolean enableQuietMode,
arangelov9b632d72018-12-07 23:21:22 +0000947 IntentSender target, @Nullable String callingPackage) {
Tony Makb7e6fd42017-12-05 19:40:28 +0000948 final UserInfo profile, parent;
949 final UserData profileUserData;
950 synchronized (mUsersLock) {
Bookatzf56f2582019-09-04 16:06:41 -0700951 profile = getUserInfoLU(userId);
952 parent = getProfileParentLU(userId);
Tony Makb7e6fd42017-12-05 19:40:28 +0000953
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000954 if (profile == null || !profile.isManagedProfile()) {
Bookatzf56f2582019-09-04 16:06:41 -0700955 throw new IllegalArgumentException("User " + userId + " is not a profile");
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000956 }
Tony Makb7e6fd42017-12-05 19:40:28 +0000957 if (profile.isQuietModeEnabled() == enableQuietMode) {
958 Slog.i(LOG_TAG, "Quiet mode is already " + enableQuietMode);
959 return;
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000960 }
Tony Makb7e6fd42017-12-05 19:40:28 +0000961 profile.flags ^= UserInfo.FLAG_QUIET_MODE;
962 profileUserData = getUserDataLU(profile.id);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000963 }
Tony Makb7e6fd42017-12-05 19:40:28 +0000964 synchronized (mPackagesLock) {
965 writeUserLP(profileUserData);
966 }
967 try {
968 if (enableQuietMode) {
Bookatzf56f2582019-09-04 16:06:41 -0700969 ActivityManager.getService().stopUser(userId, /* force */true, null);
Tony Makb7e6fd42017-12-05 19:40:28 +0000970 LocalServices.getService(ActivityManagerInternal.class)
Bookatzf56f2582019-09-04 16:06:41 -0700971 .killForegroundAppsForUser(userId);
Tony Makb7e6fd42017-12-05 19:40:28 +0000972 } else {
973 IProgressListener callback = target != null
974 ? new DisableQuietModeUserUnlockedCallback(target)
975 : null;
976 ActivityManager.getService().startUserInBackgroundWithListener(
Bookatzf56f2582019-09-04 16:06:41 -0700977 userId, callback);
Rubin Xuf13c9802016-01-21 18:06:00 +0000978 }
Bookatzf56f2582019-09-04 16:06:41 -0700979 logQuietModeEnabled(userId, enableQuietMode, callingPackage);
Tony Makb7e6fd42017-12-05 19:40:28 +0000980 } catch (RemoteException e) {
981 // Should not happen, same process.
982 e.rethrowAsRuntimeException();
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000983 }
Tony Makb7e6fd42017-12-05 19:40:28 +0000984 broadcastProfileAvailabilityChanges(profile.getUserHandle(), parent.getUserHandle(),
985 enableQuietMode);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000986 }
987
Bookatzf56f2582019-09-04 16:06:41 -0700988 private void logQuietModeEnabled(@UserIdInt int userId, boolean enableQuietMode,
arangelov9b632d72018-12-07 23:21:22 +0000989 @Nullable String callingPackage) {
990 UserData userData;
991 synchronized (mUsersLock) {
Bookatzf56f2582019-09-04 16:06:41 -0700992 userData = getUserDataLU(userId);
arangelov9b632d72018-12-07 23:21:22 +0000993 }
994 if (userData == null) {
995 return;
996 }
997 final long now = System.currentTimeMillis();
998 final long period = (userData.getLastRequestQuietModeEnabledMillis() != 0L
999 ? now - userData.getLastRequestQuietModeEnabledMillis()
1000 : now - userData.info.creationTime);
1001 DevicePolicyEventLogger
1002 .createEvent(DevicePolicyEnums.REQUEST_QUIET_MODE_ENABLED)
1003 .setStrings(callingPackage)
1004 .setBoolean(enableQuietMode)
1005 .setTimePeriod(period)
1006 .write();
1007 userData.setLastRequestQuietModeEnabledMillis(now);
1008 }
1009
Rubin Xu0a29ecd2015-11-04 15:11:48 +00001010 @Override
Bookatzf56f2582019-09-04 16:06:41 -07001011 public boolean isQuietModeEnabled(@UserIdInt int userId) {
Rubin Xu0a29ecd2015-11-04 15:11:48 +00001012 synchronized (mPackagesLock) {
1013 UserInfo info;
1014 synchronized (mUsersLock) {
Bookatzf56f2582019-09-04 16:06:41 -07001015 info = getUserInfoLU(userId);
Rubin Xu0a29ecd2015-11-04 15:11:48 +00001016 }
1017 if (info == null || !info.isManagedProfile()) {
Rubin Xuf13c9802016-01-21 18:06:00 +00001018 return false;
Rubin Xu0a29ecd2015-11-04 15:11:48 +00001019 }
1020 return info.isQuietModeEnabled();
1021 }
1022 }
1023
Tony Makb7e6fd42017-12-05 19:40:28 +00001024 /**
1025 * Show confirm credential screen to unlock user in order to turn off quiet mode.
1026 */
1027 private void showConfirmCredentialToDisableQuietMode(
Bookatzf56f2582019-09-04 16:06:41 -07001028 @UserIdInt int userId, @Nullable IntentSender target) {
Tony Makb7e6fd42017-12-05 19:40:28 +00001029 // otherwise, we show a profile challenge to trigger decryption of the user
1030 final KeyguardManager km = (KeyguardManager) mContext.getSystemService(
1031 Context.KEYGUARD_SERVICE);
Bookatzf56f2582019-09-04 16:06:41 -07001032 // We should use userId not credentialOwnerUserId here, as even if it is unified
Tony Makb7e6fd42017-12-05 19:40:28 +00001033 // lock, confirm screenlock page will know and show personal challenge, and unlock
1034 // work profile when personal challenge is correct
Bookatzf56f2582019-09-04 16:06:41 -07001035 final Intent unlockIntent = km.createConfirmDeviceCredentialIntent(null, null, userId);
Tony Makb7e6fd42017-12-05 19:40:28 +00001036 if (unlockIntent == null) {
1037 return;
Benjamin Franzf02420c2016-04-04 18:52:21 +01001038 }
Tony Makb7e6fd42017-12-05 19:40:28 +00001039 final Intent callBackIntent = new Intent(
1040 ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK);
1041 if (target != null) {
1042 callBackIntent.putExtra(Intent.EXTRA_INTENT, target);
Benjamin Franzf02420c2016-04-04 18:52:21 +01001043 }
Bookatzf56f2582019-09-04 16:06:41 -07001044 callBackIntent.putExtra(Intent.EXTRA_USER_ID, userId);
Tony Makb7e6fd42017-12-05 19:40:28 +00001045 callBackIntent.setPackage(mContext.getPackageName());
1046 callBackIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1047 final PendingIntent pendingIntent = PendingIntent.getBroadcast(
1048 mContext,
1049 0,
1050 callBackIntent,
1051 PendingIntent.FLAG_CANCEL_CURRENT |
1052 PendingIntent.FLAG_ONE_SHOT |
1053 PendingIntent.FLAG_IMMUTABLE);
1054 // After unlocking the challenge, it will disable quiet mode and run the original
1055 // intentSender
1056 unlockIntent.putExtra(Intent.EXTRA_INTENT, pendingIntent.getIntentSender());
1057 unlockIntent.setFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
1058 mContext.startActivity(unlockIntent);
Benjamin Franzf02420c2016-04-04 18:52:21 +01001059 }
1060
1061 @Override
Bookatzf56f2582019-09-04 16:06:41 -07001062 public void setUserEnabled(@UserIdInt int userId) {
Alexandra Gherghinadf35d572014-04-09 13:54:39 +01001063 checkManageUsersPermission("enable user");
1064 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001065 UserInfo info;
1066 synchronized (mUsersLock) {
1067 info = getUserInfoLU(userId);
1068 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +01001069 if (info != null && !info.isEnabled()) {
1070 info.flags ^= UserInfo.FLAG_DISABLED;
Amith Yamasani12747872015-12-07 14:19:49 -08001071 writeUserLP(getUserDataLU(info.id));
Alexandra Gherghinadf35d572014-04-09 13:54:39 +01001072 }
1073 }
1074 }
1075
jovanakf24ad492018-05-18 12:15:59 -07001076 @Override
Bookatzf56f2582019-09-04 16:06:41 -07001077 public void setUserAdmin(@UserIdInt int userId) {
jovanakf24ad492018-05-18 12:15:59 -07001078 checkManageUserAndAcrossUsersFullPermission("set user admin");
1079
1080 synchronized (mPackagesLock) {
1081 UserInfo info;
1082 synchronized (mUsersLock) {
1083 info = getUserInfoLU(userId);
1084 }
1085 if (info == null || info.isAdmin()) {
1086 // Exit if no user found with that id, or the user is already an Admin.
1087 return;
1088 }
1089
1090 info.flags ^= UserInfo.FLAG_ADMIN;
1091 writeUserLP(getUserDataLU(info.id));
1092 }
1093
1094 // Remove non-admin restrictions.
1095 // Keep synchronized with createUserEvenWhenDisallowed.
1096 setUserRestriction(UserManager.DISALLOW_SMS, false, userId);
1097 setUserRestriction(UserManager.DISALLOW_OUTGOING_CALLS, false, userId);
1098 }
1099
Andrew Scull85a63bc2016-10-24 13:47:47 +01001100 /**
1101 * Evicts a user's CE key by stopping and restarting the user.
1102 *
1103 * The key is evicted automatically by the user controller when the user has stopped.
1104 */
1105 @Override
1106 public void evictCredentialEncryptionKey(@UserIdInt int userId) {
1107 checkManageUsersPermission("evict CE key");
1108 final IActivityManager am = ActivityManagerNative.getDefault();
1109 final long identity = Binder.clearCallingIdentity();
1110 try {
1111 am.restartUserInBackground(userId);
1112 } catch (RemoteException re) {
1113 throw re.rethrowAsRuntimeException();
1114 } finally {
1115 Binder.restoreCallingIdentity(identity);
1116 }
1117 }
1118
Alexandra Gherghinadf35d572014-04-09 13:54:39 +01001119 @Override
Bookatzf56f2582019-09-04 16:06:41 -07001120 public UserInfo getUserInfo(@UserIdInt int userId) {
Sudheer Shankaaccaa082016-06-14 16:22:57 -07001121 checkManageOrCreateUsersPermission("query user");
Tony Mak8673b282016-03-21 21:10:59 +00001122 synchronized (mUsersLock) {
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001123 return userWithName(getUserInfoLU(userId));
1124 }
1125 }
1126
1127 /**
1128 * Returns a UserInfo object with the name filled in, for Owner, or the original
1129 * if the name is already set.
1130 */
1131 private UserInfo userWithName(UserInfo orig) {
1132 if (orig != null && orig.name == null && orig.id == UserHandle.USER_SYSTEM) {
1133 UserInfo withName = new UserInfo(orig);
1134 withName.name = getOwnerName();
1135 return withName;
1136 } else {
1137 return orig;
Tony Mak8673b282016-03-21 21:10:59 +00001138 }
1139 }
1140
1141 @Override
Kenny Guy02c89902016-11-15 19:36:38 +00001142 public int getManagedProfileBadge(@UserIdInt int userId) {
Jon Miranda2b340a22019-01-25 14:03:49 -08001143 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "getManagedProfileBadge");
Kenny Guy02c89902016-11-15 19:36:38 +00001144 synchronized (mUsersLock) {
1145 UserInfo userInfo = getUserInfoLU(userId);
1146 return userInfo != null ? userInfo.profileBadge : 0;
1147 }
1148 }
1149
1150 @Override
Bookatzf56f2582019-09-04 16:06:41 -07001151 public boolean isManagedProfile(@UserIdInt int userId) {
Jon Miranda2b340a22019-01-25 14:03:49 -08001152 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isManagedProfile");
Fyodor Kupolov82402752015-10-28 14:54:51 -07001153 synchronized (mUsersLock) {
Amith Yamasani1c41dc82016-06-28 16:13:15 -07001154 UserInfo userInfo = getUserInfoLU(userId);
Tony Mak8673b282016-03-21 21:10:59 +00001155 return userInfo != null && userInfo.isManagedProfile();
Amith Yamasani13593602012-03-22 16:16:17 -07001156 }
1157 }
1158
Amith Yamasani71e6c692013-03-24 17:39:28 -07001159 @Override
Bookatzf56f2582019-09-04 16:06:41 -07001160 public boolean isUserUnlockingOrUnlocked(@UserIdInt int userId) {
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08001161 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isUserUnlockingOrUnlocked");
Fyodor Kupolovc413f702016-10-06 17:11:14 -07001162 return mLocalService.isUserUnlockingOrUnlocked(userId);
1163 }
1164
1165 @Override
Bookatzf56f2582019-09-04 16:06:41 -07001166 public boolean isUserUnlocked(@UserIdInt int userId) {
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08001167 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isUserUnlocked");
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07001168 return mLocalService.isUserUnlocked(userId);
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08001169 }
1170
1171 @Override
Bookatzf56f2582019-09-04 16:06:41 -07001172 public boolean isUserRunning(@UserIdInt int userId) {
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08001173 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isUserRunning");
1174 return mLocalService.isUserRunning(userId);
1175 }
1176
Makoto Onuki73dded22017-12-20 13:14:48 +09001177 @Override
Bookatzcde3d922019-03-08 14:30:00 -08001178 public String getUserName() {
1179 if (!hasManageUsersOrPermission(android.Manifest.permission.GET_ACCOUNTS_PRIVILEGED)) {
1180 throw new SecurityException("You need MANAGE_USERS or GET_ACCOUNTS_PRIVILEGED "
1181 + "permissions to: get user name");
1182 }
1183 final int userId = UserHandle.getUserId(Binder.getCallingUid());
1184 synchronized (mUsersLock) {
1185 UserInfo userInfo = userWithName(getUserInfoLU(userId));
1186 return userInfo == null ? "" : userInfo.name;
1187 }
1188 }
1189
1190 @Override
Makoto Onuki73dded22017-12-20 13:14:48 +09001191 public long getUserStartRealtime() {
1192 final int userId = UserHandle.getUserId(Binder.getCallingUid());
1193 synchronized (mUsersLock) {
1194 final UserData user = getUserDataLU(userId);
1195 if (user != null) {
1196 return user.startRealtime;
1197 }
1198 return 0;
1199 }
1200 }
1201
1202 @Override
1203 public long getUserUnlockRealtime() {
1204 synchronized (mUsersLock) {
1205 final UserData user = getUserDataLU(UserHandle.getUserId(Binder.getCallingUid()));
1206 if (user != null) {
1207 return user.unlockRealtime;
1208 }
1209 return 0;
1210 }
1211 }
1212
Bookatzf56f2582019-09-04 16:06:41 -07001213 private void checkManageOrInteractPermIfCallerInOtherProfileGroup(@UserIdInt int userId,
1214 String name) {
Felipe Lemec1ca4412019-09-11 09:23:26 -07001215 final int callingUserId = UserHandle.getCallingUserId();
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08001216 if (callingUserId == userId || isSameProfileGroupNoChecks(callingUserId, userId) ||
1217 hasManageUsersPermission()) {
1218 return;
1219 }
jovanakf24ad492018-05-18 12:15:59 -07001220 if (!hasPermissionGranted(Manifest.permission.INTERACT_ACROSS_USERS,
1221 Binder.getCallingUid())) {
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08001222 throw new SecurityException("You need INTERACT_ACROSS_USERS or MANAGE_USERS permission "
1223 + "to: check " + name);
1224 }
1225 }
1226
1227 @Override
Bookatzf56f2582019-09-04 16:06:41 -07001228 public boolean isDemoUser(@UserIdInt int userId) {
Felipe Lemec1ca4412019-09-11 09:23:26 -07001229 final int callingUserId = UserHandle.getCallingUserId();
Amith Yamasani1c41dc82016-06-28 16:13:15 -07001230 if (callingUserId != userId && !hasManageUsersPermission()) {
1231 throw new SecurityException("You need MANAGE_USERS permission to query if u=" + userId
1232 + " is a demo user");
1233 }
1234 synchronized (mUsersLock) {
1235 UserInfo userInfo = getUserInfoLU(userId);
1236 return userInfo != null && userInfo.isDemo();
1237 }
1238 }
1239
1240 @Override
Felipe Lemec1ca4412019-09-11 09:23:26 -07001241 public boolean isPreCreated(@UserIdInt int userId) {
1242 final int callingUserId = UserHandle.getCallingUserId();
1243 if (callingUserId != userId && !hasManageUsersPermission()) {
1244 throw new SecurityException("You need MANAGE_USERS permission to query if u=" + userId
1245 + " is pre-created");
1246 }
1247 synchronized (mUsersLock) {
1248 UserInfo userInfo = getUserInfoLU(userId);
1249 return userInfo != null && userInfo.preCreated;
1250 }
1251 }
1252
1253 @Override
Amith Yamasani71e6c692013-03-24 17:39:28 -07001254 public boolean isRestricted() {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001255 synchronized (mUsersLock) {
1256 return getUserInfoLU(UserHandle.getCallingUserId()).isRestricted();
Amith Yamasani71e6c692013-03-24 17:39:28 -07001257 }
1258 }
1259
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001260 @Override
Bookatzf56f2582019-09-04 16:06:41 -07001261 public boolean canHaveRestrictedProfile(@UserIdInt int userId) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001262 checkManageUsersPermission("canHaveRestrictedProfile");
Fyodor Kupolov82402752015-10-28 14:54:51 -07001263 synchronized (mUsersLock) {
1264 final UserInfo userInfo = getUserInfoLU(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001265 if (userInfo == null || !userInfo.canHaveProfile()) {
1266 return false;
1267 }
1268 if (!userInfo.isAdmin()) {
1269 return false;
1270 }
Makoto Onukie7927da2015-11-25 10:05:17 -08001271 // restricted profile can be created if there is no DO set and the admin user has no PO;
1272 return !mIsDeviceManaged && !mIsUserManaged.get(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001273 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001274 }
1275
Fyodor Kupolovca177562017-11-09 17:43:01 -08001276 @Override
1277 public boolean hasRestrictedProfiles() {
1278 checkManageUsersPermission("hasRestrictedProfiles");
1279 final int callingUserId = UserHandle.getCallingUserId();
1280 synchronized (mUsersLock) {
1281 final int userSize = mUsers.size();
1282 for (int i = 0; i < userSize; i++) {
1283 UserInfo profile = mUsers.valueAt(i).info;
1284 if (callingUserId != profile.id
1285 && profile.restrictedProfileParentId == callingUserId) {
1286 return true;
1287 }
1288 }
1289 return false;
1290 }
1291 }
1292
Amith Yamasani195263742012-08-21 15:40:12 -07001293 /*
1294 * Should be locked on mUsers before calling this.
1295 */
Andreas Gampe2e8c7672018-07-20 13:01:08 -07001296 @GuardedBy("mUsersLock")
Bookatzf56f2582019-09-04 16:06:41 -07001297 private UserInfo getUserInfoLU(@UserIdInt int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -08001298 final UserData userData = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -07001299 // If it is partial and not in the process of being removed, return as unknown user.
Amith Yamasani12747872015-12-07 14:19:49 -08001300 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001301 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
1302 return null;
1303 }
Amith Yamasani12747872015-12-07 14:19:49 -08001304 return userData != null ? userData.info : null;
1305 }
1306
Andreas Gampe2e8c7672018-07-20 13:01:08 -07001307 @GuardedBy("mUsersLock")
Bookatzf56f2582019-09-04 16:06:41 -07001308 private UserData getUserDataLU(@UserIdInt int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -08001309 final UserData userData = mUsers.get(userId);
1310 // If it is partial and not in the process of being removed, return as unknown user.
1311 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
1312 return null;
1313 }
1314 return userData;
Amith Yamasani195263742012-08-21 15:40:12 -07001315 }
1316
Fyodor Kupolov82402752015-10-28 14:54:51 -07001317 /**
1318 * Obtains {@link #mUsersLock} and return UserInfo from mUsers.
1319 * <p>No permissions checking or any addition checks are made</p>
1320 */
Bookatzf56f2582019-09-04 16:06:41 -07001321 private UserInfo getUserInfoNoChecks(@UserIdInt int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001322 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001323 final UserData userData = mUsers.get(userId);
1324 return userData != null ? userData.info : null;
1325 }
1326 }
1327
1328 /**
1329 * Obtains {@link #mUsersLock} and return UserData from mUsers.
1330 * <p>No permissions checking or any addition checks are made</p>
1331 */
Bookatzf56f2582019-09-04 16:06:41 -07001332 private UserData getUserDataNoChecks(@UserIdInt int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -08001333 synchronized (mUsersLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001334 return mUsers.get(userId);
1335 }
1336 }
1337
Amith Yamasani236b2b52015-08-18 14:32:14 -07001338 /** Called by PackageManagerService */
Bookatzf56f2582019-09-04 16:06:41 -07001339 public boolean exists(@UserIdInt int userId) {
Todd Kennedy0eb97382017-10-03 16:57:22 -07001340 return mLocalService.exists(userId);
Amith Yamasani13593602012-03-22 16:16:17 -07001341 }
1342
Amith Yamasani258848d2012-08-10 17:06:33 -07001343 @Override
Bookatzf56f2582019-09-04 16:06:41 -07001344 public void setUserName(@UserIdInt int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001345 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001346 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -07001347 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001348 UserData userData = getUserDataNoChecks(userId);
1349 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001350 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
1351 return;
1352 }
Amith Yamasani12747872015-12-07 14:19:49 -08001353 if (name != null && !name.equals(userData.info.name)) {
1354 userData.info.name = name;
1355 writeUserLP(userData);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001356 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -07001357 }
1358 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001359 if (changed) {
Bookatzf9368552019-03-14 11:57:09 -07001360 long ident = Binder.clearCallingIdentity();
1361 try {
1362 sendUserInfoChangedBroadcast(userId);
1363 } finally {
1364 Binder.restoreCallingIdentity(ident);
1365 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001366 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001367 }
1368
Amith Yamasani258848d2012-08-10 17:06:33 -07001369 @Override
Bookatzf56f2582019-09-04 16:06:41 -07001370 public void setUserIcon(@UserIdInt int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001371 checkManageUsersPermission("update users");
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01001372 if (hasUserRestriction(UserManager.DISALLOW_SET_USER_ICON, userId)) {
1373 Log.w(LOG_TAG, "Cannot set user icon. DISALLOW_SET_USER_ICON is enabled.");
1374 return;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001375 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01001376 mLocalService.setUserIcon(userId, bitmap);
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001377 }
1378
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01001379
1380
Bookatzf56f2582019-09-04 16:06:41 -07001381 private void sendUserInfoChangedBroadcast(@UserIdInt int userId) {
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001382 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
1383 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
1384 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -07001385 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001386 }
1387
Amith Yamasani258848d2012-08-10 17:06:33 -07001388 @Override
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001389 public ParcelFileDescriptor getUserIcon(int targetUserId) {
Bookatzcde3d922019-03-08 14:30:00 -08001390 if (!hasManageUsersOrPermission(android.Manifest.permission.GET_ACCOUNTS_PRIVILEGED)) {
1391 throw new SecurityException("You need MANAGE_USERS or GET_ACCOUNTS_PRIVILEGED "
1392 + "permissions to: get user icon");
1393 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001394 String iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001395 synchronized (mPackagesLock) {
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001396 UserInfo targetUserInfo = getUserInfoNoChecks(targetUserId);
1397 if (targetUserInfo == null || targetUserInfo.partial) {
1398 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + targetUserId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001399 return null;
1400 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001401
1402 final int callingUserId = UserHandle.getCallingUserId();
1403 final int callingGroupId = getUserInfoNoChecks(callingUserId).profileGroupId;
1404 final int targetGroupId = targetUserInfo.profileGroupId;
1405 final boolean sameGroup = (callingGroupId != UserInfo.NO_PROFILE_GROUP_ID
1406 && callingGroupId == targetGroupId);
1407 if ((callingUserId != targetUserId) && !sameGroup) {
Nicolas Prevot88cc3462014-05-14 14:51:48 +01001408 checkManageUsersPermission("get the icon of a user who is not related");
1409 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001410
1411 if (targetUserInfo.iconPath == null) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001412 return null;
1413 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001414 iconPath = targetUserInfo.iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001415 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001416
1417 try {
1418 return ParcelFileDescriptor.open(
1419 new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
1420 } catch (FileNotFoundException e) {
1421 Log.e(LOG_TAG, "Couldn't find icon file", e);
1422 }
1423 return null;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001424 }
1425
Bookatzf56f2582019-09-04 16:06:41 -07001426 public void makeInitialized(@UserIdInt int userId) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001427 checkManageUsersPermission("makeInitialized");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001428 boolean scheduleWriteUser = false;
Amith Yamasani12747872015-12-07 14:19:49 -08001429 UserData userData;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001430 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001431 userData = mUsers.get(userId);
1432 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001433 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001434 return;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001435 }
Amith Yamasani12747872015-12-07 14:19:49 -08001436 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1437 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001438 scheduleWriteUser = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001439 }
1440 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001441 if (scheduleWriteUser) {
Amith Yamasani12747872015-12-07 14:19:49 -08001442 scheduleWriteUser(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001443 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001444 }
1445
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001446 /**
1447 * If default guest restrictions haven't been initialized yet, add the basic
1448 * restrictions.
1449 */
1450 private void initDefaultGuestRestrictions() {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001451 synchronized (mGuestRestrictions) {
1452 if (mGuestRestrictions.isEmpty()) {
Samuel Tand9453b82016-03-14 15:57:02 -07001453 mGuestRestrictions.putBoolean(UserManager.DISALLOW_CONFIG_WIFI, true);
Fyodor Kupolove04462c2015-11-30 15:02:53 -08001454 mGuestRestrictions.putBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, true);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001455 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
1456 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
1457 }
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001458 }
1459 }
1460
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001461 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301462 public Bundle getDefaultGuestRestrictions() {
1463 checkManageUsersPermission("getDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001464 synchronized (mGuestRestrictions) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301465 return new Bundle(mGuestRestrictions);
1466 }
1467 }
1468
1469 @Override
1470 public void setDefaultGuestRestrictions(Bundle restrictions) {
1471 checkManageUsersPermission("setDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001472 synchronized (mGuestRestrictions) {
1473 mGuestRestrictions.clear();
1474 mGuestRestrictions.putAll(restrictions);
1475 }
1476 synchronized (mPackagesLock) {
1477 writeUserListLP();
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301478 }
1479 }
1480
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001481 /**
Pavel Grafov6a40f092016-10-25 15:46:51 +01001482 * See {@link UserManagerInternal#setDevicePolicyUserRestrictions}
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001483 */
Bookatzf56f2582019-09-04 16:06:41 -07001484 private void setDevicePolicyUserRestrictionsInner(@UserIdInt int userId,
1485 @Nullable Bundle restrictions, boolean isDeviceOwner, int cameraRestrictionScope) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001486 final Bundle global = new Bundle();
1487 final Bundle local = new Bundle();
1488
1489 // Sort restrictions into local and global ensuring they don't overlap.
1490 UserRestrictionsUtils.sortToGlobalAndLocal(restrictions, isDeviceOwner,
1491 cameraRestrictionScope, global, local);
1492
1493 boolean globalChanged, localChanged;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001494 synchronized (mRestrictionsLock) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001495 // Update global and local restrictions if they were changed.
1496 globalChanged = updateRestrictionsIfNeededLR(
1497 userId, global, mDevicePolicyGlobalUserRestrictions);
1498 localChanged = updateRestrictionsIfNeededLR(
1499 userId, local, mDevicePolicyLocalUserRestrictions);
1500
1501 if (isDeviceOwner) {
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001502 // Remember the global restriction owner userId to be able to make a distinction
1503 // in getUserRestrictionSource on who set local policies.
Pavel Grafov6a40f092016-10-25 15:46:51 +01001504 mDeviceOwnerUserId = userId;
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001505 } else {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001506 if (mDeviceOwnerUserId == userId) {
Zoltan Szatmary-Ban8a5536d2016-05-27 17:56:44 +01001507 // When profile owner sets restrictions it passes null global bundle and we
1508 // reset global restriction owner userId.
1509 // This means this user used to have DO, but now the DO is gone and the user
1510 // instead has PO.
Pavel Grafov6a40f092016-10-25 15:46:51 +01001511 mDeviceOwnerUserId = UserHandle.USER_NULL;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001512 }
1513 }
1514 }
1515 if (DBG) {
1516 Log.d(LOG_TAG, "setDevicePolicyUserRestrictions: userId=" + userId
1517 + " global=" + global + (globalChanged ? " (changed)" : "")
1518 + " local=" + local + (localChanged ? " (changed)" : "")
1519 );
1520 }
1521 // Don't call them within the mRestrictionsLock.
1522 synchronized (mPackagesLock) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001523 if (localChanged || globalChanged) {
Amith Yamasani12747872015-12-07 14:19:49 -08001524 writeUserLP(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001525 }
1526 }
1527
1528 synchronized (mRestrictionsLock) {
1529 if (globalChanged) {
1530 applyUserRestrictionsForAllUsersLR();
1531 } else if (localChanged) {
1532 applyUserRestrictionsLR(userId);
1533 }
1534 }
1535 }
1536
Pavel Grafov6a40f092016-10-25 15:46:51 +01001537 /**
1538 * Updates restriction bundle for a given user in a given restriction array. If new bundle is
1539 * empty, record is removed from the array.
1540 * @return whether restrictions bundle is different from the old one.
1541 */
Bookatzf56f2582019-09-04 16:06:41 -07001542 private boolean updateRestrictionsIfNeededLR(@UserIdInt int userId,
1543 @Nullable Bundle restrictions, SparseArray<Bundle> restrictionsArray) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001544 final boolean changed =
1545 !UserRestrictionsUtils.areEqual(restrictionsArray.get(userId), restrictions);
1546 if (changed) {
1547 if (!UserRestrictionsUtils.isEmpty(restrictions)) {
1548 restrictionsArray.put(userId, restrictions);
1549 } else {
1550 restrictionsArray.delete(userId);
1551 }
1552 }
1553 return changed;
1554 }
1555
Makoto Onuki068c54a2015-10-13 14:34:03 -07001556 @GuardedBy("mRestrictionsLock")
Bookatzf56f2582019-09-04 16:06:41 -07001557 private Bundle computeEffectiveUserRestrictionsLR(@UserIdInt int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001558 final Bundle baseRestrictions =
1559 UserRestrictionsUtils.nonNull(mBaseUserRestrictions.get(userId));
Pavel Grafov6a40f092016-10-25 15:46:51 +01001560 final Bundle global = UserRestrictionsUtils.mergeAll(mDevicePolicyGlobalUserRestrictions);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001561 final Bundle local = mDevicePolicyLocalUserRestrictions.get(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001562
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001563 if (UserRestrictionsUtils.isEmpty(global) && UserRestrictionsUtils.isEmpty(local)) {
1564 // Common case first.
1565 return baseRestrictions;
Makoto Onuki068c54a2015-10-13 14:34:03 -07001566 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001567 final Bundle effective = UserRestrictionsUtils.clone(baseRestrictions);
1568 UserRestrictionsUtils.merge(effective, global);
1569 UserRestrictionsUtils.merge(effective, local);
1570
Makoto Onuki068c54a2015-10-13 14:34:03 -07001571 return effective;
1572 }
1573
1574 @GuardedBy("mRestrictionsLock")
Bookatzf56f2582019-09-04 16:06:41 -07001575 private void invalidateEffectiveUserRestrictionsLR(@UserIdInt int userId) {
Makoto Onuki068c54a2015-10-13 14:34:03 -07001576 if (DBG) {
1577 Log.d(LOG_TAG, "invalidateEffectiveUserRestrictions userId=" + userId);
1578 }
1579 mCachedEffectiveUserRestrictions.remove(userId);
1580 }
1581
Bookatzf56f2582019-09-04 16:06:41 -07001582 private Bundle getEffectiveUserRestrictions(@UserIdInt int userId) {
Makoto Onuki068c54a2015-10-13 14:34:03 -07001583 synchronized (mRestrictionsLock) {
1584 Bundle restrictions = mCachedEffectiveUserRestrictions.get(userId);
1585 if (restrictions == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001586 restrictions = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001587 mCachedEffectiveUserRestrictions.put(userId, restrictions);
1588 }
1589 return restrictions;
Amith Yamasani8cd28b52014-06-08 17:54:27 -07001590 }
1591 }
1592
Makoto Onuki068c54a2015-10-13 14:34:03 -07001593 /** @return a specific user restriction that's in effect currently. */
1594 @Override
Bookatzf56f2582019-09-04 16:06:41 -07001595 public boolean hasUserRestriction(String restrictionKey, @UserIdInt int userId) {
Patrick Baumann2f2fd712019-07-31 15:18:53 -07001596 return mLocalService.hasUserRestriction(restrictionKey, userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001597 }
1598
Makoto Onukiacc50462018-02-14 14:13:49 -08001599 /** @return if any user has the given restriction. */
1600 @Override
1601 public boolean hasUserRestrictionOnAnyUser(String restrictionKey) {
1602 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1603 return false;
1604 }
1605 final List<UserInfo> users = getUsers(/* excludeDying= */ true);
1606 for (int i = 0; i < users.size(); i++) {
1607 final int userId = users.get(i).id;
1608 Bundle restrictions = getEffectiveUserRestrictions(userId);
1609 if (restrictions != null && restrictions.getBoolean(restrictionKey)) {
1610 return true;
1611 }
1612 }
1613 return false;
1614 }
1615
Christopher Tate65fb2e42019-10-11 17:00:23 -07001616 @Override
1617 public boolean isSettingRestrictedForUser(String setting, @UserIdInt int userId,
1618 String value, int callingUid) {
1619 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
1620 throw new SecurityException("Non-system caller");
1621 }
1622 return UserRestrictionsUtils.isSettingRestrictedForUser(mContext, setting, userId,
1623 value, callingUid);
1624 }
1625
1626 @Override
1627 public void addUserRestrictionsListener(final IUserRestrictionsListener listener) {
1628 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
1629 throw new SecurityException("Non-system caller");
1630 }
1631
1632 // NOTE: unregistering not supported; only client is the settings provider,
1633 // which installs a single static permanent listener. If that listener goes
1634 // bad it implies the whole system process is going to crash.
1635 mLocalService.addUserRestrictionsListener(
1636 (int userId, Bundle newRestrict, Bundle prevRestrict) -> {
1637 try {
1638 listener.onUserRestrictionsChanged(userId, newRestrict, prevRestrict);
1639 } catch (RemoteException re) {
1640 Slog.e("IUserRestrictionsListener",
1641 "Unable to invoke listener: " + re.getMessage());
1642 }
1643 });
1644 }
1645
Makoto Onuki068c54a2015-10-13 14:34:03 -07001646 /**
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001647 * @hide
1648 *
1649 * Returns who set a user restriction on a user.
1650 * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
1651 * @param restrictionKey the string key representing the restriction
1652 * @param userId the id of the user for whom to retrieve the restrictions.
1653 * @return The source of user restriction. Any combination of
1654 * {@link UserManager#RESTRICTION_NOT_SET},
1655 * {@link UserManager#RESTRICTION_SOURCE_SYSTEM},
1656 * {@link UserManager#RESTRICTION_SOURCE_DEVICE_OWNER}
1657 * and {@link UserManager#RESTRICTION_SOURCE_PROFILE_OWNER}
1658 */
1659 @Override
Bookatzf56f2582019-09-04 16:06:41 -07001660 public int getUserRestrictionSource(String restrictionKey, @UserIdInt int userId) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001661 List<EnforcingUser> enforcingUsers = getUserRestrictionSources(restrictionKey, userId);
1662 // Get "bitwise or" of restriction sources for all enforcing users.
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001663 int result = UserManager.RESTRICTION_NOT_SET;
Pavel Grafov6a40f092016-10-25 15:46:51 +01001664 for (int i = enforcingUsers.size() - 1; i >= 0; i--) {
1665 result |= enforcingUsers.get(i).getUserRestrictionSource();
1666 }
1667 return result;
1668 }
1669
1670 @Override
1671 public List<EnforcingUser> getUserRestrictionSources(
1672 String restrictionKey, @UserIdInt int userId) {
1673 checkManageUsersPermission("getUserRestrictionSource");
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001674
1675 // Shortcut for the most common case
1676 if (!hasUserRestriction(restrictionKey, userId)) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001677 return Collections.emptyList();
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001678 }
1679
Pavel Grafov6a40f092016-10-25 15:46:51 +01001680 final List<EnforcingUser> result = new ArrayList<>();
1681
1682 // Check if it is base restriction.
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001683 if (hasBaseUserRestriction(restrictionKey, userId)) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001684 result.add(new EnforcingUser(
1685 UserHandle.USER_NULL, UserManager.RESTRICTION_SOURCE_SYSTEM));
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001686 }
1687
Pavel Grafov6a40f092016-10-25 15:46:51 +01001688 synchronized (mRestrictionsLock) {
1689 // Check if it is set by profile owner.
1690 Bundle profileOwnerRestrictions = mDevicePolicyLocalUserRestrictions.get(userId);
1691 if (UserRestrictionsUtils.contains(profileOwnerRestrictions, restrictionKey)) {
1692 result.add(getEnforcingUserLocked(userId));
1693 }
1694
1695 // Iterate over all users who enforce global restrictions.
1696 for (int i = mDevicePolicyGlobalUserRestrictions.size() - 1; i >= 0; i--) {
1697 Bundle globalRestrictions = mDevicePolicyGlobalUserRestrictions.valueAt(i);
1698 int profileUserId = mDevicePolicyGlobalUserRestrictions.keyAt(i);
1699 if (UserRestrictionsUtils.contains(globalRestrictions, restrictionKey)) {
1700 result.add(getEnforcingUserLocked(profileUserId));
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001701 }
1702 }
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001703 }
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001704 return result;
1705 }
1706
Andreas Gampea36dc622018-02-05 17:19:22 -08001707 @GuardedBy("mRestrictionsLock")
Pavel Grafov6a40f092016-10-25 15:46:51 +01001708 private EnforcingUser getEnforcingUserLocked(@UserIdInt int userId) {
1709 int source = mDeviceOwnerUserId == userId ? UserManager.RESTRICTION_SOURCE_DEVICE_OWNER
1710 : UserManager.RESTRICTION_SOURCE_PROFILE_OWNER;
1711 return new EnforcingUser(userId, source);
1712 }
1713
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001714 /**
Makoto Onuki068c54a2015-10-13 14:34:03 -07001715 * @return UserRestrictions that are in effect currently. This always returns a new
1716 * {@link Bundle}.
1717 */
Amith Yamasani8cd28b52014-06-08 17:54:27 -07001718 @Override
Bookatzf56f2582019-09-04 16:06:41 -07001719 public Bundle getUserRestrictions(@UserIdInt int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001720 return UserRestrictionsUtils.clone(getEffectiveUserRestrictions(userId));
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001721 }
1722
1723 @Override
Bookatzf56f2582019-09-04 16:06:41 -07001724 public boolean hasBaseUserRestriction(String restrictionKey, @UserIdInt int userId) {
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +00001725 checkManageUsersPermission("hasBaseUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001726 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1727 return false;
1728 }
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +00001729 synchronized (mRestrictionsLock) {
1730 Bundle bundle = mBaseUserRestrictions.get(userId);
1731 return (bundle != null && bundle.getBoolean(restrictionKey, false));
1732 }
1733 }
1734
1735 @Override
Bookatzf56f2582019-09-04 16:06:41 -07001736 public void setUserRestriction(String key, boolean value, @UserIdInt int userId) {
Fyodor Kupolovd4b26042015-07-27 14:30:59 -07001737 checkManageUsersPermission("setUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001738 if (!UserRestrictionsUtils.isValidRestriction(key)) {
1739 return;
1740 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001741 synchronized (mRestrictionsLock) {
1742 // Note we can't modify Bundles stored in mBaseUserRestrictions directly, so create
1743 // a copy.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001744 final Bundle newRestrictions = UserRestrictionsUtils.clone(
1745 mBaseUserRestrictions.get(userId));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001746 newRestrictions.putBoolean(key, value);
1747
Fyodor Kupolov82402752015-10-28 14:54:51 -07001748 updateUserRestrictionsInternalLR(newRestrictions, userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001749 }
1750 }
1751
Makoto Onuki068c54a2015-10-13 14:34:03 -07001752 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001753 * Optionally updating user restrictions, calculate the effective user restrictions and also
1754 * propagate to other services and system settings.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001755 *
Pavel Grafov6a40f092016-10-25 15:46:51 +01001756 * @param newBaseRestrictions User restrictions to set.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001757 * If null, will not update user restrictions and only does the propagation.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001758 * @param userId target user ID.
1759 */
1760 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001761 private void updateUserRestrictionsInternalLR(
Bookatzf56f2582019-09-04 16:06:41 -07001762 @Nullable Bundle newBaseRestrictions, @UserIdInt int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001763 final Bundle prevAppliedRestrictions = UserRestrictionsUtils.nonNull(
1764 mAppliedUserRestrictions.get(userId));
1765
1766 // Update base restrictions.
Pavel Grafov6a40f092016-10-25 15:46:51 +01001767 if (newBaseRestrictions != null) {
1768 // If newBaseRestrictions == the current one, it's probably a bug.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001769 final Bundle prevBaseRestrictions = mBaseUserRestrictions.get(userId);
1770
Pavel Grafov6a40f092016-10-25 15:46:51 +01001771 Preconditions.checkState(prevBaseRestrictions != newBaseRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001772 Preconditions.checkState(mCachedEffectiveUserRestrictions.get(userId)
Pavel Grafov6a40f092016-10-25 15:46:51 +01001773 != newBaseRestrictions);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001774
Pavel Grafov6a40f092016-10-25 15:46:51 +01001775 if (updateRestrictionsIfNeededLR(userId, newBaseRestrictions, mBaseUserRestrictions)) {
Amith Yamasani12747872015-12-07 14:19:49 -08001776 scheduleWriteUser(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001777 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001778 }
1779
Fyodor Kupolov82402752015-10-28 14:54:51 -07001780 final Bundle effective = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001781
Makoto Onuki759a7632015-10-28 16:43:10 -07001782 mCachedEffectiveUserRestrictions.put(userId, effective);
1783
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001784 // Apply the new restrictions.
Makoto Onuki4f160732015-10-27 17:15:38 -07001785 if (DBG) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001786 debug("Applying user restrictions: userId=" + userId
1787 + " new=" + effective + " prev=" + prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001788 }
1789
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001790 if (mAppOpsService != null) { // We skip it until system-ready.
Fyodor Kupolovec30ca32016-06-16 15:09:29 -07001791 mHandler.post(new Runnable() {
1792 @Override
1793 public void run() {
1794 try {
1795 mAppOpsService.setUserRestrictions(effective, mUserRestriconToken, userId);
1796 } catch (RemoteException e) {
1797 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
1798 }
1799 }
1800 });
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001801 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001802
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001803 propagateUserRestrictionsLR(userId, effective, prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001804
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001805 mAppliedUserRestrictions.put(userId, new Bundle(effective));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001806 }
1807
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001808 private void propagateUserRestrictionsLR(final int userId,
Makoto Onukid45a4a22015-11-02 17:17:38 -08001809 Bundle newRestrictions, Bundle prevRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001810 // Note this method doesn't touch any state, meaning it doesn't require mRestrictionsLock
1811 // actually, but we still need some kind of synchronization otherwise we might end up
1812 // calling listeners out-of-order, thus "LR".
1813
1814 if (UserRestrictionsUtils.areEqual(newRestrictions, prevRestrictions)) {
1815 return;
1816 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08001817
1818 final Bundle newRestrictionsFinal = new Bundle(newRestrictions);
1819 final Bundle prevRestrictionsFinal = new Bundle(prevRestrictions);
1820
1821 mHandler.post(new Runnable() {
1822 @Override
1823 public void run() {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07001824 UserRestrictionsUtils.applyUserRestrictions(
1825 mContext, userId, newRestrictionsFinal, prevRestrictionsFinal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001826
Makoto Onukid45a4a22015-11-02 17:17:38 -08001827 final UserRestrictionsListener[] listeners;
1828 synchronized (mUserRestrictionsListeners) {
1829 listeners = new UserRestrictionsListener[mUserRestrictionsListeners.size()];
1830 mUserRestrictionsListeners.toArray(listeners);
1831 }
1832 for (int i = 0; i < listeners.length; i++) {
1833 listeners[i].onUserRestrictionsChanged(userId,
1834 newRestrictionsFinal, prevRestrictionsFinal);
1835 }
Makoto Onukie72f81b2017-03-16 14:08:19 -07001836
1837 final Intent broadcast = new Intent(UserManager.ACTION_USER_RESTRICTIONS_CHANGED)
1838 .setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
1839 mContext.sendBroadcastAsUser(broadcast, UserHandle.of(userId));
Makoto Onukid45a4a22015-11-02 17:17:38 -08001840 }
1841 });
1842 }
1843
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001844 // Package private for the inner class.
Andreas Gampe2e8c7672018-07-20 13:01:08 -07001845 @GuardedBy("mRestrictionsLock")
Bookatzf56f2582019-09-04 16:06:41 -07001846 void applyUserRestrictionsLR(@UserIdInt int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001847 updateUserRestrictionsInternalLR(null, userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001848 }
1849
1850 @GuardedBy("mRestrictionsLock")
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001851 // Package private for the inner class.
1852 void applyUserRestrictionsForAllUsersLR() {
1853 if (DBG) {
1854 debug("applyUserRestrictionsForAllUsersLR");
1855 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001856 // First, invalidate all cached values.
Makoto Onuki4f160732015-10-27 17:15:38 -07001857 mCachedEffectiveUserRestrictions.clear();
1858
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001859 // We don't want to call into ActivityManagerService while taking a lock, so we'll call
Makoto Onuki068c54a2015-10-13 14:34:03 -07001860 // it on a handler.
1861 final Runnable r = new Runnable() {
1862 @Override
1863 public void run() {
1864 // Then get the list of running users.
1865 final int[] runningUsers;
1866 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001867 runningUsers = ActivityManager.getService().getRunningUserIds();
Makoto Onuki068c54a2015-10-13 14:34:03 -07001868 } catch (RemoteException e) {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001869 Log.w(LOG_TAG, "Unable to access ActivityManagerService");
Makoto Onuki068c54a2015-10-13 14:34:03 -07001870 return;
1871 }
1872 // Then re-calculate the effective restrictions and apply, only for running users.
1873 // It's okay if a new user has started after the getRunningUserIds() call,
1874 // because we'll do the same thing (re-calculate the restrictions and apply)
1875 // when we start a user.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001876 synchronized (mRestrictionsLock) {
1877 for (int i = 0; i < runningUsers.length; i++) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001878 applyUserRestrictionsLR(runningUsers[i]);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001879 }
1880 }
1881 }
1882 };
1883 mHandler.post(r);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001884 }
1885
Amith Yamasani258848d2012-08-10 17:06:33 -07001886 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001887 * Check if we've hit the limit of how many users can be created.
1888 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001889 private boolean isUserLimitReached() {
1890 int count;
1891 synchronized (mUsersLock) {
1892 count = getAliveUsersExcludingGuestsCountLU();
1893 }
1894 return count >= UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001895 }
1896
1897 @Override
Bookatzf56f2582019-09-04 16:06:41 -07001898 public boolean canAddMoreManagedProfiles(@UserIdInt int userId, boolean allowedToRemoveOne) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001899 checkManageUsersPermission("check if more managed profiles can be added.");
1900 if (ActivityManager.isLowRamDeviceStatic()) {
1901 return false;
1902 }
Fyodor Kupolovb6157992015-06-05 15:32:28 -07001903 if (!mContext.getPackageManager().hasSystemFeature(
1904 PackageManager.FEATURE_MANAGED_USERS)) {
1905 return false;
1906 }
Nicolas Prevotb8186812015-08-06 15:00:03 +01001907 // Limit number of managed profiles that can be created
Benjamin Franzc8776152017-01-06 14:16:41 +00001908 final int managedProfilesCount = getProfiles(userId, false).size() - 1;
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001909 final int profilesRemovedCount = managedProfilesCount > 0 && allowedToRemoveOne ? 1 : 0;
Kenny Guy02c89902016-11-15 19:36:38 +00001910 if (managedProfilesCount - profilesRemovedCount >= getMaxManagedProfiles()) {
Nicolas Prevotb8186812015-08-06 15:00:03 +01001911 return false;
1912 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001913 synchronized(mUsersLock) {
1914 UserInfo userInfo = getUserInfoLU(userId);
yuanhao47f9f7c2017-01-18 09:54:45 +08001915 if (userInfo == null || !userInfo.canHaveProfile()) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001916 return false;
1917 }
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001918 int usersCountAfterRemoving = getAliveUsersExcludingGuestsCountLU()
1919 - profilesRemovedCount;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001920 // We allow creating a managed profile in the special case where there is only one user.
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001921 return usersCountAfterRemoving == 1
1922 || usersCountAfterRemoving < UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001923 }
1924 }
1925
Andreas Gampe2e8c7672018-07-20 13:01:08 -07001926 @GuardedBy("mUsersLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001927 private int getAliveUsersExcludingGuestsCountLU() {
Amith Yamasanif584f012014-05-19 17:57:25 -07001928 int aliveUserCount = 0;
1929 final int totalUserCount = mUsers.size();
1930 // Skip over users being removed
1931 for (int i = 0; i < totalUserCount; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001932 UserInfo user = mUsers.valueAt(i).info;
Felipe Lemec1ca4412019-09-11 09:23:26 -07001933 if (!mRemovingUserIds.get(user.id) && !user.isGuest() && !user.preCreated) {
Amith Yamasanif584f012014-05-19 17:57:25 -07001934 aliveUserCount++;
1935 }
1936 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001937 return aliveUserCount;
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001938 }
1939
1940 /**
Amith Yamasani195263742012-08-21 15:40:12 -07001941 * Enforces that only the system UID or root's UID or apps that have the
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001942 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} and
1943 * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL INTERACT_ACROSS_USERS_FULL}
1944 * permissions can make certain calls to the UserManager.
1945 *
1946 * @param message used as message if SecurityException is thrown
1947 * @throws SecurityException if the caller does not have enough privilege.
1948 */
1949 private static final void checkManageUserAndAcrossUsersFullPermission(String message) {
1950 final int uid = Binder.getCallingUid();
jovanakf24ad492018-05-18 12:15:59 -07001951
1952 if (uid == Process.SYSTEM_UID || uid == 0) {
1953 // System UID or root's UID are granted privilege.
1954 return;
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001955 }
jovanakf24ad492018-05-18 12:15:59 -07001956
1957 if (hasPermissionGranted(Manifest.permission.MANAGE_USERS, uid)
1958 && hasPermissionGranted(Manifest.permission.INTERACT_ACROSS_USERS_FULL, uid)) {
1959 // Apps with both permissions are granted privilege.
1960 return;
1961 }
1962
1963 throw new SecurityException(
1964 "You need MANAGE_USERS and INTERACT_ACROSS_USERS_FULL permission to: " + message);
1965 }
1966
1967 private static boolean hasPermissionGranted(String permission, int uid) {
1968 return ActivityManager.checkComponentPermission(
1969 permission, uid, /* owningUid = */-1, /* exported = */ true) ==
1970 PackageManager.PERMISSION_GRANTED;
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001971 }
1972
1973 /**
1974 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001975 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -07001976 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -07001977 *
1978 * @param message used as message if SecurityException is thrown
1979 * @throws SecurityException if the caller is not system or root
Tony Mak4dc008c2016-03-16 10:46:49 +00001980 * @see #hasManageUsersPermission()
Amith Yamasani258848d2012-08-10 17:06:33 -07001981 */
Amith Yamasanibe465322014-04-24 13:45:17 -07001982 private static final void checkManageUsersPermission(String message) {
Tony Mak4dc008c2016-03-16 10:46:49 +00001983 if (!hasManageUsersPermission()) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001984 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
1985 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -04001986 }
1987
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001988 /**
Sudheer Shankaf5cea032016-06-08 17:13:24 -07001989 * Enforces that only the system UID or root's UID or apps that have the
1990 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or
1991 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS}
1992 * can make certain calls to the UserManager.
1993 *
1994 * @param message used as message if SecurityException is thrown
1995 * @throws SecurityException if the caller is not system or root
1996 * @see #hasManageOrCreateUsersPermission()
1997 */
1998 private static final void checkManageOrCreateUsersPermission(String message) {
1999 if (!hasManageOrCreateUsersPermission()) {
2000 throw new SecurityException(
2001 "You either need MANAGE_USERS or CREATE_USERS permission to: " + message);
2002 }
2003 }
2004
2005 /**
2006 * Similar to {@link #checkManageOrCreateUsersPermission(String)} but when the caller is tries
2007 * to create user/profiles other than what is allowed for
2008 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS} permission, then it will only
2009 * allow callers with {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} permission.
2010 */
2011 private static final void checkManageOrCreateUsersPermission(int creationFlags) {
2012 if ((creationFlags & ~ALLOWED_FLAGS_FOR_CREATE_USERS_PERMISSION) == 0) {
2013 if (!hasManageOrCreateUsersPermission()) {
2014 throw new SecurityException("You either need MANAGE_USERS or CREATE_USERS "
2015 + "permission to create an user with flags: " + creationFlags);
2016 }
2017 } else if (!hasManageUsersPermission()) {
2018 throw new SecurityException("You need MANAGE_USERS permission to create an user "
2019 + " with flags: " + creationFlags);
2020 }
2021 }
2022
2023 /**
Tony Mak4dc008c2016-03-16 10:46:49 +00002024 * @return whether the calling UID is system UID or root's UID or the calling app has the
2025 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}.
2026 */
2027 private static final boolean hasManageUsersPermission() {
2028 final int callingUid = Binder.getCallingUid();
2029 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
2030 || callingUid == Process.ROOT_UID
jovanakf24ad492018-05-18 12:15:59 -07002031 || hasPermissionGranted(android.Manifest.permission.MANAGE_USERS, callingUid);
Tony Mak4dc008c2016-03-16 10:46:49 +00002032 }
2033
2034 /**
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002035 * @return whether the calling UID is system UID or root's UID or the calling app has the
Bookatzcde3d922019-03-08 14:30:00 -08002036 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or the provided permission.
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002037 */
Bookatzcde3d922019-03-08 14:30:00 -08002038 private static final boolean hasManageUsersOrPermission(String alternativePermission) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002039 final int callingUid = Binder.getCallingUid();
2040 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
2041 || callingUid == Process.ROOT_UID
jovanakf24ad492018-05-18 12:15:59 -07002042 || hasPermissionGranted(android.Manifest.permission.MANAGE_USERS, callingUid)
Bookatzcde3d922019-03-08 14:30:00 -08002043 || hasPermissionGranted(alternativePermission, callingUid);
2044 }
2045
2046 /**
2047 * @return whether the calling UID is system UID or root's UID or the calling app has the
2048 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or
2049 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS}.
2050 */
2051 private static final boolean hasManageOrCreateUsersPermission() {
2052 return hasManageUsersOrPermission(android.Manifest.permission.CREATE_USERS);
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002053 }
2054
2055 /**
Esteban Talavera5b9f1672015-12-11 15:22:34 +00002056 * Enforces that only the system UID or root's UID (on any user) can make certain calls to the
2057 * UserManager.
2058 *
2059 * @param message used as message if SecurityException is thrown
2060 * @throws SecurityException if the caller is not system or root
2061 */
2062 private static void checkSystemOrRoot(String message) {
2063 final int uid = Binder.getCallingUid();
2064 if (!UserHandle.isSameApp(uid, Process.SYSTEM_UID) && uid != Process.ROOT_UID) {
2065 throw new SecurityException("Only system may: " + message);
2066 }
2067 }
2068
Fyodor Kupolov82402752015-10-28 14:54:51 -07002069 private void writeBitmapLP(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002070 try {
2071 File dir = new File(mUsersDir, Integer.toString(info.id));
2072 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +01002073 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002074 if (!dir.exists()) {
2075 dir.mkdir();
2076 FileUtils.setPermissions(
2077 dir.getPath(),
2078 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
2079 -1, -1);
2080 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07002081 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +01002082 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01002083 && tmp.renameTo(file) && SELinux.restorecon(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -07002084 info.iconPath = file.getAbsolutePath();
2085 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07002086 try {
2087 os.close();
2088 } catch (IOException ioe) {
2089 // What the ... !
2090 }
Adrian Roos1bdff912015-02-17 15:51:35 +01002091 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002092 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002093 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002094 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002095 }
2096
Amith Yamasani0b285492011-04-14 17:35:23 -07002097 /**
2098 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
2099 * cache it elsewhere.
2100 * @return the array of user ids.
2101 */
Dianne Hackborn1676c852012-09-10 14:52:30 -07002102 public int[] getUserIds() {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002103 synchronized (mUsersLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07002104 return mUserIds;
2105 }
Amith Yamasani0b285492011-04-14 17:35:23 -07002106 }
2107
Andreas Gampe2e8c7672018-07-20 13:01:08 -07002108 @GuardedBy({"mRestrictionsLock", "mPackagesLock"})
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002109 private void readUserListLP() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002110 if (!mUserListFile.exists()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002111 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002112 return;
2113 }
2114 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07002115 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002116 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07002117 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002118 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002119 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002120 int type;
2121 while ((type = parser.next()) != XmlPullParser.START_TAG
2122 && type != XmlPullParser.END_DOCUMENT) {
Amith Yamasani12747872015-12-07 14:19:49 -08002123 // Skip
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002124 }
2125
2126 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07002127 Slog.e(LOG_TAG, "Unable to read user list");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002128 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002129 return;
2130 }
2131
Amith Yamasani2a003292012-08-14 18:25:45 -07002132 mNextSerialNumber = -1;
2133 if (parser.getName().equals(TAG_USERS)) {
2134 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
2135 if (lastSerialNumber != null) {
2136 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
2137 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07002138 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
2139 if (versionNumber != null) {
2140 mUserVersion = Integer.parseInt(versionNumber);
2141 }
Amith Yamasani2a003292012-08-14 18:25:45 -07002142 }
2143
Pavel Grafov6a40f092016-10-25 15:46:51 +01002144 // Pre-O global user restriction were stored as a single bundle (as opposed to per-user
2145 // currently), take care of it in case of upgrade.
2146 Bundle oldDevicePolicyGlobalUserRestrictions = null;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002147
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002148 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05302149 if (type == XmlPullParser.START_TAG) {
2150 final String name = parser.getName();
2151 if (name.equals(TAG_USER)) {
2152 String id = parser.getAttributeValue(null, ATTR_ID);
Amith Yamasani6f34b412012-10-22 18:19:27 -07002153
Amith Yamasani12747872015-12-07 14:19:49 -08002154 UserData userData = readUserLP(Integer.parseInt(id));
2155
2156 if (userData != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002157 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002158 mUsers.put(userData.info.id, userData);
2159 if (mNextSerialNumber < 0
2160 || mNextSerialNumber <= userData.info.id) {
2161 mNextSerialNumber = userData.info.id + 1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002162 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05302163 }
Amith Yamasani2a003292012-08-14 18:25:45 -07002164 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05302165 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -08002166 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2167 && type != XmlPullParser.END_TAG) {
2168 if (type == XmlPullParser.START_TAG) {
2169 if (parser.getName().equals(TAG_RESTRICTIONS)) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002170 synchronized (mGuestRestrictions) {
Fyodor Kupoloveafee022017-03-15 17:09:04 -07002171 UserRestrictionsUtils
2172 .readRestrictions(parser, mGuestRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002173 }
Amith Yamasanida0b1682014-11-21 12:58:17 -08002174 }
2175 break;
2176 }
2177 }
Pavel Grafov6a40f092016-10-25 15:46:51 +01002178 } else if (name.equals(TAG_DEVICE_OWNER_USER_ID)
2179 // Legacy name, should only be encountered when upgrading from pre-O.
2180 || name.equals(TAG_GLOBAL_RESTRICTION_OWNER_ID)) {
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01002181 String ownerUserId = parser.getAttributeValue(null, ATTR_ID);
2182 if (ownerUserId != null) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01002183 mDeviceOwnerUserId = Integer.parseInt(ownerUserId);
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01002184 }
Pavel Grafov6a40f092016-10-25 15:46:51 +01002185 } else if (name.equals(TAG_DEVICE_POLICY_RESTRICTIONS)) {
2186 // Should only happen when upgrading from pre-O (version < 7).
2187 oldDevicePolicyGlobalUserRestrictions =
2188 UserRestrictionsUtils.readRestrictions(parser);
Amith Yamasani258848d2012-08-10 17:06:33 -07002189 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002190 }
2191 }
Pavel Grafov6a40f092016-10-25 15:46:51 +01002192
Fyodor Kupolov82402752015-10-28 14:54:51 -07002193 updateUserIds();
Pavel Grafov6a40f092016-10-25 15:46:51 +01002194 upgradeIfNecessaryLP(oldDevicePolicyGlobalUserRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002195 } catch (IOException | XmlPullParserException e) {
2196 fallbackToSingleUserLP();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08002197 } finally {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002198 IoUtils.closeQuietly(fis);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002199 }
2200 }
2201
Amith Yamasani6f34b412012-10-22 18:19:27 -07002202 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -08002203 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Pavel Grafov6a40f092016-10-25 15:46:51 +01002204 * @param oldGlobalUserRestrictions Pre-O global device policy restrictions.
Amith Yamasani6f34b412012-10-22 18:19:27 -07002205 */
Andreas Gampe2e8c7672018-07-20 13:01:08 -07002206 @GuardedBy({"mRestrictionsLock", "mPackagesLock"})
Pavel Grafov6a40f092016-10-25 15:46:51 +01002207 private void upgradeIfNecessaryLP(Bundle oldGlobalUserRestrictions) {
Bookatz75f0a072019-08-05 14:12:16 -07002208 Set<Integer> userIdsToWrite = new ArraySet<>();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002209 final int originalVersion = mUserVersion;
Amith Yamasani6f34b412012-10-22 18:19:27 -07002210 int userVersion = mUserVersion;
2211 if (userVersion < 1) {
2212 // Assign a proper name for the owner, if not initialized correctly before
Amith Yamasani12747872015-12-07 14:19:49 -08002213 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
2214 if ("Primary".equals(userData.info.name)) {
2215 userData.info.name =
2216 mContext.getResources().getString(com.android.internal.R.string.owner_name);
Bookatz75f0a072019-08-05 14:12:16 -07002217 userIdsToWrite.add(userData.info.id);
Amith Yamasani6f34b412012-10-22 18:19:27 -07002218 }
2219 userVersion = 1;
2220 }
2221
Amith Yamasanibc9625052012-11-15 14:39:18 -08002222 if (userVersion < 2) {
2223 // Owner should be marked as initialized
Amith Yamasani12747872015-12-07 14:19:49 -08002224 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
2225 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
2226 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
Bookatz75f0a072019-08-05 14:12:16 -07002227 userIdsToWrite.add(userData.info.id);
Amith Yamasanibc9625052012-11-15 14:39:18 -08002228 }
2229 userVersion = 2;
2230 }
2231
Amith Yamasani350962c2013-08-06 11:18:53 -07002232
Amith Yamasani5e486f52013-08-07 11:06:44 -07002233 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -07002234 userVersion = 4;
2235 }
2236
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07002237 if (userVersion < 5) {
2238 initDefaultGuestRestrictions();
2239 userVersion = 5;
2240 }
2241
Fyodor Kupolov1c363152015-09-02 13:27:21 -07002242 if (userVersion < 6) {
2243 final boolean splitSystemUser = UserManager.isSplitSystemUser();
Fyodor Kupolov82402752015-10-28 14:54:51 -07002244 synchronized (mUsersLock) {
2245 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002246 UserData userData = mUsers.valueAt(i);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002247 // In non-split mode, only user 0 can have restricted profiles
Amith Yamasani12747872015-12-07 14:19:49 -08002248 if (!splitSystemUser && userData.info.isRestricted()
2249 && (userData.info.restrictedProfileParentId
2250 == UserInfo.NO_PROFILE_GROUP_ID)) {
2251 userData.info.restrictedProfileParentId = UserHandle.USER_SYSTEM;
Bookatz75f0a072019-08-05 14:12:16 -07002252 userIdsToWrite.add(userData.info.id);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002253 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07002254 }
2255 }
2256 userVersion = 6;
2257 }
2258
Pavel Grafov6a40f092016-10-25 15:46:51 +01002259 if (userVersion < 7) {
2260 // Previously only one user could enforce global restrictions, now it is per-user.
2261 synchronized (mRestrictionsLock) {
2262 if (!UserRestrictionsUtils.isEmpty(oldGlobalUserRestrictions)
2263 && mDeviceOwnerUserId != UserHandle.USER_NULL) {
2264 mDevicePolicyGlobalUserRestrictions.put(
2265 mDeviceOwnerUserId, oldGlobalUserRestrictions);
2266 }
2267 // ENSURE_VERIFY_APPS is now enforced globally even if put by profile owner, so move
2268 // it from local to global bundle for all users who set it.
2269 UserRestrictionsUtils.moveRestriction(UserManager.ENSURE_VERIFY_APPS,
2270 mDevicePolicyLocalUserRestrictions, mDevicePolicyGlobalUserRestrictions
2271 );
2272 }
2273 userVersion = 7;
2274 }
2275
Bookatz75f0a072019-08-05 14:12:16 -07002276 if (userVersion < 8) {
2277 // Added FLAG_FULL and FLAG_SYSTEM flags.
2278 synchronized (mUsersLock) {
2279 UserData userData = mUsers.get(UserHandle.USER_SYSTEM);
2280 userData.info.flags |= UserInfo.FLAG_SYSTEM;
2281 if (!UserManager.isHeadlessSystemUserMode()) {
2282 userData.info.flags |= UserInfo.FLAG_FULL;
2283 }
2284 userIdsToWrite.add(userData.info.id);
2285
2286 // Mark FULL all non-profile users except USER_SYSTEM.
2287 // Start index at 1 since USER_SYSTEM is the smallest userId and we're skipping it.
2288 for (int i = 1; i < mUsers.size(); i++) {
2289 userData = mUsers.valueAt(i);
2290 if ((userData.info.flags & UserInfo.FLAG_MANAGED_PROFILE) == 0) {
2291 userData.info.flags |= UserInfo.FLAG_FULL;
2292 userIdsToWrite.add(userData.info.id);
2293 }
2294 }
2295 }
2296 userVersion = 8;
2297 }
2298
Amith Yamasani6f34b412012-10-22 18:19:27 -07002299 if (userVersion < USER_VERSION) {
2300 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
2301 + USER_VERSION);
2302 } else {
2303 mUserVersion = userVersion;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002304
2305 if (originalVersion < mUserVersion) {
Bookatz75f0a072019-08-05 14:12:16 -07002306 for (int userId : userIdsToWrite) {
2307 UserData userData = getUserDataNoChecks(userId);
2308 if (userData != null) {
2309 writeUserLP(userData);
2310 }
2311 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002312 writeUserListLP();
2313 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07002314 }
2315 }
2316
Andreas Gampe2e8c7672018-07-20 13:01:08 -07002317 @GuardedBy({"mPackagesLock", "mRestrictionsLock"})
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002318 private void fallbackToSingleUserLP() {
Ying Zheng215116f2019-09-11 12:50:09 -07002319 int flags = UserInfo.FLAG_SYSTEM | UserInfo.FLAG_INITIALIZED | UserInfo.FLAG_ADMIN
2320 | UserInfo.FLAG_PRIMARY;
2321 // In headless system user mode, headless system user is not a full user.
Bookatz75f0a072019-08-05 14:12:16 -07002322 if (!UserManager.isHeadlessSystemUserMode()) {
Ying Zheng215116f2019-09-11 12:50:09 -07002323 flags |= UserInfo.FLAG_FULL;
Bookatz75f0a072019-08-05 14:12:16 -07002324 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -07002325 // Create the system user
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07002326 UserInfo system = new UserInfo(UserHandle.USER_SYSTEM, null, null, flags);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002327 UserData userData = putUserInfo(system);
Amith Yamasani634cf312012-10-04 17:34:21 -07002328 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -04002329 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -08002330
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05002331 Bundle restrictions = new Bundle();
Mahaver Chopra3d9805d2016-07-07 16:25:05 +01002332 try {
2333 final String[] defaultFirstUserRestrictions = mContext.getResources().getStringArray(
2334 com.android.internal.R.array.config_defaultFirstUserRestrictions);
2335 for (String userRestriction : defaultFirstUserRestrictions) {
2336 if (UserRestrictionsUtils.isValidRestriction(userRestriction)) {
2337 restrictions.putBoolean(userRestriction, true);
2338 }
2339 }
2340 } catch (Resources.NotFoundException e) {
2341 Log.e(LOG_TAG, "Couldn't find resource: config_defaultFirstUserRestrictions", e);
2342 }
2343
Pavel Grafov6a40f092016-10-25 15:46:51 +01002344 if (!restrictions.isEmpty()) {
2345 synchronized (mRestrictionsLock) {
2346 mBaseUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions);
2347 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07002348 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08002349
Fyodor Kupolov82402752015-10-28 14:54:51 -07002350 updateUserIds();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07002351 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002352
Amith Yamasani12747872015-12-07 14:19:49 -08002353 writeUserLP(userData);
Jeff Sharkeycd575992016-03-29 14:12:49 -06002354 writeUserListLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002355 }
2356
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07002357 private String getOwnerName() {
2358 return mContext.getResources().getString(com.android.internal.R.string.owner_name);
2359 }
2360
Bookatz75f0a072019-08-05 14:12:16 -07002361 private void scheduleWriteUser(UserData userData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002362 if (DBG) {
2363 debug("scheduleWriteUser");
2364 }
Makoto Onuki9e935a32015-11-06 14:24:24 -08002365 // No need to wrap it within a lock -- worst case, we'll just post the same message
2366 // twice.
Bookatz75f0a072019-08-05 14:12:16 -07002367 if (!mHandler.hasMessages(WRITE_USER_MSG, userData)) {
2368 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, userData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002369 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
2370 }
2371 }
2372
Amith Yamasani12747872015-12-07 14:19:49 -08002373 private void writeUserLP(UserData userData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002374 if (DBG) {
Amith Yamasani12747872015-12-07 14:19:49 -08002375 debug("writeUserLP " + userData);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002376 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002377 FileOutputStream fos = null;
Amith Yamasani12747872015-12-07 14:19:49 -08002378 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userData.info.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002379 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07002380 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002381 final BufferedOutputStream bos = new BufferedOutputStream(fos);
Kenny Guy02c89902016-11-15 19:36:38 +00002382 writeUserLP(userData, bos);
Amith Yamasani2a003292012-08-14 18:25:45 -07002383 userFile.finishWrite(fos);
2384 } catch (Exception ioe) {
Jeff Sharkeycd575992016-03-29 14:12:49 -06002385 Slog.e(LOG_TAG, "Error writing user info " + userData.info.id, ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -07002386 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002387 }
2388 }
2389
2390 /*
Kenny Guy02c89902016-11-15 19:36:38 +00002391 * Writes the user file in this format:
2392 *
2393 * <user flags="20039023" id="0">
2394 * <name>Primary</name>
2395 * </user>
2396 */
2397 @VisibleForTesting
2398 void writeUserLP(UserData userData, OutputStream os)
2399 throws IOException, XmlPullParserException {
2400 // XmlSerializer serializer = XmlUtils.serializerInstance();
2401 final XmlSerializer serializer = new FastXmlSerializer();
2402 serializer.setOutput(os, StandardCharsets.UTF_8.name());
2403 serializer.startDocument(null, true);
2404 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2405
2406 final UserInfo userInfo = userData.info;
2407 serializer.startTag(null, TAG_USER);
2408 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
2409 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
2410 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
2411 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
2412 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
2413 Long.toString(userInfo.lastLoggedInTime));
2414 if (userInfo.lastLoggedInFingerprint != null) {
2415 serializer.attribute(null, ATTR_LAST_LOGGED_IN_FINGERPRINT,
2416 userInfo.lastLoggedInFingerprint);
2417 }
2418 if (userInfo.iconPath != null) {
2419 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
2420 }
2421 if (userInfo.partial) {
2422 serializer.attribute(null, ATTR_PARTIAL, "true");
2423 }
Felipe Lemec1ca4412019-09-11 09:23:26 -07002424 if (userInfo.preCreated) {
2425 serializer.attribute(null, ATTR_PRE_CREATED, "true");
2426 }
Kenny Guy02c89902016-11-15 19:36:38 +00002427 if (userInfo.guestToRemove) {
2428 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
2429 }
2430 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
2431 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
2432 Integer.toString(userInfo.profileGroupId));
2433 }
2434 serializer.attribute(null, ATTR_PROFILE_BADGE,
2435 Integer.toString(userInfo.profileBadge));
2436 if (userInfo.restrictedProfileParentId != UserInfo.NO_PROFILE_GROUP_ID) {
2437 serializer.attribute(null, ATTR_RESTRICTED_PROFILE_PARENT_ID,
2438 Integer.toString(userInfo.restrictedProfileParentId));
2439 }
2440 // Write seed data
2441 if (userData.persistSeedData) {
2442 if (userData.seedAccountName != null) {
2443 serializer.attribute(null, ATTR_SEED_ACCOUNT_NAME, userData.seedAccountName);
2444 }
2445 if (userData.seedAccountType != null) {
2446 serializer.attribute(null, ATTR_SEED_ACCOUNT_TYPE, userData.seedAccountType);
2447 }
2448 }
2449 if (userInfo.name != null) {
2450 serializer.startTag(null, TAG_NAME);
2451 serializer.text(userInfo.name);
2452 serializer.endTag(null, TAG_NAME);
2453 }
2454 synchronized (mRestrictionsLock) {
2455 UserRestrictionsUtils.writeRestrictions(serializer,
2456 mBaseUserRestrictions.get(userInfo.id), TAG_RESTRICTIONS);
2457 UserRestrictionsUtils.writeRestrictions(serializer,
2458 mDevicePolicyLocalUserRestrictions.get(userInfo.id),
2459 TAG_DEVICE_POLICY_RESTRICTIONS);
Pavel Grafov6a40f092016-10-25 15:46:51 +01002460 UserRestrictionsUtils.writeRestrictions(serializer,
2461 mDevicePolicyGlobalUserRestrictions.get(userInfo.id),
2462 TAG_DEVICE_POLICY_GLOBAL_RESTRICTIONS);
Kenny Guy02c89902016-11-15 19:36:38 +00002463 }
2464
2465 if (userData.account != null) {
2466 serializer.startTag(null, TAG_ACCOUNT);
2467 serializer.text(userData.account);
2468 serializer.endTag(null, TAG_ACCOUNT);
2469 }
2470
2471 if (userData.persistSeedData && userData.seedAccountOptions != null) {
2472 serializer.startTag(null, TAG_SEED_ACCOUNT_OPTIONS);
2473 userData.seedAccountOptions.saveToXml(serializer);
2474 serializer.endTag(null, TAG_SEED_ACCOUNT_OPTIONS);
2475 }
2476
arangelov9b632d72018-12-07 23:21:22 +00002477 if (userData.getLastRequestQuietModeEnabledMillis() != 0L) {
2478 serializer.startTag(/* namespace */ null, TAG_LAST_REQUEST_QUIET_MODE_ENABLED_CALL);
2479 serializer.text(String.valueOf(userData.getLastRequestQuietModeEnabledMillis()));
2480 serializer.endTag(/* namespace */ null, TAG_LAST_REQUEST_QUIET_MODE_ENABLED_CALL);
2481 }
2482
Kenny Guy02c89902016-11-15 19:36:38 +00002483 serializer.endTag(null, TAG_USER);
2484
2485 serializer.endDocument();
2486 }
2487
2488 /*
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002489 * Writes the user list file in this format:
2490 *
Amith Yamasani2a003292012-08-14 18:25:45 -07002491 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002492 * <user id="0"></user>
2493 * <user id="2"></user>
2494 * </users>
2495 */
Andreas Gampe2e8c7672018-07-20 13:01:08 -07002496 @GuardedBy({"mRestrictionsLock", "mPackagesLock"})
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002497 private void writeUserListLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002498 if (DBG) {
2499 debug("writeUserList");
2500 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002501 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07002502 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002503 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07002504 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002505 final BufferedOutputStream bos = new BufferedOutputStream(fos);
2506
2507 // XmlSerializer serializer = XmlUtils.serializerInstance();
2508 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002509 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002510 serializer.startDocument(null, true);
2511 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2512
2513 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -07002514 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -07002515 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002516
Adam Lesinskieddeb492014-09-08 17:50:03 -07002517 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002518 synchronized (mGuestRestrictions) {
2519 UserRestrictionsUtils
2520 .writeRestrictions(serializer, mGuestRestrictions, TAG_RESTRICTIONS);
2521 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05302522 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Pavel Grafov6a40f092016-10-25 15:46:51 +01002523 serializer.startTag(null, TAG_DEVICE_OWNER_USER_ID);
2524 serializer.attribute(null, ATTR_ID, Integer.toString(mDeviceOwnerUserId));
2525 serializer.endTag(null, TAG_DEVICE_OWNER_USER_ID);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002526 int[] userIdsToWrite;
2527 synchronized (mUsersLock) {
2528 userIdsToWrite = new int[mUsers.size()];
2529 for (int i = 0; i < userIdsToWrite.length; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002530 UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002531 userIdsToWrite[i] = user.id;
2532 }
2533 }
2534 for (int id : userIdsToWrite) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002535 serializer.startTag(null, TAG_USER);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002536 serializer.attribute(null, ATTR_ID, Integer.toString(id));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002537 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002538 }
2539
2540 serializer.endTag(null, TAG_USERS);
2541
2542 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07002543 userListFile.finishWrite(fos);
2544 } catch (Exception e) {
2545 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -07002546 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002547 }
2548 }
2549
Amith Yamasani12747872015-12-07 14:19:49 -08002550 private UserData readUserLP(int id) {
Kenny Guy02c89902016-11-15 19:36:38 +00002551 FileInputStream fis = null;
2552 try {
2553 AtomicFile userFile =
2554 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
2555 fis = userFile.openRead();
2556 return readUserLP(id, fis);
2557 } catch (IOException ioe) {
2558 Slog.e(LOG_TAG, "Error reading user list");
2559 } catch (XmlPullParserException pe) {
2560 Slog.e(LOG_TAG, "Error reading user list");
2561 } finally {
2562 IoUtils.closeQuietly(fis);
2563 }
2564 return null;
2565 }
2566
2567 @VisibleForTesting
2568 UserData readUserLP(int id, InputStream is) throws IOException,
2569 XmlPullParserException {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002570 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -07002571 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002572 String name = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -08002573 String account = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002574 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -07002575 long creationTime = 0L;
2576 long lastLoggedInTime = 0L;
arangelov9b632d72018-12-07 23:21:22 +00002577 long lastRequestQuietModeEnabledTimestamp = 0L;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002578 String lastLoggedInFingerprint = null;
Kenny Guy2a764942014-04-02 13:29:20 +01002579 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Kenny Guy02c89902016-11-15 19:36:38 +00002580 int profileBadge = 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002581 int restrictedProfileParentId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002582 boolean partial = false;
Felipe Lemec1ca4412019-09-11 09:23:26 -07002583 boolean preCreated = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -07002584 boolean guestToRemove = false;
Amith Yamasani12747872015-12-07 14:19:49 -08002585 boolean persistSeedData = false;
2586 String seedAccountName = null;
2587 String seedAccountType = null;
2588 PersistableBundle seedAccountOptions = null;
Pavel Grafov6a40f092016-10-25 15:46:51 +01002589 Bundle baseRestrictions = null;
2590 Bundle localRestrictions = null;
2591 Bundle globalRestrictions = null;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002592
Kenny Guy02c89902016-11-15 19:36:38 +00002593 XmlPullParser parser = Xml.newPullParser();
2594 parser.setInput(is, StandardCharsets.UTF_8.name());
2595 int type;
2596 while ((type = parser.next()) != XmlPullParser.START_TAG
2597 && type != XmlPullParser.END_DOCUMENT) {
2598 // Skip
2599 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002600
Kenny Guy02c89902016-11-15 19:36:38 +00002601 if (type != XmlPullParser.START_TAG) {
2602 Slog.e(LOG_TAG, "Unable to read user " + id);
2603 return null;
2604 }
2605
2606 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
2607 int storedId = readIntAttribute(parser, ATTR_ID, -1);
2608 if (storedId != id) {
2609 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002610 return null;
2611 }
Kenny Guy02c89902016-11-15 19:36:38 +00002612 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
2613 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
2614 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
2615 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
2616 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
2617 lastLoggedInFingerprint = parser.getAttributeValue(null,
2618 ATTR_LAST_LOGGED_IN_FINGERPRINT);
2619 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
2620 UserInfo.NO_PROFILE_GROUP_ID);
2621 profileBadge = readIntAttribute(parser, ATTR_PROFILE_BADGE, 0);
2622 restrictedProfileParentId = readIntAttribute(parser,
2623 ATTR_RESTRICTED_PROFILE_PARENT_ID, UserInfo.NO_PROFILE_GROUP_ID);
2624 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
2625 if ("true".equals(valueString)) {
2626 partial = true;
2627 }
Felipe Lemec1ca4412019-09-11 09:23:26 -07002628 valueString = parser.getAttributeValue(null, ATTR_PRE_CREATED);
2629 if ("true".equals(valueString)) {
2630 preCreated = true;
2631 }
Kenny Guy02c89902016-11-15 19:36:38 +00002632 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
2633 if ("true".equals(valueString)) {
2634 guestToRemove = true;
2635 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002636
Kenny Guy02c89902016-11-15 19:36:38 +00002637 seedAccountName = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_NAME);
2638 seedAccountType = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_TYPE);
2639 if (seedAccountName != null || seedAccountType != null) {
2640 persistSeedData = true;
2641 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002642
Kenny Guy02c89902016-11-15 19:36:38 +00002643 int outerDepth = parser.getDepth();
2644 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2645 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2646 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2647 continue;
2648 }
2649 String tag = parser.getName();
2650 if (TAG_NAME.equals(tag)) {
2651 type = parser.next();
2652 if (type == XmlPullParser.TEXT) {
2653 name = parser.getText();
2654 }
2655 } else if (TAG_RESTRICTIONS.equals(tag)) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01002656 baseRestrictions = UserRestrictionsUtils.readRestrictions(parser);
Kenny Guy02c89902016-11-15 19:36:38 +00002657 } else if (TAG_DEVICE_POLICY_RESTRICTIONS.equals(tag)) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01002658 localRestrictions = UserRestrictionsUtils.readRestrictions(parser);
2659 } else if (TAG_DEVICE_POLICY_GLOBAL_RESTRICTIONS.equals(tag)) {
2660 globalRestrictions = UserRestrictionsUtils.readRestrictions(parser);
Kenny Guy02c89902016-11-15 19:36:38 +00002661 } else if (TAG_ACCOUNT.equals(tag)) {
2662 type = parser.next();
2663 if (type == XmlPullParser.TEXT) {
2664 account = parser.getText();
2665 }
2666 } else if (TAG_SEED_ACCOUNT_OPTIONS.equals(tag)) {
2667 seedAccountOptions = PersistableBundle.restoreFromXml(parser);
Amith Yamasani12747872015-12-07 14:19:49 -08002668 persistSeedData = true;
arangelov9b632d72018-12-07 23:21:22 +00002669 } else if (TAG_LAST_REQUEST_QUIET_MODE_ENABLED_CALL.equals(tag)) {
2670 type = parser.next();
2671 if (type == XmlPullParser.TEXT) {
2672 lastRequestQuietModeEnabledTimestamp = Long.parseLong(parser.getText());
2673 }
Amith Yamasani12747872015-12-07 14:19:49 -08002674 }
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08002675 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002676 }
Kenny Guy02c89902016-11-15 19:36:38 +00002677
2678 // Create the UserInfo object that gets passed around
2679 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
2680 userInfo.serialNumber = serialNumber;
2681 userInfo.creationTime = creationTime;
2682 userInfo.lastLoggedInTime = lastLoggedInTime;
2683 userInfo.lastLoggedInFingerprint = lastLoggedInFingerprint;
2684 userInfo.partial = partial;
Felipe Lemec1ca4412019-09-11 09:23:26 -07002685 userInfo.preCreated = preCreated;
Kenny Guy02c89902016-11-15 19:36:38 +00002686 userInfo.guestToRemove = guestToRemove;
2687 userInfo.profileGroupId = profileGroupId;
2688 userInfo.profileBadge = profileBadge;
2689 userInfo.restrictedProfileParentId = restrictedProfileParentId;
2690
2691 // Create the UserData object that's internal to this class
2692 UserData userData = new UserData();
2693 userData.info = userInfo;
2694 userData.account = account;
2695 userData.seedAccountName = seedAccountName;
2696 userData.seedAccountType = seedAccountType;
2697 userData.persistSeedData = persistSeedData;
2698 userData.seedAccountOptions = seedAccountOptions;
arangelov9b632d72018-12-07 23:21:22 +00002699 userData.setLastRequestQuietModeEnabledMillis(lastRequestQuietModeEnabledTimestamp);
Kenny Guy02c89902016-11-15 19:36:38 +00002700
2701 synchronized (mRestrictionsLock) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01002702 if (baseRestrictions != null) {
2703 mBaseUserRestrictions.put(id, baseRestrictions);
2704 }
2705 if (localRestrictions != null) {
2706 mDevicePolicyLocalUserRestrictions.put(id, localRestrictions);
2707 }
2708 if (globalRestrictions != null) {
2709 mDevicePolicyGlobalUserRestrictions.put(id, globalRestrictions);
2710 }
Kenny Guy02c89902016-11-15 19:36:38 +00002711 }
2712 return userData;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002713 }
2714
Amith Yamasani920ace02012-09-20 22:15:37 -07002715 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
2716 String valueString = parser.getAttributeValue(null, attr);
2717 if (valueString == null) return defaultValue;
2718 try {
2719 return Integer.parseInt(valueString);
2720 } catch (NumberFormatException nfe) {
2721 return defaultValue;
2722 }
2723 }
2724
2725 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
2726 String valueString = parser.getAttributeValue(null, attr);
2727 if (valueString == null) return defaultValue;
2728 try {
2729 return Long.parseLong(valueString);
2730 } catch (NumberFormatException nfe) {
2731 return defaultValue;
2732 }
2733 }
2734
Amith Yamasanib82add22013-07-09 11:24:44 -07002735 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002736 * Removes the app restrictions file for a specific package and user id, if it exists.
2737 */
Bookatzf56f2582019-09-04 16:06:41 -07002738 private static void cleanAppRestrictionsForPackageLAr(String pkg, @UserIdInt int userId) {
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07002739 File dir = Environment.getUserSystemDirectory(userId);
2740 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
2741 if (resFile.exists()) {
2742 resFile.delete();
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002743 }
2744 }
2745
Kenny Guya52dc3e2014-02-11 15:33:14 +00002746 @Override
Bookatzf56f2582019-09-04 16:06:41 -07002747 public UserInfo createProfileForUser(String name, int flags, @UserIdInt int userId,
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002748 String[] disallowedPackages) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002749 checkManageOrCreateUsersPermission(flags);
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002750 return createUserInternal(name, flags, userId, disallowedPackages);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002751 }
2752
Amith Yamasani258848d2012-08-10 17:06:33 -07002753 @Override
Bookatzf56f2582019-09-04 16:06:41 -07002754 public UserInfo createProfileForUserEvenWhenDisallowed(String name, int flags,
2755 @UserIdInt int userId, String[] disallowedPackages) {
Tony Mak6dc428f2016-10-10 15:48:27 +01002756 checkManageOrCreateUsersPermission(flags);
Felipe Lemec1ca4412019-09-11 09:23:26 -07002757 return createUserInternalUnchecked(name, flags, userId, /* preCreate= */ false,
2758 disallowedPackages);
Tony Mak6dc428f2016-10-10 15:48:27 +01002759 }
2760
2761 @Override
Bookatzf56f2582019-09-04 16:06:41 -07002762 public boolean removeUserEvenWhenDisallowed(@UserIdInt int userId) {
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00002763 checkManageOrCreateUsersPermission("Only the system can remove users");
Bookatzf56f2582019-09-04 16:06:41 -07002764 return removeUserUnchecked(userId);
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00002765 }
2766
2767 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07002768 public UserInfo createUser(String name, int flags) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002769 checkManageOrCreateUsersPermission(flags);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00002770 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002771 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07002772
Felipe Lemec1ca4412019-09-11 09:23:26 -07002773 @Override
2774 public UserInfo preCreateUser(int flags) {
2775 checkManageOrCreateUsersPermission(flags);
2776
2777 Preconditions.checkArgument(!UserInfo.isManagedProfile(flags),
2778 "cannot pre-create managed profiles");
2779
Felipe Leme09a7f2d2019-10-02 16:27:46 -07002780 Slog.i(LOG_TAG, "Pre-creating user with flags " + UserInfo.flagsToString(flags));
2781
Felipe Lemec1ca4412019-09-11 09:23:26 -07002782 return createUserInternalUnchecked(/* name= */ null, flags,
2783 /* parentId= */ UserHandle.USER_NULL, /* preCreate= */ true,
2784 /* disallowedPackages= */ null);
2785 }
2786
2787 private UserInfo createUserInternal(@Nullable String name, @UserInfoFlag int flags,
2788 @UserIdInt int parentId) {
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002789 return createUserInternal(name, flags, parentId, null);
2790 }
2791
Felipe Lemec1ca4412019-09-11 09:23:26 -07002792 private UserInfo createUserInternal(@Nullable String name, @UserInfoFlag int flags,
2793 @UserIdInt int parentId, @Nullable String[] disallowedPackages) {
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002794 String restriction = ((flags & UserInfo.FLAG_MANAGED_PROFILE) != 0)
2795 ? UserManager.DISALLOW_ADD_MANAGED_PROFILE
2796 : UserManager.DISALLOW_ADD_USER;
2797 if (hasUserRestriction(restriction, UserHandle.getCallingUserId())) {
2798 Log.w(LOG_TAG, "Cannot add user. " + restriction + " is enabled.");
Julia Reynolds75175022014-06-26 16:35:00 -04002799 return null;
2800 }
Felipe Lemec1ca4412019-09-11 09:23:26 -07002801 return createUserInternalUnchecked(name, flags, parentId, /* preCreate= */ false,
2802 disallowedPackages);
Tony Mak6dc428f2016-10-10 15:48:27 +01002803 }
2804
Felipe Lemec1ca4412019-09-11 09:23:26 -07002805 private UserInfo createUserInternalUnchecked(@Nullable String name, @UserInfoFlag int flags,
2806 @UserIdInt int parentId, boolean preCreate,
2807 @Nullable String[] disallowedPackages) {
2808 final TimingsTraceAndSlog t = new TimingsTraceAndSlog();
2809 t.traceBegin("createUser-" + flags);
2810 try {
2811 return createUserInternalUncheckedNoTracing(name, flags, parentId, preCreate,
2812 disallowedPackages, t);
2813 } finally {
2814 t.traceEnd();
2815 }
jovanakdd7e4752019-09-04 12:35:45 -07002816 }
2817
Felipe Lemec1ca4412019-09-11 09:23:26 -07002818 private UserInfo createUserInternalUncheckedNoTracing(@Nullable String name,
2819 @UserInfoFlag int flags, @UserIdInt int parentId, boolean preCreate,
2820 @Nullable String[] disallowedPackages, @NonNull TimingsTraceAndSlog t) {
2821
2822 // First try to use a pre-created user (if available).
2823 // NOTE: currently we don't support pre-created managed profiles
2824 if (!preCreate && (parentId < 0 && !UserInfo.isManagedProfile(flags))) {
2825 final UserData preCreatedUserData;
2826 synchronized (mUsersLock) {
2827 preCreatedUserData = getPreCreatedUserLU(flags);
2828 }
2829 if (preCreatedUserData != null) {
2830 final UserInfo preCreatedUser = preCreatedUserData.info;
2831 Log.i(LOG_TAG, "Reusing pre-created user " + preCreatedUser.id + " for flags + "
2832 + UserInfo.flagsToString(flags));
2833 if (DBG) {
2834 Log.d(LOG_TAG, "pre-created user flags: "
2835 + UserInfo.flagsToString(preCreatedUser.flags)
2836 + " new-user flags: " + UserInfo.flagsToString(flags));
2837 }
2838 preCreatedUser.name = name;
2839 preCreatedUser.preCreated = false;
2840 preCreatedUser.creationTime = getCreationTime();
2841
2842 dispatchUserAddedIntent(preCreatedUser);
2843
2844 writeUserLP(preCreatedUserData);
2845 writeUserListLP();
2846
2847 return preCreatedUser;
2848 }
2849 }
2850
Suprabh Shuklac5e057c2016-08-08 16:22:44 -07002851 DeviceStorageMonitorInternal dsm = LocalServices
2852 .getService(DeviceStorageMonitorInternal.class);
2853 if (dsm.isMemoryLow()) {
2854 Log.w(LOG_TAG, "Cannot add user. Not enough space on disk.");
2855 return null;
2856 }
jovanakdd7e4752019-09-04 12:35:45 -07002857
Felipe Lemec1ca4412019-09-11 09:23:26 -07002858 final boolean isGuest = UserInfo.isGuest(flags);
2859 final boolean isManagedProfile = UserInfo.isManagedProfile(flags);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002860 final boolean isRestricted = (flags & UserInfo.FLAG_RESTRICTED) != 0;
Amith Yamasani52c21e32016-05-31 09:12:20 -07002861 final boolean isDemo = (flags & UserInfo.FLAG_DEMO) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002862 final long ident = Binder.clearCallingIdentity();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002863 UserInfo userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08002864 UserData userData;
Amith Yamasanibb054c92015-07-09 14:16:27 -07002865 final int userId;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002866 try {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002867 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002868 UserData parent = null;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002869 if (parentId != UserHandle.USER_NULL) {
2870 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002871 parent = getUserDataLU(parentId);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00002872 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002873 if (parent == null) return null;
2874 }
2875 if (isManagedProfile && !canAddMoreManagedProfiles(parentId, false)) {
2876 Log.e(LOG_TAG, "Cannot add more managed profiles for user " + parentId);
2877 return null;
2878 }
Amith Yamasani52c21e32016-05-31 09:12:20 -07002879 if (!isGuest && !isManagedProfile && !isDemo && isUserLimitReached()) {
Felipe Lemec1ca4412019-09-11 09:23:26 -07002880 // If we're not adding a guest/demo user or a managed profile,
2881 // and the limit has been reached, cannot add a user.
jovanaka6763a32018-12-03 17:23:20 -08002882 Log.e(LOG_TAG, "Cannot add user. Maximum user limit is reached.");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002883 return null;
2884 }
2885 // If we're adding a guest and there already exists one, bail.
Felipe Lemee35f5b02019-10-14 15:37:44 -07002886 if (isGuest && !preCreate && findCurrentGuestUser() != null) {
jovanaka6763a32018-12-03 17:23:20 -08002887 Log.e(LOG_TAG, "Cannot add guest user. Guest user already exists.");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002888 return null;
2889 }
2890 // In legacy mode, restricted profile's parent can only be the owner user
2891 if (isRestricted && !UserManager.isSplitSystemUser()
2892 && (parentId != UserHandle.USER_SYSTEM)) {
2893 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
2894 return null;
2895 }
2896 if (isRestricted && UserManager.isSplitSystemUser()) {
2897 if (parent == null) {
2898 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be "
2899 + "specified");
Nicolas Prevot12678a92015-05-13 12:15:03 -07002900 return null;
2901 }
Amith Yamasani12747872015-12-07 14:19:49 -08002902 if (!parent.info.canHaveProfile()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002903 Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be "
2904 + "created for the specified parent user id " + parentId);
Amith Yamasani95ab7842014-08-11 17:09:26 -07002905 return null;
2906 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002907 }
Ying Zheng215116f2019-09-11 12:50:09 -07002908
Bookatz75f0a072019-08-05 14:12:16 -07002909 if (!isManagedProfile) {
2910 // New users cannot be system, and it's not a profile, so per-force it's FULL.
2911 flags |= UserInfo.FLAG_FULL;
2912 }
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002913
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002914 userId = getNextAvailableId();
2915 Environment.getUserSystemDirectory(userId).mkdirs();
Felipe Lemec1ca4412019-09-11 09:23:26 -07002916 boolean ephemeralGuests = areGuestUsersEphemeral();
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002917
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002918 synchronized (mUsersLock) {
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002919 // Add ephemeral flag to guests/users if required. Also inherit it from parent.
2920 if ((isGuest && ephemeralGuests) || mForceEphemeralUsers
2921 || (parent != null && parent.info.isEphemeral())) {
2922 flags |= UserInfo.FLAG_EPHEMERAL;
2923 }
2924
2925 userInfo = new UserInfo(userId, name, null, flags);
2926 userInfo.serialNumber = mNextSerialNumber++;
Felipe Lemec1ca4412019-09-11 09:23:26 -07002927 userInfo.creationTime = getCreationTime();
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002928 userInfo.partial = true;
Felipe Lemec1ca4412019-09-11 09:23:26 -07002929 userInfo.preCreated = preCreate;
Fyodor Kupolov83c24242016-03-31 13:30:42 -07002930 userInfo.lastLoggedInFingerprint = Build.FINGERPRINT;
Kenny Guy02c89902016-11-15 19:36:38 +00002931 if (isManagedProfile && parentId != UserHandle.USER_NULL) {
2932 userInfo.profileBadge = getFreeProfileBadgeLU(parentId);
2933 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002934 userData = new UserData();
2935 userData.info = userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08002936 mUsers.put(userId, userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002937 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06002938 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002939 writeUserListLP();
2940 if (parent != null) {
2941 if (isManagedProfile) {
Amith Yamasani12747872015-12-07 14:19:49 -08002942 if (parent.info.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
2943 parent.info.profileGroupId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002944 writeUserLP(parent);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002945 }
Amith Yamasani12747872015-12-07 14:19:49 -08002946 userInfo.profileGroupId = parent.info.profileGroupId;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002947 } else if (isRestricted) {
Amith Yamasani12747872015-12-07 14:19:49 -08002948 if (parent.info.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) {
2949 parent.info.restrictedProfileParentId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002950 writeUserLP(parent);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002951 }
Amith Yamasani12747872015-12-07 14:19:49 -08002952 userInfo.restrictedProfileParentId = parent.info.restrictedProfileParentId;
Makoto Onuki068c54a2015-10-13 14:34:03 -07002953 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002954 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07002955 }
jovanakdd7e4752019-09-04 12:35:45 -07002956
2957 t.traceBegin("createUserKey");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002958 final StorageManager storage = mContext.getSystemService(StorageManager.class);
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002959 storage.createUserKey(userId, userInfo.serialNumber, userInfo.isEphemeral());
jovanakdd7e4752019-09-04 12:35:45 -07002960 t.traceEnd();
2961
2962 t.traceBegin("prepareUserData");
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -08002963 mUserDataPreparer.prepareUserData(userId, userInfo.serialNumber,
Jeff Sharkey47f71082016-02-01 17:03:54 -07002964 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
jovanakdd7e4752019-09-04 12:35:45 -07002965 t.traceEnd();
2966
Bookatz04d7ae52019-08-05 14:07:12 -07002967 final Set<String> installablePackages =
2968 mSystemPackageInstaller.getInstallablePackagesForUserType(flags);
jovanakdd7e4752019-09-04 12:35:45 -07002969 t.traceBegin("PM.createNewUser");
Bookatz04d7ae52019-08-05 14:07:12 -07002970 mPm.createNewUser(userId, installablePackages, disallowedPackages);
jovanakdd7e4752019-09-04 12:35:45 -07002971 t.traceEnd();
2972
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002973 userInfo.partial = false;
2974 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002975 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002976 }
2977 updateUserIds();
2978 Bundle restrictions = new Bundle();
Fyodor Kupolove04462c2015-11-30 15:02:53 -08002979 if (isGuest) {
2980 synchronized (mGuestRestrictions) {
2981 restrictions.putAll(mGuestRestrictions);
2982 }
2983 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002984 synchronized (mRestrictionsLock) {
2985 mBaseUserRestrictions.append(userId, restrictions);
2986 }
jovanakdd7e4752019-09-04 12:35:45 -07002987
2988 t.traceBegin("PM.onNewUserCreated");
Fyodor Kupolov5fd967d2016-07-12 14:46:19 -07002989 mPm.onNewUserCreated(userId);
jovanakdd7e4752019-09-04 12:35:45 -07002990
Felipe Lemec1ca4412019-09-11 09:23:26 -07002991 if (preCreate) {
2992 // Must start user (which will be stopped right away, through
2993 // UserController.finishUserUnlockedCompleted) so services can properly
2994 // intialize it.
Felipe Lemec6e015d2019-10-21 12:51:08 -07002995 // TODO(b/143092698): in the long-term, it might be better to add a onCreateUser()
2996 // callback on SystemService instead.
Felipe Lemec1ca4412019-09-11 09:23:26 -07002997 Slog.i(LOG_TAG, "starting pre-created user " + userInfo.toFullString());
2998 final IActivityManager am = ActivityManager.getService();
2999 try {
3000 am.startUserInBackground(userId);
3001 } catch (RemoteException e) {
3002 Slog.w(LOG_TAG, "could not start pre-created user " + userId, e);
3003 }
3004 } else {
3005 dispatchUserAddedIntent(userInfo);
3006 }
3007
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07003008 } finally {
3009 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07003010 }
Felipe Lemec1ca4412019-09-11 09:23:26 -07003011
Felipe Lemec6e015d2019-10-21 12:51:08 -07003012 // TODO(b/143092698): it's possible to reach "max users overflow" when the user is created
Felipe Lemec1ca4412019-09-11 09:23:26 -07003013 // "from scratch" (i.e., not from a pre-created user) and reaches the maximum number of
3014 // users without counting the pre-created one. Then when the pre-created is converted, the
3015 // "effective" number of max users is exceeds. Example:
3016 // Max: 3 Current: 2 full (u0 and u10) + 1 pre-created (u11)
3017 // Step 1: create(/* flags doesn't match u11 */): u12 is created, "effective max" is now 3
3018 // (u0, u10, u12) but "real" max is 4 (u0, u10, u11, u12)
3019 // Step 2: create(/* flags match u11 */): u11 is converted, now "effective max" is also 4
3020 // (u0, u10, u11, u12)
3021 // One way to avoid this issue is by removing a pre-created user from the pool when the
3022 // "real" max exceeds the max here.
3023
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003024 return userInfo;
3025 }
3026
Bookatz04d7ae52019-08-05 14:07:12 -07003027 /** Install/uninstall system packages for all users based on their user-type, as applicable. */
3028 boolean installWhitelistedSystemPackages(boolean isFirstBoot, boolean isUpgrade) {
3029 return mSystemPackageInstaller.installWhitelistedSystemPackages(isFirstBoot, isUpgrade);
3030 }
3031
Felipe Lemec1ca4412019-09-11 09:23:26 -07003032 private long getCreationTime() {
3033 final long now = System.currentTimeMillis();
3034 return (now > EPOCH_PLUS_30_YEARS) ? now : 0;
3035 }
3036
3037 private void dispatchUserAddedIntent(@NonNull UserInfo userInfo) {
3038 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
3039 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userInfo.id);
3040 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
3041 android.Manifest.permission.MANAGE_USERS);
3042 MetricsLogger.count(mContext, userInfo.isGuest() ? TRON_GUEST_CREATED
3043 : (userInfo.isDemo() ? TRON_DEMO_CREATED : TRON_USER_CREATED), 1);
3044 }
3045
3046 private boolean areGuestUsersEphemeral() {
3047 return Resources.getSystem()
3048 .getBoolean(com.android.internal.R.bool.config_guestUserEphemeral);
3049 }
3050
3051 /**
3052 * Gets a pre-created user for the given flag.
3053 *
3054 * <p>Should be used only during user creation, so the pre-created user can be used (instead of
3055 * creating and initializing a new user from scratch).
3056 */
Felipe Lemec6e015d2019-10-21 12:51:08 -07003057 // TODO(b/143092698): add unit test
Felipe Lemec1ca4412019-09-11 09:23:26 -07003058 @GuardedBy("mUsersLock")
3059 private @Nullable UserData getPreCreatedUserLU(@UserInfoFlag int flags) {
3060 if (DBG) {
3061 Slog.d(LOG_TAG, "getPreCreatedUser(): initialFlags= " + UserInfo.flagsToString(flags));
3062 }
3063 flags |= UserInfo.FLAG_FULL;
3064 if (UserInfo.isGuest(flags) && areGuestUsersEphemeral()) {
3065 flags |= UserInfo.FLAG_EPHEMERAL;
3066 }
3067 if (DBG) {
3068 Slog.d(LOG_TAG, "getPreCreatedUser(): targetFlags= " + UserInfo.flagsToString(flags));
3069 }
3070 final int userSize = mUsers.size();
3071 for (int i = 0; i < userSize; i++) {
3072 final UserData user = mUsers.valueAt(i);
3073 if (DBG) Slog.d(LOG_TAG, i + ":" + user.info.toFullString());
3074 if (user.info.preCreated
3075 && (user.info.flags & ~UserInfo.FLAG_INITIALIZED) == flags) {
3076 if (!user.info.isInitialized()) {
3077 Slog.w(LOG_TAG, "found pre-created user for flags "
3078 + "" + UserInfo.flagsToString(flags)
3079 + ", but it's not initialized yet: " + user.info.toFullString());
3080 continue;
3081 }
3082 return user;
3083 }
3084 }
3085 return null;
3086 }
3087
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003088 @VisibleForTesting
3089 UserData putUserInfo(UserInfo userInfo) {
3090 final UserData userData = new UserData();
3091 userData.info = userInfo;
3092 synchronized (mUsers) {
3093 mUsers.put(userInfo.id, userData);
3094 }
3095 return userData;
3096 }
3097
3098 @VisibleForTesting
Bookatzf56f2582019-09-04 16:06:41 -07003099 void removeUserInfo(@UserIdInt int userId) {
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003100 synchronized (mUsers) {
3101 mUsers.remove(userId);
3102 }
3103 }
3104
Amith Yamasani0b285492011-04-14 17:35:23 -07003105 /**
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003106 * @hide
3107 */
Amith Yamasani12747872015-12-07 14:19:49 -08003108 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003109 public UserInfo createRestrictedProfile(String name, int parentUserId) {
Sudheer Shanka53d41472016-06-16 09:11:08 -07003110 checkManageOrCreateUsersPermission("setupRestrictedProfile");
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07003111 final UserInfo user = createProfileForUser(
3112 name, UserInfo.FLAG_RESTRICTED, parentUserId, null);
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003113 if (user == null) {
3114 return null;
3115 }
Fyodor Kupolov9e912ba2016-02-09 18:29:43 -08003116 long identity = Binder.clearCallingIdentity();
3117 try {
3118 setUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, true, user.id);
3119 // Change the setting before applying the DISALLOW_SHARE_LOCATION restriction, otherwise
3120 // the putIntForUser() will fail.
3121 android.provider.Settings.Secure.putIntForUser(mContext.getContentResolver(),
3122 android.provider.Settings.Secure.LOCATION_MODE,
3123 android.provider.Settings.Secure.LOCATION_MODE_OFF, user.id);
3124 setUserRestriction(UserManager.DISALLOW_SHARE_LOCATION, true, user.id);
3125 } finally {
3126 Binder.restoreCallingIdentity(identity);
3127 }
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003128 return user;
3129 }
3130
3131 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07003132 * Find the current guest user. If the Guest user is partial,
3133 * then do not include it in the results as it is about to die.
Adam Lesinskieddeb492014-09-08 17:50:03 -07003134 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07003135 private UserInfo findCurrentGuestUser() {
3136 synchronized (mUsersLock) {
3137 final int size = mUsers.size();
3138 for (int i = 0; i < size; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003139 final UserInfo user = mUsers.valueAt(i).info;
Felipe Lemee35f5b02019-10-14 15:37:44 -07003140 if (user.isGuest() && !user.guestToRemove && !user.preCreated
3141 && !mRemovingUserIds.get(user.id)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003142 return user;
3143 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07003144 }
3145 }
3146 return null;
3147 }
3148
3149 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07003150 * Mark this guest user for deletion to allow us to create another guest
3151 * and switch to that user before actually removing this guest.
Bookatzf56f2582019-09-04 16:06:41 -07003152 * @param userId the userid of the current guest
Amith Yamasani1df14732014-08-29 21:37:27 -07003153 * @return whether the user could be marked for deletion
3154 */
Amith Yamasani12747872015-12-07 14:19:49 -08003155 @Override
Bookatzf56f2582019-09-04 16:06:41 -07003156 public boolean markGuestForDeletion(@UserIdInt int userId) {
Amith Yamasani1df14732014-08-29 21:37:27 -07003157 checkManageUsersPermission("Only the system can remove users");
3158 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
3159 UserManager.DISALLOW_REMOVE_USER, false)) {
3160 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
3161 return false;
3162 }
3163
3164 long ident = Binder.clearCallingIdentity();
3165 try {
Amith Yamasani12747872015-12-07 14:19:49 -08003166 final UserData userData;
Amith Yamasani1df14732014-08-29 21:37:27 -07003167 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003168 synchronized (mUsersLock) {
Bookatzf56f2582019-09-04 16:06:41 -07003169 userData = mUsers.get(userId);
3170 if (userId == 0 || userData == null || mRemovingUserIds.get(userId)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003171 return false;
3172 }
Amith Yamasani1df14732014-08-29 21:37:27 -07003173 }
Amith Yamasani12747872015-12-07 14:19:49 -08003174 if (!userData.info.isGuest()) {
Amith Yamasani1df14732014-08-29 21:37:27 -07003175 return false;
3176 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07003177 // We set this to a guest user that is to be removed. This is a temporary state
3178 // where we are allowed to add new Guest users, even if this one is still not
3179 // removed. This user will still show up in getUserInfo() calls.
3180 // If we don't get around to removing this Guest user, it will be purged on next
3181 // startup.
Amith Yamasani12747872015-12-07 14:19:49 -08003182 userData.info.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07003183 // Mark it as disabled, so that it isn't returned any more when
3184 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08003185 userData.info.flags |= UserInfo.FLAG_DISABLED;
3186 writeUserLP(userData);
Amith Yamasani1df14732014-08-29 21:37:27 -07003187 }
3188 } finally {
3189 Binder.restoreCallingIdentity(ident);
3190 }
3191 return true;
3192 }
3193
3194 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07003195 * Removes a user and all data directories created for that user. This method should be called
3196 * after the user's processes have been terminated.
Bookatzf56f2582019-09-04 16:06:41 -07003197 * @param userId the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07003198 */
Amith Yamasani12747872015-12-07 14:19:49 -08003199 @Override
Bookatzf56f2582019-09-04 16:06:41 -07003200 public boolean removeUser(@UserIdInt int userId) {
3201 Slog.i(LOG_TAG, "removeUser u" + userId);
Sudheer Shankaf5cea032016-06-08 17:13:24 -07003202 checkManageOrCreateUsersPermission("Only the system can remove users");
Esteban Talavera6c9116a2016-11-24 16:12:44 +00003203
3204 final boolean isManagedProfile;
3205 synchronized (mUsersLock) {
Bookatzf56f2582019-09-04 16:06:41 -07003206 UserInfo userInfo = getUserInfoLU(userId);
Esteban Talavera6c9116a2016-11-24 16:12:44 +00003207 isManagedProfile = userInfo != null && userInfo.isManagedProfile();
3208 }
3209 String restriction = isManagedProfile
3210 ? UserManager.DISALLOW_REMOVE_MANAGED_PROFILE : UserManager.DISALLOW_REMOVE_USER;
3211 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(restriction, false)) {
3212 Log.w(LOG_TAG, "Cannot remove user. " + restriction + " is enabled.");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04003213 return false;
3214 }
Bookatzf56f2582019-09-04 16:06:41 -07003215 return removeUserUnchecked(userId);
Nicolas Prevotdf1b87d2016-10-25 13:57:08 +01003216 }
Julia Reynolds4ac5f852014-06-23 17:38:51 -04003217
Bookatzf56f2582019-09-04 16:06:41 -07003218 private boolean removeUserUnchecked(@UserIdInt int userId) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01003219 long ident = Binder.clearCallingIdentity();
3220 try {
Amith Yamasani12747872015-12-07 14:19:49 -08003221 final UserData userData;
Fyodor Kupolov0df68cd2015-10-01 13:54:22 -07003222 int currentUser = ActivityManager.getCurrentUser();
Bookatzf56f2582019-09-04 16:06:41 -07003223 if (currentUser == userId) {
jovanaka6763a32018-12-03 17:23:20 -08003224 Log.w(LOG_TAG, "Current user cannot be removed.");
Fyodor Kupolov0df68cd2015-10-01 13:54:22 -07003225 return false;
3226 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01003227 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003228 synchronized (mUsersLock) {
Bookatzf56f2582019-09-04 16:06:41 -07003229 userData = mUsers.get(userId);
3230 if (userId == UserHandle.USER_SYSTEM) {
jovanaka6763a32018-12-03 17:23:20 -08003231 Log.e(LOG_TAG, "System user cannot be removed.");
3232 return false;
3233 }
3234
3235 if (userData == null) {
3236 Log.e(LOG_TAG, String.format(
Bookatzf56f2582019-09-04 16:06:41 -07003237 "Cannot remove user %d, invalid user id provided.", userId));
jovanaka6763a32018-12-03 17:23:20 -08003238 return false;
3239 }
3240
Bookatzf56f2582019-09-04 16:06:41 -07003241 if (mRemovingUserIds.get(userId)) {
jovanaka6763a32018-12-03 17:23:20 -08003242 Log.e(LOG_TAG, String.format(
Bookatzf56f2582019-09-04 16:06:41 -07003243 "User %d is already scheduled for removal.", userId));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003244 return false;
3245 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08003246
Bookatzf56f2582019-09-04 16:06:41 -07003247 addRemovingUserIdLocked(userId);
Fyodor Kupolov82402752015-10-28 14:54:51 -07003248 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08003249
Kenny Guyee58b4f2014-05-23 15:19:53 +01003250 // Set this to a partially created user, so that the user will be purged
3251 // on next startup, in case the runtime stops now before stopping and
3252 // removing the user completely.
Amith Yamasani12747872015-12-07 14:19:49 -08003253 userData.info.partial = true;
Kenny Guyee58b4f2014-05-23 15:19:53 +01003254 // Mark it as disabled, so that it isn't returned any more when
3255 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08003256 userData.info.flags |= UserInfo.FLAG_DISABLED;
3257 writeUserLP(userData);
Kenny Guyee58b4f2014-05-23 15:19:53 +01003258 }
Fyodor Kupolov6c96f7f2017-06-28 18:22:59 -07003259 try {
Bookatzf56f2582019-09-04 16:06:41 -07003260 mAppOpsService.removeUser(userId);
Fyodor Kupolov6c96f7f2017-06-28 18:22:59 -07003261 } catch (RemoteException e) {
jovanaka6763a32018-12-03 17:23:20 -08003262 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user.", e);
Fyodor Kupolov6c96f7f2017-06-28 18:22:59 -07003263 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01003264
Amith Yamasani12747872015-12-07 14:19:49 -08003265 if (userData.info.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
3266 && userData.info.isManagedProfile()) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01003267 // Send broadcast to notify system that the user removed was a
3268 // managed user.
Amith Yamasani12747872015-12-07 14:19:49 -08003269 sendProfileRemovedBroadcast(userData.info.profileGroupId, userData.info.id);
Kenny Guyee58b4f2014-05-23 15:19:53 +01003270 }
3271
Bookatzf56f2582019-09-04 16:06:41 -07003272 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userId);
Kenny Guyee58b4f2014-05-23 15:19:53 +01003273 int res;
3274 try {
Bookatzf56f2582019-09-04 16:06:41 -07003275 res = ActivityManager.getService().stopUser(userId, /* force= */ true,
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07003276 new IStopUserCallback.Stub() {
Kenny Guyee58b4f2014-05-23 15:19:53 +01003277 @Override
Bookatzf56f2582019-09-04 16:06:41 -07003278 public void userStopped(int userIdParam) {
3279 finishRemoveUser(userIdParam);
Kenny Guyee58b4f2014-05-23 15:19:53 +01003280 }
3281 @Override
Bookatzf56f2582019-09-04 16:06:41 -07003282 public void userStopAborted(int userIdParam) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01003283 }
3284 });
3285 } catch (RemoteException e) {
jovanaka6763a32018-12-03 17:23:20 -08003286 Log.w(LOG_TAG, "Failed to stop user during removal.", e);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003287 return false;
3288 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01003289 return res == ActivityManager.USER_OP_SUCCESS;
3290 } finally {
3291 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003292 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003293 }
3294
Andreas Gampea36dc622018-02-05 17:19:22 -08003295 @GuardedBy("mUsersLock")
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003296 @VisibleForTesting
Bookatzf56f2582019-09-04 16:06:41 -07003297 void addRemovingUserIdLocked(@UserIdInt int userId) {
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003298 // We remember deleted user IDs to prevent them from being
3299 // reused during the current boot; they can still be reused
3300 // after a reboot or recycling of userIds.
3301 mRemovingUserIds.put(userId, true);
3302 mRecentlyRemovedIds.add(userId);
3303 // Keep LRU queue of recently removed IDs for recycling
3304 if (mRecentlyRemovedIds.size() > MAX_RECENTLY_REMOVED_IDS_SIZE) {
3305 mRecentlyRemovedIds.removeFirst();
3306 }
3307 }
3308
Bookatzf56f2582019-09-04 16:06:41 -07003309 void finishRemoveUser(final @UserIdInt int userId) {
3310 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userId);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07003311 // Let other services shutdown any activity and clean up their state before completely
3312 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07003313 long ident = Binder.clearCallingIdentity();
3314 try {
3315 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
Bookatzf56f2582019-09-04 16:06:41 -07003316 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07003317 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
3318 android.Manifest.permission.MANAGE_USERS,
3319
3320 new BroadcastReceiver() {
3321 @Override
3322 public void onReceive(Context context, Intent intent) {
3323 if (DBG) {
3324 Slog.i(LOG_TAG,
3325 "USER_REMOVED broadcast sent, cleaning up user data "
Bookatzf56f2582019-09-04 16:06:41 -07003326 + userId);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07003327 }
3328 new Thread() {
Amith Yamasani12747872015-12-07 14:19:49 -08003329 @Override
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07003330 public void run() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003331 // Clean up any ActivityTaskManager state
3332 LocalServices.getService(ActivityTaskManagerInternal.class)
Bookatzf56f2582019-09-04 16:06:41 -07003333 .onUserStopped(userId);
3334 removeUserState(userId);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07003335 }
3336 }.start();
3337 }
3338 },
3339
3340 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07003341 } finally {
3342 Binder.restoreCallingIdentity(ident);
3343 }
Amith Yamasani2a003292012-08-14 18:25:45 -07003344 }
3345
Bookatzf56f2582019-09-04 16:06:41 -07003346 private void removeUserState(final @UserIdInt int userId) {
Paul Crowley91293792016-03-25 15:23:07 -07003347 try {
Bookatzf56f2582019-09-04 16:06:41 -07003348 mContext.getSystemService(StorageManager.class).destroyUserKey(userId);
Paul Crowley91293792016-03-25 15:23:07 -07003349 } catch (IllegalStateException e) {
3350 // This may be simply because the user was partially created.
Bookatzf56f2582019-09-04 16:06:41 -07003351 Slog.i(LOG_TAG, "Destroying key for user " + userId + " failed, continuing anyway", e);
Paul Crowley91293792016-03-25 15:23:07 -07003352 }
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06003353
Amith Yamasanid04aaa32016-06-13 12:09:36 -07003354 // Cleanup gatekeeper secure user id
3355 try {
3356 final IGateKeeperService gk = GateKeeper.getService();
3357 if (gk != null) {
Bookatzf56f2582019-09-04 16:06:41 -07003358 gk.clearSecureUserId(userId);
Amith Yamasanid04aaa32016-06-13 12:09:36 -07003359 }
3360 } catch (Exception ex) {
3361 Slog.w(LOG_TAG, "unable to clear GK secure user id");
3362 }
3363
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003364 // Cleanup package manager settings
Bookatzf56f2582019-09-04 16:06:41 -07003365 mPm.cleanUpUser(this, userId);
Amith Yamasanid04aaa32016-06-13 12:09:36 -07003366
3367 // Clean up all data before removing metadata
Bookatzf56f2582019-09-04 16:06:41 -07003368 mUserDataPreparer.destroyUserData(userId,
Amith Yamasanid04aaa32016-06-13 12:09:36 -07003369 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
3370
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003371 // Remove this user from the list
Fyodor Kupolov82402752015-10-28 14:54:51 -07003372 synchronized (mUsersLock) {
Bookatzf56f2582019-09-04 16:06:41 -07003373 mUsers.remove(userId);
3374 mIsUserManaged.delete(userId);
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003375 }
3376 synchronized (mUserStates) {
Bookatzf56f2582019-09-04 16:06:41 -07003377 mUserStates.delete(userId);
Makoto Onukie7927da2015-11-25 10:05:17 -08003378 }
3379 synchronized (mRestrictionsLock) {
Bookatzf56f2582019-09-04 16:06:41 -07003380 mBaseUserRestrictions.remove(userId);
3381 mAppliedUserRestrictions.remove(userId);
3382 mCachedEffectiveUserRestrictions.remove(userId);
3383 mDevicePolicyLocalUserRestrictions.remove(userId);
3384 if (mDevicePolicyGlobalUserRestrictions.get(userId) != null) {
3385 mDevicePolicyGlobalUserRestrictions.remove(userId);
Pavel Grafov6a40f092016-10-25 15:46:51 +01003386 applyUserRestrictionsForAllUsersLR();
3387 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07003388 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003389 // Update the user list
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003390 synchronized (mPackagesLock) {
3391 writeUserListLP();
3392 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06003393 // Remove user file
Bookatzf56f2582019-09-04 16:06:41 -07003394 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userId + XML_SUFFIX));
Jeff Sharkeycd575992016-03-29 14:12:49 -06003395 userFile.delete();
Fyodor Kupolov82402752015-10-28 14:54:51 -07003396 updateUserIds();
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003397 if (RELEASE_DELETED_USER_ID) {
3398 synchronized (mUsers) {
Bookatzf56f2582019-09-04 16:06:41 -07003399 mRemovingUserIds.delete(userId);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003400 }
3401 }
Amith Yamasani61f57372012-08-31 12:12:28 -07003402 }
3403
Kenny Guyf8d3a232014-05-15 16:09:52 +01003404 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01003405 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01003406 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
3407 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01003408 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
Jeff Sharkeyaf6ec292015-12-17 11:19:00 -07003409 managedProfileIntent.putExtra(Intent.EXTRA_USER_HANDLE, removedUserId);
Kenny Guyf8d3a232014-05-15 16:09:52 +01003410 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01003411 }
3412
Amith Yamasani2a003292012-08-14 18:25:45 -07003413 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07003414 public Bundle getApplicationRestrictions(String packageName) {
3415 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
3416 }
3417
3418 @Override
Bookatzf56f2582019-09-04 16:06:41 -07003419 public Bundle getApplicationRestrictionsForUser(String packageName, @UserIdInt int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003420 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07003421 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07003422 checkSystemOrRoot("get application restrictions for other user/app " + packageName);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003423 }
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003424 synchronized (mAppRestrictionsLock) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003425 // Read the restrictions from XML
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003426 return readApplicationRestrictionsLAr(packageName, userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003427 }
3428 }
3429
3430 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07003431 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Bookatzf56f2582019-09-04 16:06:41 -07003432 @UserIdInt int userId) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00003433 checkSystemOrRoot("set application restrictions");
Fyodor Kupolov0d88d542016-04-19 11:37:22 -07003434 if (restrictions != null) {
3435 restrictions.setDefusable(true);
3436 }
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003437 synchronized (mAppRestrictionsLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01003438 if (restrictions == null || restrictions.isEmpty()) {
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003439 cleanAppRestrictionsForPackageLAr(packageName, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01003440 } else {
3441 // Write the restrictions to XML
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003442 writeApplicationRestrictionsLAr(packageName, restrictions, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01003443 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003444 }
Robin Lee66e5d962014-04-09 16:44:21 +01003445
Fyodor Kupolovd2846122016-02-11 18:06:34 -08003446 // Notify package of changes via an intent - only sent to explicitly registered receivers.
3447 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
3448 changeIntent.setPackage(packageName);
3449 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3450 mContext.sendBroadcastAsUser(changeIntent, UserHandle.of(userId));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003451 }
3452
3453 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07003454 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003455 try {
3456 return mContext.getPackageManager().getApplicationInfo(packageName,
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07003457 PackageManager.MATCH_ANY_USER).uid;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003458 } catch (NameNotFoundException nnfe) {
3459 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07003460 } finally {
3461 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003462 }
3463 }
3464
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003465 @GuardedBy("mAppRestrictionsLock")
Bookatzf56f2582019-09-04 16:06:41 -07003466 private static Bundle readApplicationRestrictionsLAr(String packageName,
3467 @UserIdInt int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003468 AtomicFile restrictionsFile =
3469 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
3470 packageToRestrictionsFileName(packageName)));
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003471 return readApplicationRestrictionsLAr(restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003472 }
3473
3474 @VisibleForTesting
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003475 @GuardedBy("mAppRestrictionsLock")
3476 static Bundle readApplicationRestrictionsLAr(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07003477 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003478 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07003479 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07003480 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07003481 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003482
3483 FileInputStream fis = null;
3484 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003485 fis = restrictionsFile.openRead();
3486 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01003487 parser.setInput(fis, StandardCharsets.UTF_8.name());
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003488 XmlUtils.nextElement(parser);
3489 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003490 Slog.e(LOG_TAG, "Unable to read restrictions file "
3491 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07003492 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003493 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003494 while (parser.next() != XmlPullParser.END_DOCUMENT) {
3495 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003496 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003497 } catch (IOException|XmlPullParserException e) {
3498 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003499 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003500 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003501 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07003502 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003503 }
3504
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003505 private static void readEntry(Bundle restrictions, ArrayList<String> values,
3506 XmlPullParser parser) throws XmlPullParserException, IOException {
3507 int type = parser.getEventType();
3508 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
3509 String key = parser.getAttributeValue(null, ATTR_KEY);
3510 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
3511 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
3512 if (multiple != null) {
3513 values.clear();
3514 int count = Integer.parseInt(multiple);
3515 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
3516 if (type == XmlPullParser.START_TAG
3517 && parser.getName().equals(TAG_VALUE)) {
3518 values.add(parser.nextText().trim());
3519 count--;
3520 }
3521 }
3522 String [] valueStrings = new String[values.size()];
3523 values.toArray(valueStrings);
3524 restrictions.putStringArray(key, valueStrings);
3525 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
3526 restrictions.putBundle(key, readBundleEntry(parser, values));
3527 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
3528 final int outerDepth = parser.getDepth();
3529 ArrayList<Bundle> bundleList = new ArrayList<>();
3530 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
3531 Bundle childBundle = readBundleEntry(parser, values);
3532 bundleList.add(childBundle);
3533 }
3534 restrictions.putParcelableArray(key,
3535 bundleList.toArray(new Bundle[bundleList.size()]));
3536 } else {
3537 String value = parser.nextText().trim();
3538 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
3539 restrictions.putBoolean(key, Boolean.parseBoolean(value));
3540 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
3541 restrictions.putInt(key, Integer.parseInt(value));
3542 } else {
3543 restrictions.putString(key, value);
3544 }
3545 }
3546 }
3547 }
3548
3549 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
3550 throws IOException, XmlPullParserException {
3551 Bundle childBundle = new Bundle();
3552 final int outerDepth = parser.getDepth();
3553 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
3554 readEntry(childBundle, values, parser);
3555 }
3556 return childBundle;
3557 }
3558
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003559 @GuardedBy("mAppRestrictionsLock")
3560 private static void writeApplicationRestrictionsLAr(String packageName,
Bookatzf56f2582019-09-04 16:06:41 -07003561 Bundle restrictions, @UserIdInt int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003562 AtomicFile restrictionsFile = new AtomicFile(
3563 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07003564 packageToRestrictionsFileName(packageName)));
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003565 writeApplicationRestrictionsLAr(restrictions, restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003566 }
3567
3568 @VisibleForTesting
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003569 @GuardedBy("mAppRestrictionsLock")
3570 static void writeApplicationRestrictionsLAr(Bundle restrictions, AtomicFile restrictionsFile) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003571 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003572 try {
3573 fos = restrictionsFile.startWrite();
3574 final BufferedOutputStream bos = new BufferedOutputStream(fos);
3575
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003576 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01003577 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003578 serializer.startDocument(null, true);
3579 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
3580
3581 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003582 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003583 serializer.endTag(null, TAG_RESTRICTIONS);
3584
3585 serializer.endDocument();
3586 restrictionsFile.finishWrite(fos);
3587 } catch (Exception e) {
3588 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003589 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
3590 }
3591 }
3592
3593 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
3594 throws IOException {
3595 for (String key : restrictions.keySet()) {
3596 Object value = restrictions.get(key);
3597 serializer.startTag(null, TAG_ENTRY);
3598 serializer.attribute(null, ATTR_KEY, key);
3599
3600 if (value instanceof Boolean) {
3601 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
3602 serializer.text(value.toString());
3603 } else if (value instanceof Integer) {
3604 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
3605 serializer.text(value.toString());
3606 } else if (value == null || value instanceof String) {
3607 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
3608 serializer.text(value != null ? (String) value : "");
3609 } else if (value instanceof Bundle) {
3610 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
3611 writeBundle((Bundle) value, serializer);
3612 } else if (value instanceof Parcelable[]) {
3613 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
3614 Parcelable[] array = (Parcelable[]) value;
3615 for (Parcelable parcelable : array) {
3616 if (!(parcelable instanceof Bundle)) {
3617 throw new IllegalArgumentException("bundle-array can only hold Bundles");
3618 }
3619 serializer.startTag(null, TAG_ENTRY);
3620 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
3621 writeBundle((Bundle) parcelable, serializer);
3622 serializer.endTag(null, TAG_ENTRY);
3623 }
3624 } else {
3625 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
3626 String[] values = (String[]) value;
3627 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
3628 for (String choice : values) {
3629 serializer.startTag(null, TAG_VALUE);
3630 serializer.text(choice != null ? choice : "");
3631 serializer.endTag(null, TAG_VALUE);
3632 }
3633 }
3634 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003635 }
3636 }
3637
3638 @Override
Bookatzf56f2582019-09-04 16:06:41 -07003639 public int getUserSerialNumber(@UserIdInt int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003640 synchronized (mUsersLock) {
Bookatzf56f2582019-09-04 16:06:41 -07003641 final UserInfo userInfo = getUserInfoLU(userId);
Pavel Grafov9c295d42019-03-26 19:42:08 +00003642 return userInfo != null ? userInfo.serialNumber : -1;
Amith Yamasani2a003292012-08-14 18:25:45 -07003643 }
3644 }
3645
3646 @Override
Bookatzf56f2582019-09-04 16:06:41 -07003647 public boolean isUserNameSet(@UserIdInt int userId) {
Fyodor Kupolov605b12a2017-05-10 15:58:09 -07003648 synchronized (mUsersLock) {
Bookatzf56f2582019-09-04 16:06:41 -07003649 final UserInfo userInfo = getUserInfoLU(userId);
Fyodor Kupolov605b12a2017-05-10 15:58:09 -07003650 return userInfo != null && userInfo.name != null;
3651 }
3652 }
3653
3654 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07003655 public int getUserHandle(int userSerialNumber) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003656 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07003657 for (int userId : mUserIds) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003658 UserInfo info = getUserInfoLU(userId);
Kenny Guy945f8832015-02-10 15:17:26 +00003659 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07003660 }
3661 // Not found
3662 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07003663 }
3664 }
3665
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003666 @Override
Bookatzf56f2582019-09-04 16:06:41 -07003667 public long getUserCreationTime(@UserIdInt int userId) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003668 int callingUserId = UserHandle.getCallingUserId();
3669 UserInfo userInfo = null;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003670 synchronized (mUsersLock) {
Bookatzf56f2582019-09-04 16:06:41 -07003671 if (callingUserId == userId) {
3672 userInfo = getUserInfoLU(userId);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003673 } else {
Bookatzf56f2582019-09-04 16:06:41 -07003674 UserInfo parent = getProfileParentLU(userId);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003675 if (parent != null && parent.id == callingUserId) {
Bookatzf56f2582019-09-04 16:06:41 -07003676 userInfo = getUserInfoLU(userId);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003677 }
3678 }
3679 }
3680 if (userInfo == null) {
Bookatzf56f2582019-09-04 16:06:41 -07003681 throw new SecurityException("userId can only be the calling user or a managed "
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003682 + "profile associated with this user");
3683 }
3684 return userInfo.creationTime;
3685 }
3686
Amith Yamasani0b285492011-04-14 17:35:23 -07003687 /**
3688 * Caches the list of user ids in an array, adjusting the array size when necessary.
3689 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07003690 private void updateUserIds() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003691 int num = 0;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003692 synchronized (mUsersLock) {
3693 final int userSize = mUsers.size();
3694 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003695 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003696 num++;
3697 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003698 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07003699 final int[] newUsers = new int[num];
3700 int n = 0;
3701 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003702 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003703 newUsers[n++] = mUsers.keyAt(i);
3704 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003705 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07003706 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07003707 }
3708 }
3709
3710 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003711 * Called right before a user is started. This gives us a chance to prepare
3712 * app storage and apply any user restrictions.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003713 */
Bookatzf56f2582019-09-04 16:06:41 -07003714 public void onBeforeStartUser(@UserIdInt int userId) {
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003715 UserInfo userInfo = getUserInfo(userId);
3716 if (userInfo == null) {
3717 return;
3718 }
Felipe Leme3aad1be2019-05-31 11:43:12 -07003719 TimingsTraceAndSlog t = new TimingsTraceAndSlog();
3720 t.traceBegin("onBeforeStartUser-" + userId);
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003721 final int userSerial = userInfo.serialNumber;
3722 // Migrate only if build fingerprints mismatch
3723 boolean migrateAppsData = !Build.FINGERPRINT.equals(userInfo.lastLoggedInFingerprint);
Felipe Leme3aad1be2019-05-31 11:43:12 -07003724 t.traceBegin("prepareUserData");
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -08003725 mUserDataPreparer.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_DE);
Felipe Leme3aad1be2019-05-31 11:43:12 -07003726 t.traceEnd();
3727 t.traceBegin("reconcileAppsData");
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003728 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_DE, migrateAppsData);
Felipe Leme3aad1be2019-05-31 11:43:12 -07003729 t.traceEnd();
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003730
3731 if (userId != UserHandle.USER_SYSTEM) {
Felipe Leme3aad1be2019-05-31 11:43:12 -07003732 t.traceBegin("applyUserRestrictions");
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003733 synchronized (mRestrictionsLock) {
3734 applyUserRestrictionsLR(userId);
3735 }
Felipe Leme3aad1be2019-05-31 11:43:12 -07003736 t.traceEnd();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003737 }
Felipe Leme3aad1be2019-05-31 11:43:12 -07003738 t.traceEnd(); // onBeforeStartUser
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003739 }
3740
3741 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003742 * Called right before a user is unlocked. This gives us a chance to prepare
3743 * app storage.
3744 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003745 public void onBeforeUnlockUser(@UserIdInt int userId) {
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003746 UserInfo userInfo = getUserInfo(userId);
3747 if (userInfo == null) {
3748 return;
3749 }
3750 final int userSerial = userInfo.serialNumber;
3751 // Migrate only if build fingerprints mismatch
3752 boolean migrateAppsData = !Build.FINGERPRINT.equals(userInfo.lastLoggedInFingerprint);
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -08003753 mUserDataPreparer.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_CE);
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003754 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_CE, migrateAppsData);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003755 }
3756
3757 /**
Fyodor Kupolov50979d12017-01-27 17:36:32 -08003758 * Examine all users present on given mounted volume, and destroy data
3759 * belonging to users that are no longer valid, or whose user ID has been
3760 * recycled.
3761 */
3762 void reconcileUsers(String volumeUuid) {
3763 mUserDataPreparer.reconcileUsers(volumeUuid, getUsers(true /* excludeDying */));
3764 }
3765
3766 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07003767 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasanieb437d42016-04-29 09:31:25 -07003768 * This is called with ActivityManagerService lock held.
Amith Yamasani920ace02012-09-20 22:15:37 -07003769 * @param userId the user that was just foregrounded
3770 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003771 public void onUserLoggedIn(@UserIdInt int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -08003772 UserData userData = getUserDataNoChecks(userId);
3773 if (userData == null || userData.info.partial) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003774 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
3775 return;
3776 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003777
3778 final long now = System.currentTimeMillis();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003779 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani12747872015-12-07 14:19:49 -08003780 userData.info.lastLoggedInTime = now;
Amith Yamasani920ace02012-09-20 22:15:37 -07003781 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003782 userData.info.lastLoggedInFingerprint = Build.FINGERPRINT;
3783 scheduleWriteUser(userData);
Amith Yamasani920ace02012-09-20 22:15:37 -07003784 }
3785
3786 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07003787 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani0b285492011-04-14 17:35:23 -07003788 */
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003789 @VisibleForTesting
3790 int getNextAvailableId() {
3791 int nextId;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003792 synchronized (mUsersLock) {
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003793 nextId = scanNextAvailableIdLocked();
3794 if (nextId >= 0) {
3795 return nextId;
3796 }
3797 // All ids up to MAX_USER_ID were used. Remove all mRemovingUserIds,
3798 // except most recently removed
3799 if (mRemovingUserIds.size() > 0) {
3800 Slog.i(LOG_TAG, "All available IDs are used. Recycling LRU ids.");
3801 mRemovingUserIds.clear();
3802 for (Integer recentlyRemovedId : mRecentlyRemovedIds) {
3803 mRemovingUserIds.put(recentlyRemovedId, true);
Amith Yamasani195263742012-08-21 15:40:12 -07003804 }
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003805 nextId = scanNextAvailableIdLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003806 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003807 }
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003808 if (nextId < 0) {
3809 throw new IllegalStateException("No user id available!");
3810 }
3811 return nextId;
3812 }
3813
Andreas Gampea36dc622018-02-05 17:19:22 -08003814 @GuardedBy("mUsersLock")
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003815 private int scanNextAvailableIdLocked() {
3816 for (int i = MIN_USER_ID; i < MAX_USER_ID; i++) {
3817 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
3818 return i;
3819 }
3820 }
3821 return -1;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003822 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003823
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003824 private static String packageToRestrictionsFileName(String packageName) {
Amith Yamasanifc95e702013-09-26 13:20:17 -07003825 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
3826 }
3827
Amith Yamasani920ace02012-09-20 22:15:37 -07003828 @Override
Bookatzf56f2582019-09-04 16:06:41 -07003829 public void setSeedAccountData(@UserIdInt int userId, String accountName, String accountType,
Amith Yamasani12747872015-12-07 14:19:49 -08003830 PersistableBundle accountOptions, boolean persist) {
3831 checkManageUsersPermission("Require MANAGE_USERS permission to set user seed data");
3832 synchronized (mPackagesLock) {
3833 final UserData userData;
3834 synchronized (mUsersLock) {
3835 userData = getUserDataLU(userId);
3836 if (userData == null) {
3837 Slog.e(LOG_TAG, "No such user for settings seed data u=" + userId);
3838 return;
3839 }
3840 userData.seedAccountName = accountName;
3841 userData.seedAccountType = accountType;
3842 userData.seedAccountOptions = accountOptions;
3843 userData.persistSeedData = persist;
3844 }
3845 if (persist) {
3846 writeUserLP(userData);
3847 }
3848 }
3849 }
3850
3851 @Override
3852 public String getSeedAccountName() throws RemoteException {
3853 checkManageUsersPermission("Cannot get seed account information");
3854 synchronized (mUsersLock) {
3855 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3856 return userData.seedAccountName;
3857 }
3858 }
3859
3860 @Override
3861 public String getSeedAccountType() throws RemoteException {
3862 checkManageUsersPermission("Cannot get seed account information");
3863 synchronized (mUsersLock) {
3864 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3865 return userData.seedAccountType;
3866 }
3867 }
3868
3869 @Override
3870 public PersistableBundle getSeedAccountOptions() throws RemoteException {
3871 checkManageUsersPermission("Cannot get seed account information");
3872 synchronized (mUsersLock) {
3873 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3874 return userData.seedAccountOptions;
3875 }
3876 }
3877
3878 @Override
3879 public void clearSeedAccountData() throws RemoteException {
3880 checkManageUsersPermission("Cannot clear seed account information");
3881 synchronized (mPackagesLock) {
3882 UserData userData;
3883 synchronized (mUsersLock) {
3884 userData = getUserDataLU(UserHandle.getCallingUserId());
3885 if (userData == null) return;
3886 userData.clearSeedAccountData();
3887 }
3888 writeUserLP(userData);
3889 }
3890 }
3891
3892 @Override
3893 public boolean someUserHasSeedAccount(String accountName, String accountType)
3894 throws RemoteException {
3895 checkManageUsersPermission("Cannot check seed account information");
3896 synchronized (mUsersLock) {
3897 final int userSize = mUsers.size();
3898 for (int i = 0; i < userSize; i++) {
3899 final UserData data = mUsers.valueAt(i);
3900 if (data.info.isInitialized()) continue;
3901 if (data.seedAccountName == null || !data.seedAccountName.equals(accountName)) {
3902 continue;
3903 }
3904 if (data.seedAccountType == null || !data.seedAccountType.equals(accountType)) {
3905 continue;
3906 }
3907 return true;
3908 }
3909 }
3910 return false;
3911 }
3912
3913 @Override
Todd Kennedy60459ab2015-10-30 11:32:16 -07003914 public void onShellCommand(FileDescriptor in, FileDescriptor out,
Dianne Hackborn354736e2016-08-22 17:00:05 -07003915 FileDescriptor err, String[] args, ShellCallback callback,
3916 ResultReceiver resultReceiver) {
3917 (new Shell()).exec(this, in, out, err, args, callback, resultReceiver);
Todd Kennedy60459ab2015-10-30 11:32:16 -07003918 }
3919
3920 int onShellCommand(Shell shell, String cmd) {
3921 if (cmd == null) {
3922 return shell.handleDefaultCommands(cmd);
3923 }
3924
3925 final PrintWriter pw = shell.getOutPrintWriter();
3926 try {
3927 switch(cmd) {
3928 case "list":
Felipe Lemec1ca4412019-09-11 09:23:26 -07003929 return runList(pw, shell);
Hui Yu8ba65972018-04-16 18:45:48 -07003930 default:
3931 return shell.handleDefaultCommands(cmd);
Todd Kennedy60459ab2015-10-30 11:32:16 -07003932 }
3933 } catch (RemoteException e) {
3934 pw.println("Remote exception: " + e);
3935 }
3936 return -1;
3937 }
3938
Felipe Lemec1ca4412019-09-11 09:23:26 -07003939 private int runList(PrintWriter pw, Shell shell) throws RemoteException {
3940 boolean all = false;
3941 boolean verbose = false;
3942 String opt;
3943 while ((opt = shell.getNextOption()) != null) {
3944 switch (opt) {
3945 case "-v":
3946 verbose = true;
3947 break;
3948 case "--all":
3949 all = true;
3950 break;
3951 default:
3952 pw.println("Invalid option: " + opt);
3953 return -1;
3954 }
3955 }
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003956 final IActivityManager am = ActivityManager.getService();
Felipe Lemec1ca4412019-09-11 09:23:26 -07003957 final List<UserInfo> users = getUsers(/* excludePartial= */ !all,
3958 /* excludingDying=*/ false, /* excludePreCreated= */ !all);
Todd Kennedy60459ab2015-10-30 11:32:16 -07003959 if (users == null) {
3960 pw.println("Error: couldn't get users");
3961 return 1;
3962 } else {
Felipe Lemec1ca4412019-09-11 09:23:26 -07003963 final int size = users.size();
3964 int currentUser = UserHandle.USER_NULL;
3965 if (verbose) {
3966 pw.printf("%d users:\n\n", size);
3967 currentUser = am.getCurrentUser().id;
3968 } else {
3969 // NOTE: the standard "list users" command is used by integration tests and
3970 // hence should not be changed. If you need to add more info, use the
3971 // verbose option.
3972 pw.println("Users:");
3973 }
3974 for (int i = 0; i < size; i++) {
3975 final UserInfo user = users.get(i);
3976 final boolean running = am.isUserRunning(user.id, 0);
3977 final boolean current = user.id == currentUser;
3978 if (verbose) {
3979 pw.printf("%d: id=%d, name=%s, flags=%s%s%s%s%s\n", i, user.id, user.name,
3980 UserInfo.flagsToString(user.flags),
3981 running ? " (running)" : "",
3982 user.partial ? " (partial)" : "",
3983 user.preCreated ? " (pre-created)" : "",
3984 current ? " (current)" : "");
3985 } else {
3986 // NOTE: the standard "list users" command is used by integration tests and
3987 // hence should not be changed. If you need to add more info, use the
3988 // verbose option.
3989 pw.printf("\t%s%s\n", user, running ? " running" : "");
3990 }
Todd Kennedy60459ab2015-10-30 11:32:16 -07003991 }
3992 return 0;
3993 }
3994 }
3995
3996 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -07003997 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06003998 if (!DumpUtils.checkDumpPermission(mContext, LOG_TAG, pw)) return;
Amith Yamasani920ace02012-09-20 22:15:37 -07003999
4000 long now = System.currentTimeMillis();
Makoto Onuki73dded22017-12-20 13:14:48 +09004001 final long nowRealtime = SystemClock.elapsedRealtime();
Felipe Lemed7b88382019-06-12 17:40:53 -07004002
Felipe Leme5b8dc762019-10-04 16:23:16 -07004003 final ActivityManagerInternal amInternal = LocalServices
4004 .getService(ActivityManagerInternal.class);
4005 pw.print("Current user: ");
4006 if (amInternal != null) {
4007 pw.println(amInternal.getCurrentUserId());
4008 } else {
4009 pw.println("N/A");
4010 }
Felipe Lemed7b88382019-06-12 17:40:53 -07004011
Amith Yamasani920ace02012-09-20 22:15:37 -07004012 StringBuilder sb = new StringBuilder();
4013 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07004014 synchronized (mUsersLock) {
4015 pw.println("Users:");
4016 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08004017 UserData userData = mUsers.valueAt(i);
4018 if (userData == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07004019 continue;
4020 }
Amith Yamasani12747872015-12-07 14:19:49 -08004021 UserInfo userInfo = userData.info;
4022 final int userId = userInfo.id;
4023 pw.print(" "); pw.print(userInfo);
4024 pw.print(" serialNo="); pw.print(userInfo.serialNumber);
Felipe Lemed7b88382019-06-12 17:40:53 -07004025 pw.print(" isPrimary="); pw.print(userInfo.isPrimary());
Makoto Onukie7927da2015-11-25 10:05:17 -08004026 if (mRemovingUserIds.get(userId)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07004027 pw.print(" <removing> ");
4028 }
Amith Yamasani12747872015-12-07 14:19:49 -08004029 if (userInfo.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07004030 pw.print(" <partial>");
4031 }
Felipe Lemec1ca4412019-09-11 09:23:26 -07004032 if (userInfo.preCreated) {
4033 pw.print(" <pre-created>");
4034 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07004035 pw.println();
Felipe Lemee5434c32019-08-13 09:28:33 -07004036 pw.print(" Flags: "); pw.print(userInfo.flags); pw.print(" (");
4037 pw.print(UserInfo.flagsToString(userInfo.flags)); pw.println(")");
Makoto Onuki88aef752017-03-29 16:52:03 -07004038 pw.print(" State: ");
4039 final int state;
4040 synchronized (mUserStates) {
4041 state = mUserStates.get(userId, -1);
4042 }
4043 pw.println(UserState.stateToString(state));
Fyodor Kupolov82402752015-10-28 14:54:51 -07004044 pw.print(" Created: ");
Makoto Onuki73dded22017-12-20 13:14:48 +09004045 dumpTimeAgo(pw, sb, now, userInfo.creationTime);
4046
Fyodor Kupolov82402752015-10-28 14:54:51 -07004047 pw.print(" Last logged in: ");
Makoto Onuki73dded22017-12-20 13:14:48 +09004048 dumpTimeAgo(pw, sb, now, userInfo.lastLoggedInTime);
4049
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06004050 pw.print(" Last logged in fingerprint: ");
4051 pw.println(userInfo.lastLoggedInFingerprint);
Makoto Onuki73dded22017-12-20 13:14:48 +09004052
4053 pw.print(" Start time: ");
4054 dumpTimeAgo(pw, sb, nowRealtime, userData.startRealtime);
4055
4056 pw.print(" Unlock time: ");
4057 dumpTimeAgo(pw, sb, nowRealtime, userData.unlockRealtime);
4058
Makoto Onukie7927da2015-11-25 10:05:17 -08004059 pw.print(" Has profile owner: ");
4060 pw.println(mIsUserManaged.get(userId));
Fyodor Kupolov82402752015-10-28 14:54:51 -07004061 pw.println(" Restrictions:");
4062 synchronized (mRestrictionsLock) {
4063 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08004064 pw, " ", mBaseUserRestrictions.get(userInfo.id));
Pavel Grafov6a40f092016-10-25 15:46:51 +01004065 pw.println(" Device policy global restrictions:");
4066 UserRestrictionsUtils.dumpRestrictions(
4067 pw, " ", mDevicePolicyGlobalUserRestrictions.get(userInfo.id));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08004068 pw.println(" Device policy local restrictions:");
4069 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08004070 pw, " ", mDevicePolicyLocalUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07004071 pw.println(" Effective restrictions:");
4072 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08004073 pw, " ", mCachedEffectiveUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07004074 }
Amith Yamasani12747872015-12-07 14:19:49 -08004075
4076 if (userData.account != null) {
4077 pw.print(" Account name: " + userData.account);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08004078 pw.println();
4079 }
Amith Yamasani12747872015-12-07 14:19:49 -08004080
4081 if (userData.seedAccountName != null) {
4082 pw.print(" Seed account name: " + userData.seedAccountName);
4083 pw.println();
4084 if (userData.seedAccountType != null) {
4085 pw.print(" account type: " + userData.seedAccountType);
4086 pw.println();
4087 }
4088 if (userData.seedAccountOptions != null) {
4089 pw.print(" account options exist");
4090 pw.println();
4091 }
4092 }
Amith Yamasani920ace02012-09-20 22:15:37 -07004093 }
Amith Yamasani920ace02012-09-20 22:15:37 -07004094 }
Amith Yamasani12747872015-12-07 14:19:49 -08004095 pw.println();
Pavel Grafov6a40f092016-10-25 15:46:51 +01004096 pw.println(" Device owner id:" + mDeviceOwnerUserId);
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01004097 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08004098 pw.println(" Guest restrictions:");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08004099 synchronized (mGuestRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08004100 UserRestrictionsUtils.dumpRestrictions(pw, " ", mGuestRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08004101 }
Makoto Onukie7927da2015-11-25 10:05:17 -08004102 synchronized (mUsersLock) {
4103 pw.println();
4104 pw.println(" Device managed: " + mIsDeviceManaged);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07004105 if (mRemovingUserIds.size() > 0) {
4106 pw.println();
4107 pw.println(" Recently removed userIds: " + mRecentlyRemovedIds);
4108 }
Makoto Onukie7927da2015-11-25 10:05:17 -08004109 }
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00004110 synchronized (mUserStates) {
4111 pw.println(" Started users state: " + mUserStates);
4112 }
Felipe Lemed7b88382019-06-12 17:40:53 -07004113 } // synchronized (mPackagesLock)
4114
4115 // Dump some capabilities
4116 pw.println();
Felipe Lemec1ca4412019-09-11 09:23:26 -07004117 pw.print(" Max users: " + UserManager.getMaxSupportedUsers());
4118 pw.println(" (limit reached: " + isUserLimitReached() + ")");
Felipe Lemed7b88382019-06-12 17:40:53 -07004119 pw.println(" Supports switchable users: " + UserManager.supportsMultipleUsers());
Felipe Lemec1ca4412019-09-11 09:23:26 -07004120 pw.println(" All guests ephemeral: " + areGuestUsersEphemeral());
Felipe Lemed7b88382019-06-12 17:40:53 -07004121 pw.println(" Is split-system user: " + UserManager.isSplitSystemUser());
Felipe Lemee5434c32019-08-13 09:28:33 -07004122 pw.println(" Is headless-system mode: " + UserManager.isHeadlessSystemUserMode());
4123 pw.println(" User version: " + mUserVersion);
Bookatz04d7ae52019-08-05 14:07:12 -07004124
4125 // Dump package whitelist
4126 pw.println();
4127 mSystemPackageInstaller.dump(pw);
Amith Yamasani920ace02012-09-20 22:15:37 -07004128 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08004129
Makoto Onuki73dded22017-12-20 13:14:48 +09004130 private static void dumpTimeAgo(PrintWriter pw, StringBuilder sb, long nowTime, long time) {
4131 if (time == 0) {
4132 pw.println("<unknown>");
4133 } else {
4134 sb.setLength(0);
4135 TimeUtils.formatDuration(nowTime - time, sb);
4136 sb.append(" ago");
4137 pw.println(sb);
4138 }
4139 }
4140
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08004141 final class MainHandler extends Handler {
4142
4143 @Override
4144 public void handleMessage(Message msg) {
4145 switch (msg.what) {
4146 case WRITE_USER_MSG:
4147 removeMessages(WRITE_USER_MSG, msg.obj);
4148 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08004149 int userId = ((UserData) msg.obj).info.id;
4150 UserData userData = getUserDataNoChecks(userId);
4151 if (userData != null) {
4152 writeUserLP(userData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08004153 }
4154 }
4155 }
4156 }
4157 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07004158
4159 /**
4160 * @param userId
4161 * @return whether the user has been initialized yet
4162 */
Bookatzf56f2582019-09-04 16:06:41 -07004163 boolean isUserInitialized(@UserIdInt int userId) {
Todd Kennedy0eb97382017-10-03 16:57:22 -07004164 return mLocalService.isUserInitialized(userId);
Amith Yamasanibb054c92015-07-09 14:16:27 -07004165 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07004166
4167 private class LocalService extends UserManagerInternal {
Makoto Onuki068c54a2015-10-13 14:34:03 -07004168 @Override
Bookatzf56f2582019-09-04 16:06:41 -07004169 public void setDevicePolicyUserRestrictions(@UserIdInt int userId,
4170 @Nullable Bundle restrictions, boolean isDeviceOwner, int cameraRestrictionScope) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01004171 UserManagerService.this.setDevicePolicyUserRestrictionsInner(userId, restrictions,
4172 isDeviceOwner, cameraRestrictionScope);
Makoto Onuki068c54a2015-10-13 14:34:03 -07004173 }
4174
4175 @Override
Bookatzf56f2582019-09-04 16:06:41 -07004176 public Bundle getBaseUserRestrictions(@UserIdInt int userId) {
Makoto Onuki068c54a2015-10-13 14:34:03 -07004177 synchronized (mRestrictionsLock) {
4178 return mBaseUserRestrictions.get(userId);
4179 }
4180 }
4181
4182 @Override
4183 public void setBaseUserRestrictionsByDpmsForMigration(
Bookatzf56f2582019-09-04 16:06:41 -07004184 @UserIdInt int userId, Bundle baseRestrictions) {
Makoto Onuki068c54a2015-10-13 14:34:03 -07004185 synchronized (mRestrictionsLock) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01004186 if (updateRestrictionsIfNeededLR(
4187 userId, new Bundle(baseRestrictions), mBaseUserRestrictions)) {
4188 invalidateEffectiveUserRestrictionsLR(userId);
4189 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07004190 }
4191
Amith Yamasani12747872015-12-07 14:19:49 -08004192 final UserData userData = getUserDataNoChecks(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07004193 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08004194 if (userData != null) {
4195 writeUserLP(userData);
Makoto Onuki068c54a2015-10-13 14:34:03 -07004196 } else {
4197 Slog.w(LOG_TAG, "UserInfo not found for " + userId);
4198 }
4199 }
4200 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08004201
4202 @Override
Bookatzf56f2582019-09-04 16:06:41 -07004203 public boolean getUserRestriction(@UserIdInt int userId, String key) {
Makoto Onukid45a4a22015-11-02 17:17:38 -08004204 return getUserRestrictions(userId).getBoolean(key);
4205 }
4206
4207 @Override
4208 public void addUserRestrictionsListener(UserRestrictionsListener listener) {
4209 synchronized (mUserRestrictionsListeners) {
4210 mUserRestrictionsListeners.add(listener);
4211 }
4212 }
4213
4214 @Override
4215 public void removeUserRestrictionsListener(UserRestrictionsListener listener) {
4216 synchronized (mUserRestrictionsListeners) {
4217 mUserRestrictionsListeners.remove(listener);
4218 }
4219 }
Makoto Onukie7927da2015-11-25 10:05:17 -08004220
4221 @Override
4222 public void setDeviceManaged(boolean isManaged) {
4223 synchronized (mUsersLock) {
4224 mIsDeviceManaged = isManaged;
4225 }
4226 }
4227
4228 @Override
Rubin Xu0f1e56d2019-08-23 13:34:25 +01004229 public boolean isDeviceManaged() {
4230 synchronized (mUsersLock) {
4231 return mIsDeviceManaged;
4232 }
4233 }
4234
4235 @Override
Bookatzf56f2582019-09-04 16:06:41 -07004236 public void setUserManaged(@UserIdInt int userId, boolean isManaged) {
Makoto Onukie7927da2015-11-25 10:05:17 -08004237 synchronized (mUsersLock) {
4238 mIsUserManaged.put(userId, isManaged);
4239 }
4240 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01004241
4242 @Override
Rubin Xu0f1e56d2019-08-23 13:34:25 +01004243 public boolean isUserManaged(@UserIdInt int userId) {
4244 synchronized (mUsersLock) {
4245 return mIsUserManaged.get(userId);
4246 }
4247 }
4248
4249 @Override
Bookatzf56f2582019-09-04 16:06:41 -07004250 public void setUserIcon(@UserIdInt int userId, Bitmap bitmap) {
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01004251 long ident = Binder.clearCallingIdentity();
4252 try {
4253 synchronized (mPackagesLock) {
4254 UserData userData = getUserDataNoChecks(userId);
4255 if (userData == null || userData.info.partial) {
4256 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
4257 return;
4258 }
4259 writeBitmapLP(userData.info, bitmap);
4260 writeUserLP(userData);
4261 }
4262 sendUserInfoChangedBroadcast(userId);
4263 } finally {
4264 Binder.restoreCallingIdentity(ident);
4265 }
4266 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01004267
4268 @Override
4269 public void setForceEphemeralUsers(boolean forceEphemeralUsers) {
4270 synchronized (mUsersLock) {
4271 mForceEphemeralUsers = forceEphemeralUsers;
4272 }
4273 }
4274
4275 @Override
4276 public void removeAllUsers() {
4277 if (UserHandle.USER_SYSTEM == ActivityManager.getCurrentUser()) {
4278 // Remove the non-system users straight away.
4279 removeNonSystemUsers();
4280 } else {
4281 // Switch to the system user first and then remove the other users.
4282 BroadcastReceiver userSwitchedReceiver = new BroadcastReceiver() {
4283 @Override
4284 public void onReceive(Context context, Intent intent) {
4285 int userId =
4286 intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
4287 if (userId != UserHandle.USER_SYSTEM) {
4288 return;
4289 }
4290 mContext.unregisterReceiver(this);
4291 removeNonSystemUsers();
4292 }
4293 };
4294 IntentFilter userSwitchedFilter = new IntentFilter();
4295 userSwitchedFilter.addAction(Intent.ACTION_USER_SWITCHED);
4296 mContext.registerReceiver(
4297 userSwitchedReceiver, userSwitchedFilter, null, mHandler);
4298
4299 // Switch to the system user.
4300 ActivityManager am =
4301 (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
4302 am.switchUser(UserHandle.USER_SYSTEM);
4303 }
4304 }
phweisse9c44062016-02-10 12:57:38 +01004305
4306 @Override
Bookatzf56f2582019-09-04 16:06:41 -07004307 public void onEphemeralUserStop(@UserIdInt int userId) {
Lenka Trochtova1ddda472016-02-12 10:42:12 +01004308 synchronized (mUsersLock) {
4309 UserInfo userInfo = getUserInfoLU(userId);
4310 if (userInfo != null && userInfo.isEphemeral()) {
4311 // Do not allow switching back to the ephemeral user again as the user is going
4312 // to be deleted.
4313 userInfo.flags |= UserInfo.FLAG_DISABLED;
4314 if (userInfo.isGuest()) {
4315 // Indicate that the guest will be deleted after it stops.
4316 userInfo.guestToRemove = true;
4317 }
4318 }
4319 }
4320 }
4321
4322 @Override
Alex Chaub6a9f942017-11-07 11:28:56 +08004323 public UserInfo createUserEvenWhenDisallowed(String name, int flags,
4324 String[] disallowedPackages) {
4325 UserInfo user = createUserInternalUnchecked(name, flags, UserHandle.USER_NULL,
Felipe Lemec1ca4412019-09-11 09:23:26 -07004326 /* preCreated= */ false, disallowedPackages);
phweisse9c44062016-02-10 12:57:38 +01004327 // Keep this in sync with UserManager.createUser
Christine Franks97a54802017-08-09 10:06:43 -07004328 if (user != null && !user.isAdmin() && !user.isDemo()) {
phweisse9c44062016-02-10 12:57:38 +01004329 setUserRestriction(UserManager.DISALLOW_SMS, true, user.id);
4330 setUserRestriction(UserManager.DISALLOW_OUTGOING_CALLS, true, user.id);
4331 }
4332 return user;
4333 }
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07004334
4335 @Override
Bookatzf56f2582019-09-04 16:06:41 -07004336 public boolean removeUserEvenWhenDisallowed(@UserIdInt int userId) {
Nicolas Prevotdf1b87d2016-10-25 13:57:08 +01004337 return removeUserUnchecked(userId);
4338 }
4339
4340 @Override
Bookatzf56f2582019-09-04 16:06:41 -07004341 public boolean isUserRunning(@UserIdInt int userId) {
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00004342 synchronized (mUserStates) {
4343 return mUserStates.get(userId, -1) >= 0;
4344 }
4345 }
4346
4347 @Override
Bookatzf56f2582019-09-04 16:06:41 -07004348 public void setUserState(@UserIdInt int userId, int userState) {
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00004349 synchronized (mUserStates) {
4350 mUserStates.put(userId, userState);
4351 }
4352 }
4353
4354 @Override
Bookatzf56f2582019-09-04 16:06:41 -07004355 public void removeUserState(@UserIdInt int userId) {
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00004356 synchronized (mUserStates) {
4357 mUserStates.delete(userId);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07004358 }
4359 }
4360
4361 @Override
Michael Wachenschwanz3f2b6552017-05-15 13:53:09 -07004362 public int[] getUserIds() {
4363 return UserManagerService.this.getUserIds();
4364 }
4365
4366 @Override
Bookatzf56f2582019-09-04 16:06:41 -07004367 public boolean isUserUnlockingOrUnlocked(@UserIdInt int userId) {
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07004368 int state;
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00004369 synchronized (mUserStates) {
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07004370 state = mUserStates.get(userId, -1);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07004371 }
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07004372 // Special case, in the stopping/shutdown state user key can still be unlocked
4373 if (state == UserState.STATE_STOPPING || state == UserState.STATE_SHUTDOWN) {
4374 return StorageManager.isUserKeyUnlocked(userId);
4375 }
4376 return (state == UserState.STATE_RUNNING_UNLOCKING)
4377 || (state == UserState.STATE_RUNNING_UNLOCKED);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07004378 }
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08004379
4380 @Override
Bookatzf56f2582019-09-04 16:06:41 -07004381 public boolean isUserUnlocked(@UserIdInt int userId) {
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07004382 int state;
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08004383 synchronized (mUserStates) {
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07004384 state = mUserStates.get(userId, -1);
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08004385 }
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07004386 // Special case, in the stopping/shutdown state user key can still be unlocked
4387 if (state == UserState.STATE_STOPPING || state == UserState.STATE_SHUTDOWN) {
4388 return StorageManager.isUserKeyUnlocked(userId);
4389 }
4390 return state == UserState.STATE_RUNNING_UNLOCKED;
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08004391 }
Todd Kennedy0eb97382017-10-03 16:57:22 -07004392
4393 @Override
Bookatzf56f2582019-09-04 16:06:41 -07004394 public boolean isUserInitialized(@UserIdInt int userId) {
Todd Kennedy0eb97382017-10-03 16:57:22 -07004395 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
4396 }
4397
4398 @Override
Bookatzf56f2582019-09-04 16:06:41 -07004399 public boolean exists(@UserIdInt int userId) {
Todd Kennedy0eb97382017-10-03 16:57:22 -07004400 return getUserInfoNoChecks(userId) != null;
4401 }
Sunny Goyal145c8f82018-02-15 14:27:09 -08004402
4403 @Override
4404 public boolean isProfileAccessible(int callingUserId, int targetUserId, String debugMsg,
4405 boolean throwSecurityException) {
4406 if (targetUserId == callingUserId) {
4407 return true;
4408 }
4409 synchronized (mUsersLock) {
4410 UserInfo callingUserInfo = getUserInfoLU(callingUserId);
4411 if (callingUserInfo == null || callingUserInfo.isManagedProfile()) {
4412 if (throwSecurityException) {
4413 throw new SecurityException(
4414 debugMsg + " for another profile "
4415 + targetUserId + " from " + callingUserId);
4416 }
4417 }
4418
4419 UserInfo targetUserInfo = getUserInfoLU(targetUserId);
4420 if (targetUserInfo == null || !targetUserInfo.isEnabled()) {
4421 // Do not throw any exception here as this could happen due to race conditions
4422 // between the system updating its state and the client getting notified.
4423 if (throwSecurityException) {
4424 Slog.w(LOG_TAG, debugMsg + " for disabled profile "
4425 + targetUserId + " from " + callingUserId);
4426 }
4427 return false;
4428 }
4429
4430 if (targetUserInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID ||
4431 targetUserInfo.profileGroupId != callingUserInfo.profileGroupId) {
4432 if (throwSecurityException) {
4433 throw new SecurityException(
4434 debugMsg + " for unrelated profile " + targetUserId);
4435 }
4436 return false;
4437 }
4438 }
4439 return true;
4440 }
4441
4442 @Override
Bookatzf56f2582019-09-04 16:06:41 -07004443 public int getProfileParentId(@UserIdInt int userId) {
Sunny Goyal145c8f82018-02-15 14:27:09 -08004444 synchronized (mUsersLock) {
4445 UserInfo profileParent = getProfileParentLU(userId);
4446 if (profileParent == null) {
4447 return userId;
4448 }
4449 return profileParent.id;
4450 }
4451 }
yuemingw1d13eae2018-01-30 17:27:54 +00004452
4453 @Override
4454 public boolean isSettingRestrictedForUser(String setting, @UserIdInt int userId,
4455 String value, int callingUid) {
Christopher Tate65fb2e42019-10-11 17:00:23 -07004456 return UserManagerService.this.isSettingRestrictedForUser(setting, userId,
yuemingw1d13eae2018-01-30 17:27:54 +00004457 value, callingUid);
4458 }
Patrick Baumann2f2fd712019-07-31 15:18:53 -07004459
4460 @Override
Bookatzf56f2582019-09-04 16:06:41 -07004461 public boolean hasUserRestriction(String restrictionKey, @UserIdInt int userId) {
Patrick Baumann2f2fd712019-07-31 15:18:53 -07004462 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
4463 return false;
4464 }
4465 Bundle restrictions = getEffectiveUserRestrictions(userId);
4466 return restrictions != null && restrictions.getBoolean(restrictionKey);
4467 }
Felipe Lemee5434c32019-08-13 09:28:33 -07004468
Rubin Xu0f1e56d2019-08-23 13:34:25 +01004469 @Override
Felipe Lemee5434c32019-08-13 09:28:33 -07004470 public @Nullable UserInfo getUserInfo(@UserIdInt int userId) {
4471 UserData userData;
4472 synchronized (mUsersLock) {
4473 userData = mUsers.get(userId);
4474 }
4475 return userData == null ? null : userData.info;
4476 }
Felipe Leme987655d2019-08-26 10:45:24 -07004477
4478 public @NonNull UserInfo[] getUserInfos() {
4479 synchronized (mUsersLock) {
4480 int userSize = mUsers.size();
4481 UserInfo[] allInfos = new UserInfo[userSize];
4482 for (int i = 0; i < userSize; i++) {
4483 allInfos[i] = mUsers.valueAt(i).info;
4484 }
4485 return allInfos;
4486 }
4487 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01004488 }
4489
4490 /* Remove all the users except of the system one. */
4491 private void removeNonSystemUsers() {
4492 ArrayList<UserInfo> usersToRemove = new ArrayList<>();
4493 synchronized (mUsersLock) {
4494 final int userSize = mUsers.size();
4495 for (int i = 0; i < userSize; i++) {
4496 UserInfo ui = mUsers.valueAt(i).info;
4497 if (ui.id != UserHandle.USER_SYSTEM) {
4498 usersToRemove.add(ui);
4499 }
4500 }
4501 }
4502 for (UserInfo ui: usersToRemove) {
4503 removeUser(ui.id);
4504 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07004505 }
Todd Kennedy60459ab2015-10-30 11:32:16 -07004506
4507 private class Shell extends ShellCommand {
4508 @Override
4509 public int onCommand(String cmd) {
4510 return onShellCommand(this, cmd);
4511 }
4512
4513 @Override
4514 public void onHelp() {
4515 final PrintWriter pw = getOutPrintWriter();
4516 pw.println("User manager (user) commands:");
4517 pw.println(" help");
4518 pw.println(" Print this help text.");
4519 pw.println("");
Felipe Lemec1ca4412019-09-11 09:23:26 -07004520 pw.println(" list [-v] [-all]");
Todd Kennedy60459ab2015-10-30 11:32:16 -07004521 pw.println(" Prints all users on the system.");
4522 }
4523 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08004524
4525 private static void debug(String message) {
4526 Log.d(LOG_TAG, message +
4527 (DBG_WITH_STACKTRACE ? " called at\n" + Debug.getCallers(10, " ") : ""));
4528 }
Kenny Guy02c89902016-11-15 19:36:38 +00004529
4530 @VisibleForTesting
4531 static int getMaxManagedProfiles() {
4532 // Allow overriding max managed profiles on debuggable builds for testing
4533 // of multiple profiles.
4534 if (!Build.IS_DEBUGGABLE) {
4535 return MAX_MANAGED_PROFILES;
4536 } else {
4537 return SystemProperties.getInt("persist.sys.max_profiles",
4538 MAX_MANAGED_PROFILES);
4539 }
4540 }
4541
Andreas Gampe2e8c7672018-07-20 13:01:08 -07004542 @GuardedBy("mUsersLock")
Kenny Guy02c89902016-11-15 19:36:38 +00004543 @VisibleForTesting
4544 int getFreeProfileBadgeLU(int parentUserId) {
4545 int maxManagedProfiles = getMaxManagedProfiles();
4546 boolean[] usedBadges = new boolean[maxManagedProfiles];
4547 final int userSize = mUsers.size();
4548 for (int i = 0; i < userSize; i++) {
4549 UserInfo ui = mUsers.valueAt(i).info;
4550 // Check which badge indexes are already used by this profile group.
4551 if (ui.isManagedProfile()
4552 && ui.profileGroupId == parentUserId
4553 && !mRemovingUserIds.get(ui.id)
4554 && ui.profileBadge < maxManagedProfiles) {
4555 usedBadges[ui.profileBadge] = true;
4556 }
4557 }
4558 for (int i = 0; i < maxManagedProfiles; i++) {
4559 if (!usedBadges[i]) {
4560 return i;
4561 }
4562 }
4563 return 0;
4564 }
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07004565
4566 /**
4567 * Checks if the given user has a managed profile associated with it.
4568 * @param userId The parent user
4569 * @return
4570 */
Bookatzf56f2582019-09-04 16:06:41 -07004571 boolean hasManagedProfile(@UserIdInt int userId) {
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07004572 synchronized (mUsersLock) {
4573 UserInfo userInfo = getUserInfoLU(userId);
4574 final int userSize = mUsers.size();
4575 for (int i = 0; i < userSize; i++) {
4576 UserInfo profile = mUsers.valueAt(i).info;
4577 if (userId != profile.id && isProfileOf(userInfo, profile)) {
4578 return true;
4579 }
4580 }
4581 return false;
4582 }
4583 }
Tony Makd390ae92017-12-28 13:23:10 +00004584
4585 /**
4586 * Check if the calling package name matches with the calling UID, throw
4587 * {@link SecurityException} if not.
4588 */
4589 private void verifyCallingPackage(String callingPackage, int callingUid) {
4590 int packageUid = mPm.getPackageUid(callingPackage, 0, UserHandle.getUserId(callingUid));
4591 if (packageUid != callingUid) {
4592 throw new SecurityException("Specified package " + callingPackage
4593 + " does not match the calling uid " + callingUid);
4594 }
4595 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07004596}