blob: 5c9b9c93e4fedaaf211fb521cdd96b890c178e2f [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) {
Roshan Pius7969c802019-10-21 19:58:57 -07001596 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "hasUserRestriction");
Patrick Baumann2f2fd712019-07-31 15:18:53 -07001597 return mLocalService.hasUserRestriction(restrictionKey, userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001598 }
1599
Makoto Onukiacc50462018-02-14 14:13:49 -08001600 /** @return if any user has the given restriction. */
1601 @Override
1602 public boolean hasUserRestrictionOnAnyUser(String restrictionKey) {
1603 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1604 return false;
1605 }
1606 final List<UserInfo> users = getUsers(/* excludeDying= */ true);
1607 for (int i = 0; i < users.size(); i++) {
1608 final int userId = users.get(i).id;
1609 Bundle restrictions = getEffectiveUserRestrictions(userId);
1610 if (restrictions != null && restrictions.getBoolean(restrictionKey)) {
1611 return true;
1612 }
1613 }
1614 return false;
1615 }
1616
Christopher Tate65fb2e42019-10-11 17:00:23 -07001617 @Override
1618 public boolean isSettingRestrictedForUser(String setting, @UserIdInt int userId,
1619 String value, int callingUid) {
1620 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
1621 throw new SecurityException("Non-system caller");
1622 }
1623 return UserRestrictionsUtils.isSettingRestrictedForUser(mContext, setting, userId,
1624 value, callingUid);
1625 }
1626
1627 @Override
1628 public void addUserRestrictionsListener(final IUserRestrictionsListener listener) {
1629 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
1630 throw new SecurityException("Non-system caller");
1631 }
1632
1633 // NOTE: unregistering not supported; only client is the settings provider,
1634 // which installs a single static permanent listener. If that listener goes
1635 // bad it implies the whole system process is going to crash.
1636 mLocalService.addUserRestrictionsListener(
1637 (int userId, Bundle newRestrict, Bundle prevRestrict) -> {
1638 try {
1639 listener.onUserRestrictionsChanged(userId, newRestrict, prevRestrict);
1640 } catch (RemoteException re) {
1641 Slog.e("IUserRestrictionsListener",
1642 "Unable to invoke listener: " + re.getMessage());
1643 }
1644 });
1645 }
1646
Makoto Onuki068c54a2015-10-13 14:34:03 -07001647 /**
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001648 * @hide
1649 *
1650 * Returns who set a user restriction on a user.
1651 * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
1652 * @param restrictionKey the string key representing the restriction
1653 * @param userId the id of the user for whom to retrieve the restrictions.
1654 * @return The source of user restriction. Any combination of
1655 * {@link UserManager#RESTRICTION_NOT_SET},
1656 * {@link UserManager#RESTRICTION_SOURCE_SYSTEM},
1657 * {@link UserManager#RESTRICTION_SOURCE_DEVICE_OWNER}
1658 * and {@link UserManager#RESTRICTION_SOURCE_PROFILE_OWNER}
1659 */
1660 @Override
Bookatzf56f2582019-09-04 16:06:41 -07001661 public int getUserRestrictionSource(String restrictionKey, @UserIdInt int userId) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001662 List<EnforcingUser> enforcingUsers = getUserRestrictionSources(restrictionKey, userId);
1663 // Get "bitwise or" of restriction sources for all enforcing users.
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001664 int result = UserManager.RESTRICTION_NOT_SET;
Pavel Grafov6a40f092016-10-25 15:46:51 +01001665 for (int i = enforcingUsers.size() - 1; i >= 0; i--) {
1666 result |= enforcingUsers.get(i).getUserRestrictionSource();
1667 }
1668 return result;
1669 }
1670
1671 @Override
1672 public List<EnforcingUser> getUserRestrictionSources(
1673 String restrictionKey, @UserIdInt int userId) {
1674 checkManageUsersPermission("getUserRestrictionSource");
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001675
1676 // Shortcut for the most common case
1677 if (!hasUserRestriction(restrictionKey, userId)) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001678 return Collections.emptyList();
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001679 }
1680
Pavel Grafov6a40f092016-10-25 15:46:51 +01001681 final List<EnforcingUser> result = new ArrayList<>();
1682
1683 // Check if it is base restriction.
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001684 if (hasBaseUserRestriction(restrictionKey, userId)) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001685 result.add(new EnforcingUser(
1686 UserHandle.USER_NULL, UserManager.RESTRICTION_SOURCE_SYSTEM));
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001687 }
1688
Pavel Grafov6a40f092016-10-25 15:46:51 +01001689 synchronized (mRestrictionsLock) {
1690 // Check if it is set by profile owner.
1691 Bundle profileOwnerRestrictions = mDevicePolicyLocalUserRestrictions.get(userId);
1692 if (UserRestrictionsUtils.contains(profileOwnerRestrictions, restrictionKey)) {
1693 result.add(getEnforcingUserLocked(userId));
1694 }
1695
1696 // Iterate over all users who enforce global restrictions.
1697 for (int i = mDevicePolicyGlobalUserRestrictions.size() - 1; i >= 0; i--) {
1698 Bundle globalRestrictions = mDevicePolicyGlobalUserRestrictions.valueAt(i);
1699 int profileUserId = mDevicePolicyGlobalUserRestrictions.keyAt(i);
1700 if (UserRestrictionsUtils.contains(globalRestrictions, restrictionKey)) {
1701 result.add(getEnforcingUserLocked(profileUserId));
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001702 }
1703 }
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001704 }
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001705 return result;
1706 }
1707
Andreas Gampea36dc622018-02-05 17:19:22 -08001708 @GuardedBy("mRestrictionsLock")
Pavel Grafov6a40f092016-10-25 15:46:51 +01001709 private EnforcingUser getEnforcingUserLocked(@UserIdInt int userId) {
1710 int source = mDeviceOwnerUserId == userId ? UserManager.RESTRICTION_SOURCE_DEVICE_OWNER
1711 : UserManager.RESTRICTION_SOURCE_PROFILE_OWNER;
1712 return new EnforcingUser(userId, source);
1713 }
1714
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001715 /**
Makoto Onuki068c54a2015-10-13 14:34:03 -07001716 * @return UserRestrictions that are in effect currently. This always returns a new
1717 * {@link Bundle}.
1718 */
Amith Yamasani8cd28b52014-06-08 17:54:27 -07001719 @Override
Bookatzf56f2582019-09-04 16:06:41 -07001720 public Bundle getUserRestrictions(@UserIdInt int userId) {
Roshan Pius7969c802019-10-21 19:58:57 -07001721 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "getUserRestrictions");
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001722 return UserRestrictionsUtils.clone(getEffectiveUserRestrictions(userId));
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001723 }
1724
1725 @Override
Bookatzf56f2582019-09-04 16:06:41 -07001726 public boolean hasBaseUserRestriction(String restrictionKey, @UserIdInt int userId) {
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +00001727 checkManageUsersPermission("hasBaseUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001728 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1729 return false;
1730 }
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +00001731 synchronized (mRestrictionsLock) {
1732 Bundle bundle = mBaseUserRestrictions.get(userId);
1733 return (bundle != null && bundle.getBoolean(restrictionKey, false));
1734 }
1735 }
1736
1737 @Override
Bookatzf56f2582019-09-04 16:06:41 -07001738 public void setUserRestriction(String key, boolean value, @UserIdInt int userId) {
Fyodor Kupolovd4b26042015-07-27 14:30:59 -07001739 checkManageUsersPermission("setUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001740 if (!UserRestrictionsUtils.isValidRestriction(key)) {
1741 return;
1742 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001743 synchronized (mRestrictionsLock) {
1744 // Note we can't modify Bundles stored in mBaseUserRestrictions directly, so create
1745 // a copy.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001746 final Bundle newRestrictions = UserRestrictionsUtils.clone(
1747 mBaseUserRestrictions.get(userId));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001748 newRestrictions.putBoolean(key, value);
1749
Fyodor Kupolov82402752015-10-28 14:54:51 -07001750 updateUserRestrictionsInternalLR(newRestrictions, userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001751 }
1752 }
1753
Makoto Onuki068c54a2015-10-13 14:34:03 -07001754 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001755 * Optionally updating user restrictions, calculate the effective user restrictions and also
1756 * propagate to other services and system settings.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001757 *
Pavel Grafov6a40f092016-10-25 15:46:51 +01001758 * @param newBaseRestrictions User restrictions to set.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001759 * If null, will not update user restrictions and only does the propagation.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001760 * @param userId target user ID.
1761 */
1762 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001763 private void updateUserRestrictionsInternalLR(
Bookatzf56f2582019-09-04 16:06:41 -07001764 @Nullable Bundle newBaseRestrictions, @UserIdInt int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001765 final Bundle prevAppliedRestrictions = UserRestrictionsUtils.nonNull(
1766 mAppliedUserRestrictions.get(userId));
1767
1768 // Update base restrictions.
Pavel Grafov6a40f092016-10-25 15:46:51 +01001769 if (newBaseRestrictions != null) {
1770 // If newBaseRestrictions == the current one, it's probably a bug.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001771 final Bundle prevBaseRestrictions = mBaseUserRestrictions.get(userId);
1772
Pavel Grafov6a40f092016-10-25 15:46:51 +01001773 Preconditions.checkState(prevBaseRestrictions != newBaseRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001774 Preconditions.checkState(mCachedEffectiveUserRestrictions.get(userId)
Pavel Grafov6a40f092016-10-25 15:46:51 +01001775 != newBaseRestrictions);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001776
Pavel Grafov6a40f092016-10-25 15:46:51 +01001777 if (updateRestrictionsIfNeededLR(userId, newBaseRestrictions, mBaseUserRestrictions)) {
Amith Yamasani12747872015-12-07 14:19:49 -08001778 scheduleWriteUser(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001779 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001780 }
1781
Fyodor Kupolov82402752015-10-28 14:54:51 -07001782 final Bundle effective = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001783
Makoto Onuki759a7632015-10-28 16:43:10 -07001784 mCachedEffectiveUserRestrictions.put(userId, effective);
1785
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001786 // Apply the new restrictions.
Makoto Onuki4f160732015-10-27 17:15:38 -07001787 if (DBG) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001788 debug("Applying user restrictions: userId=" + userId
1789 + " new=" + effective + " prev=" + prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001790 }
1791
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001792 if (mAppOpsService != null) { // We skip it until system-ready.
Fyodor Kupolovec30ca32016-06-16 15:09:29 -07001793 mHandler.post(new Runnable() {
1794 @Override
1795 public void run() {
1796 try {
1797 mAppOpsService.setUserRestrictions(effective, mUserRestriconToken, userId);
1798 } catch (RemoteException e) {
1799 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
1800 }
1801 }
1802 });
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001803 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001804
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001805 propagateUserRestrictionsLR(userId, effective, prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001806
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001807 mAppliedUserRestrictions.put(userId, new Bundle(effective));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001808 }
1809
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001810 private void propagateUserRestrictionsLR(final int userId,
Makoto Onukid45a4a22015-11-02 17:17:38 -08001811 Bundle newRestrictions, Bundle prevRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001812 // Note this method doesn't touch any state, meaning it doesn't require mRestrictionsLock
1813 // actually, but we still need some kind of synchronization otherwise we might end up
1814 // calling listeners out-of-order, thus "LR".
1815
1816 if (UserRestrictionsUtils.areEqual(newRestrictions, prevRestrictions)) {
1817 return;
1818 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08001819
1820 final Bundle newRestrictionsFinal = new Bundle(newRestrictions);
1821 final Bundle prevRestrictionsFinal = new Bundle(prevRestrictions);
1822
1823 mHandler.post(new Runnable() {
1824 @Override
1825 public void run() {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07001826 UserRestrictionsUtils.applyUserRestrictions(
1827 mContext, userId, newRestrictionsFinal, prevRestrictionsFinal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001828
Makoto Onukid45a4a22015-11-02 17:17:38 -08001829 final UserRestrictionsListener[] listeners;
1830 synchronized (mUserRestrictionsListeners) {
1831 listeners = new UserRestrictionsListener[mUserRestrictionsListeners.size()];
1832 mUserRestrictionsListeners.toArray(listeners);
1833 }
1834 for (int i = 0; i < listeners.length; i++) {
1835 listeners[i].onUserRestrictionsChanged(userId,
1836 newRestrictionsFinal, prevRestrictionsFinal);
1837 }
Makoto Onukie72f81b2017-03-16 14:08:19 -07001838
1839 final Intent broadcast = new Intent(UserManager.ACTION_USER_RESTRICTIONS_CHANGED)
1840 .setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
1841 mContext.sendBroadcastAsUser(broadcast, UserHandle.of(userId));
Makoto Onukid45a4a22015-11-02 17:17:38 -08001842 }
1843 });
1844 }
1845
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001846 // Package private for the inner class.
Andreas Gampe2e8c7672018-07-20 13:01:08 -07001847 @GuardedBy("mRestrictionsLock")
Bookatzf56f2582019-09-04 16:06:41 -07001848 void applyUserRestrictionsLR(@UserIdInt int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001849 updateUserRestrictionsInternalLR(null, userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001850 }
1851
1852 @GuardedBy("mRestrictionsLock")
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001853 // Package private for the inner class.
1854 void applyUserRestrictionsForAllUsersLR() {
1855 if (DBG) {
1856 debug("applyUserRestrictionsForAllUsersLR");
1857 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001858 // First, invalidate all cached values.
Makoto Onuki4f160732015-10-27 17:15:38 -07001859 mCachedEffectiveUserRestrictions.clear();
1860
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001861 // We don't want to call into ActivityManagerService while taking a lock, so we'll call
Makoto Onuki068c54a2015-10-13 14:34:03 -07001862 // it on a handler.
1863 final Runnable r = new Runnable() {
1864 @Override
1865 public void run() {
1866 // Then get the list of running users.
1867 final int[] runningUsers;
1868 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001869 runningUsers = ActivityManager.getService().getRunningUserIds();
Makoto Onuki068c54a2015-10-13 14:34:03 -07001870 } catch (RemoteException e) {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001871 Log.w(LOG_TAG, "Unable to access ActivityManagerService");
Makoto Onuki068c54a2015-10-13 14:34:03 -07001872 return;
1873 }
1874 // Then re-calculate the effective restrictions and apply, only for running users.
1875 // It's okay if a new user has started after the getRunningUserIds() call,
1876 // because we'll do the same thing (re-calculate the restrictions and apply)
1877 // when we start a user.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001878 synchronized (mRestrictionsLock) {
1879 for (int i = 0; i < runningUsers.length; i++) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001880 applyUserRestrictionsLR(runningUsers[i]);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001881 }
1882 }
1883 }
1884 };
1885 mHandler.post(r);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001886 }
1887
Amith Yamasani258848d2012-08-10 17:06:33 -07001888 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001889 * Check if we've hit the limit of how many users can be created.
1890 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001891 private boolean isUserLimitReached() {
1892 int count;
1893 synchronized (mUsersLock) {
1894 count = getAliveUsersExcludingGuestsCountLU();
1895 }
1896 return count >= UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001897 }
1898
1899 @Override
Bookatzf56f2582019-09-04 16:06:41 -07001900 public boolean canAddMoreManagedProfiles(@UserIdInt int userId, boolean allowedToRemoveOne) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001901 checkManageUsersPermission("check if more managed profiles can be added.");
1902 if (ActivityManager.isLowRamDeviceStatic()) {
1903 return false;
1904 }
Fyodor Kupolovb6157992015-06-05 15:32:28 -07001905 if (!mContext.getPackageManager().hasSystemFeature(
1906 PackageManager.FEATURE_MANAGED_USERS)) {
1907 return false;
1908 }
Nicolas Prevotb8186812015-08-06 15:00:03 +01001909 // Limit number of managed profiles that can be created
Benjamin Franzc8776152017-01-06 14:16:41 +00001910 final int managedProfilesCount = getProfiles(userId, false).size() - 1;
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001911 final int profilesRemovedCount = managedProfilesCount > 0 && allowedToRemoveOne ? 1 : 0;
Kenny Guy02c89902016-11-15 19:36:38 +00001912 if (managedProfilesCount - profilesRemovedCount >= getMaxManagedProfiles()) {
Nicolas Prevotb8186812015-08-06 15:00:03 +01001913 return false;
1914 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001915 synchronized(mUsersLock) {
1916 UserInfo userInfo = getUserInfoLU(userId);
yuanhao47f9f7c2017-01-18 09:54:45 +08001917 if (userInfo == null || !userInfo.canHaveProfile()) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001918 return false;
1919 }
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001920 int usersCountAfterRemoving = getAliveUsersExcludingGuestsCountLU()
1921 - profilesRemovedCount;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001922 // We allow creating a managed profile in the special case where there is only one user.
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001923 return usersCountAfterRemoving == 1
1924 || usersCountAfterRemoving < UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001925 }
1926 }
1927
Andreas Gampe2e8c7672018-07-20 13:01:08 -07001928 @GuardedBy("mUsersLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001929 private int getAliveUsersExcludingGuestsCountLU() {
Amith Yamasanif584f012014-05-19 17:57:25 -07001930 int aliveUserCount = 0;
1931 final int totalUserCount = mUsers.size();
1932 // Skip over users being removed
1933 for (int i = 0; i < totalUserCount; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001934 UserInfo user = mUsers.valueAt(i).info;
Felipe Lemec1ca4412019-09-11 09:23:26 -07001935 if (!mRemovingUserIds.get(user.id) && !user.isGuest() && !user.preCreated) {
Amith Yamasanif584f012014-05-19 17:57:25 -07001936 aliveUserCount++;
1937 }
1938 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001939 return aliveUserCount;
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001940 }
1941
1942 /**
Amith Yamasani195263742012-08-21 15:40:12 -07001943 * Enforces that only the system UID or root's UID or apps that have the
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001944 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} and
1945 * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL INTERACT_ACROSS_USERS_FULL}
1946 * permissions can make certain calls to the UserManager.
1947 *
1948 * @param message used as message if SecurityException is thrown
1949 * @throws SecurityException if the caller does not have enough privilege.
1950 */
1951 private static final void checkManageUserAndAcrossUsersFullPermission(String message) {
1952 final int uid = Binder.getCallingUid();
jovanakf24ad492018-05-18 12:15:59 -07001953
1954 if (uid == Process.SYSTEM_UID || uid == 0) {
1955 // System UID or root's UID are granted privilege.
1956 return;
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001957 }
jovanakf24ad492018-05-18 12:15:59 -07001958
1959 if (hasPermissionGranted(Manifest.permission.MANAGE_USERS, uid)
1960 && hasPermissionGranted(Manifest.permission.INTERACT_ACROSS_USERS_FULL, uid)) {
1961 // Apps with both permissions are granted privilege.
1962 return;
1963 }
1964
1965 throw new SecurityException(
1966 "You need MANAGE_USERS and INTERACT_ACROSS_USERS_FULL permission to: " + message);
1967 }
1968
1969 private static boolean hasPermissionGranted(String permission, int uid) {
1970 return ActivityManager.checkComponentPermission(
1971 permission, uid, /* owningUid = */-1, /* exported = */ true) ==
1972 PackageManager.PERMISSION_GRANTED;
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001973 }
1974
1975 /**
1976 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001977 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -07001978 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -07001979 *
1980 * @param message used as message if SecurityException is thrown
1981 * @throws SecurityException if the caller is not system or root
Tony Mak4dc008c2016-03-16 10:46:49 +00001982 * @see #hasManageUsersPermission()
Amith Yamasani258848d2012-08-10 17:06:33 -07001983 */
Amith Yamasanibe465322014-04-24 13:45:17 -07001984 private static final void checkManageUsersPermission(String message) {
Tony Mak4dc008c2016-03-16 10:46:49 +00001985 if (!hasManageUsersPermission()) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001986 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
1987 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -04001988 }
1989
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001990 /**
Sudheer Shankaf5cea032016-06-08 17:13:24 -07001991 * Enforces that only the system UID or root's UID or apps that have the
1992 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or
1993 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS}
1994 * can make certain calls to the UserManager.
1995 *
1996 * @param message used as message if SecurityException is thrown
1997 * @throws SecurityException if the caller is not system or root
1998 * @see #hasManageOrCreateUsersPermission()
1999 */
2000 private static final void checkManageOrCreateUsersPermission(String message) {
2001 if (!hasManageOrCreateUsersPermission()) {
2002 throw new SecurityException(
2003 "You either need MANAGE_USERS or CREATE_USERS permission to: " + message);
2004 }
2005 }
2006
2007 /**
2008 * Similar to {@link #checkManageOrCreateUsersPermission(String)} but when the caller is tries
2009 * to create user/profiles other than what is allowed for
2010 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS} permission, then it will only
2011 * allow callers with {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} permission.
2012 */
2013 private static final void checkManageOrCreateUsersPermission(int creationFlags) {
2014 if ((creationFlags & ~ALLOWED_FLAGS_FOR_CREATE_USERS_PERMISSION) == 0) {
2015 if (!hasManageOrCreateUsersPermission()) {
2016 throw new SecurityException("You either need MANAGE_USERS or CREATE_USERS "
2017 + "permission to create an user with flags: " + creationFlags);
2018 }
2019 } else if (!hasManageUsersPermission()) {
2020 throw new SecurityException("You need MANAGE_USERS permission to create an user "
2021 + " with flags: " + creationFlags);
2022 }
2023 }
2024
2025 /**
Tony Mak4dc008c2016-03-16 10:46:49 +00002026 * @return whether the calling UID is system UID or root's UID or the calling app has the
2027 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}.
2028 */
2029 private static final boolean hasManageUsersPermission() {
2030 final int callingUid = Binder.getCallingUid();
2031 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
2032 || callingUid == Process.ROOT_UID
jovanakf24ad492018-05-18 12:15:59 -07002033 || hasPermissionGranted(android.Manifest.permission.MANAGE_USERS, callingUid);
Tony Mak4dc008c2016-03-16 10:46:49 +00002034 }
2035
2036 /**
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002037 * @return whether the calling UID is system UID or root's UID or the calling app has the
Bookatzcde3d922019-03-08 14:30:00 -08002038 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or the provided permission.
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002039 */
Bookatzcde3d922019-03-08 14:30:00 -08002040 private static final boolean hasManageUsersOrPermission(String alternativePermission) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002041 final int callingUid = Binder.getCallingUid();
2042 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
2043 || callingUid == Process.ROOT_UID
jovanakf24ad492018-05-18 12:15:59 -07002044 || hasPermissionGranted(android.Manifest.permission.MANAGE_USERS, callingUid)
Bookatzcde3d922019-03-08 14:30:00 -08002045 || hasPermissionGranted(alternativePermission, callingUid);
2046 }
2047
2048 /**
2049 * @return whether the calling UID is system UID or root's UID or the calling app has the
2050 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or
2051 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS}.
2052 */
2053 private static final boolean hasManageOrCreateUsersPermission() {
2054 return hasManageUsersOrPermission(android.Manifest.permission.CREATE_USERS);
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002055 }
2056
2057 /**
Esteban Talavera5b9f1672015-12-11 15:22:34 +00002058 * Enforces that only the system UID or root's UID (on any user) can make certain calls to the
2059 * UserManager.
2060 *
2061 * @param message used as message if SecurityException is thrown
2062 * @throws SecurityException if the caller is not system or root
2063 */
2064 private static void checkSystemOrRoot(String message) {
2065 final int uid = Binder.getCallingUid();
2066 if (!UserHandle.isSameApp(uid, Process.SYSTEM_UID) && uid != Process.ROOT_UID) {
2067 throw new SecurityException("Only system may: " + message);
2068 }
2069 }
2070
Fyodor Kupolov82402752015-10-28 14:54:51 -07002071 private void writeBitmapLP(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002072 try {
2073 File dir = new File(mUsersDir, Integer.toString(info.id));
2074 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +01002075 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002076 if (!dir.exists()) {
2077 dir.mkdir();
2078 FileUtils.setPermissions(
2079 dir.getPath(),
2080 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
2081 -1, -1);
2082 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07002083 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +01002084 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01002085 && tmp.renameTo(file) && SELinux.restorecon(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -07002086 info.iconPath = file.getAbsolutePath();
2087 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07002088 try {
2089 os.close();
2090 } catch (IOException ioe) {
2091 // What the ... !
2092 }
Adrian Roos1bdff912015-02-17 15:51:35 +01002093 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002094 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002095 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002096 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002097 }
2098
Amith Yamasani0b285492011-04-14 17:35:23 -07002099 /**
2100 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
2101 * cache it elsewhere.
2102 * @return the array of user ids.
2103 */
Dianne Hackborn1676c852012-09-10 14:52:30 -07002104 public int[] getUserIds() {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002105 synchronized (mUsersLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07002106 return mUserIds;
2107 }
Amith Yamasani0b285492011-04-14 17:35:23 -07002108 }
2109
Andreas Gampe2e8c7672018-07-20 13:01:08 -07002110 @GuardedBy({"mRestrictionsLock", "mPackagesLock"})
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002111 private void readUserListLP() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002112 if (!mUserListFile.exists()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002113 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002114 return;
2115 }
2116 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07002117 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002118 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07002119 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002120 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002121 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002122 int type;
2123 while ((type = parser.next()) != XmlPullParser.START_TAG
2124 && type != XmlPullParser.END_DOCUMENT) {
Amith Yamasani12747872015-12-07 14:19:49 -08002125 // Skip
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002126 }
2127
2128 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07002129 Slog.e(LOG_TAG, "Unable to read user list");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002130 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002131 return;
2132 }
2133
Amith Yamasani2a003292012-08-14 18:25:45 -07002134 mNextSerialNumber = -1;
2135 if (parser.getName().equals(TAG_USERS)) {
2136 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
2137 if (lastSerialNumber != null) {
2138 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
2139 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07002140 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
2141 if (versionNumber != null) {
2142 mUserVersion = Integer.parseInt(versionNumber);
2143 }
Amith Yamasani2a003292012-08-14 18:25:45 -07002144 }
2145
Pavel Grafov6a40f092016-10-25 15:46:51 +01002146 // Pre-O global user restriction were stored as a single bundle (as opposed to per-user
2147 // currently), take care of it in case of upgrade.
2148 Bundle oldDevicePolicyGlobalUserRestrictions = null;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002149
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002150 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05302151 if (type == XmlPullParser.START_TAG) {
2152 final String name = parser.getName();
2153 if (name.equals(TAG_USER)) {
2154 String id = parser.getAttributeValue(null, ATTR_ID);
Amith Yamasani6f34b412012-10-22 18:19:27 -07002155
Amith Yamasani12747872015-12-07 14:19:49 -08002156 UserData userData = readUserLP(Integer.parseInt(id));
2157
2158 if (userData != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002159 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002160 mUsers.put(userData.info.id, userData);
2161 if (mNextSerialNumber < 0
2162 || mNextSerialNumber <= userData.info.id) {
2163 mNextSerialNumber = userData.info.id + 1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002164 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05302165 }
Amith Yamasani2a003292012-08-14 18:25:45 -07002166 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05302167 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -08002168 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2169 && type != XmlPullParser.END_TAG) {
2170 if (type == XmlPullParser.START_TAG) {
2171 if (parser.getName().equals(TAG_RESTRICTIONS)) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002172 synchronized (mGuestRestrictions) {
Fyodor Kupoloveafee022017-03-15 17:09:04 -07002173 UserRestrictionsUtils
2174 .readRestrictions(parser, mGuestRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002175 }
Amith Yamasanida0b1682014-11-21 12:58:17 -08002176 }
2177 break;
2178 }
2179 }
Pavel Grafov6a40f092016-10-25 15:46:51 +01002180 } else if (name.equals(TAG_DEVICE_OWNER_USER_ID)
2181 // Legacy name, should only be encountered when upgrading from pre-O.
2182 || name.equals(TAG_GLOBAL_RESTRICTION_OWNER_ID)) {
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01002183 String ownerUserId = parser.getAttributeValue(null, ATTR_ID);
2184 if (ownerUserId != null) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01002185 mDeviceOwnerUserId = Integer.parseInt(ownerUserId);
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01002186 }
Pavel Grafov6a40f092016-10-25 15:46:51 +01002187 } else if (name.equals(TAG_DEVICE_POLICY_RESTRICTIONS)) {
2188 // Should only happen when upgrading from pre-O (version < 7).
2189 oldDevicePolicyGlobalUserRestrictions =
2190 UserRestrictionsUtils.readRestrictions(parser);
Amith Yamasani258848d2012-08-10 17:06:33 -07002191 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002192 }
2193 }
Pavel Grafov6a40f092016-10-25 15:46:51 +01002194
Fyodor Kupolov82402752015-10-28 14:54:51 -07002195 updateUserIds();
Pavel Grafov6a40f092016-10-25 15:46:51 +01002196 upgradeIfNecessaryLP(oldDevicePolicyGlobalUserRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002197 } catch (IOException | XmlPullParserException e) {
2198 fallbackToSingleUserLP();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08002199 } finally {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002200 IoUtils.closeQuietly(fis);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002201 }
2202 }
2203
Amith Yamasani6f34b412012-10-22 18:19:27 -07002204 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -08002205 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Pavel Grafov6a40f092016-10-25 15:46:51 +01002206 * @param oldGlobalUserRestrictions Pre-O global device policy restrictions.
Amith Yamasani6f34b412012-10-22 18:19:27 -07002207 */
Andreas Gampe2e8c7672018-07-20 13:01:08 -07002208 @GuardedBy({"mRestrictionsLock", "mPackagesLock"})
Pavel Grafov6a40f092016-10-25 15:46:51 +01002209 private void upgradeIfNecessaryLP(Bundle oldGlobalUserRestrictions) {
Bookatz75f0a072019-08-05 14:12:16 -07002210 Set<Integer> userIdsToWrite = new ArraySet<>();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002211 final int originalVersion = mUserVersion;
Amith Yamasani6f34b412012-10-22 18:19:27 -07002212 int userVersion = mUserVersion;
2213 if (userVersion < 1) {
2214 // Assign a proper name for the owner, if not initialized correctly before
Amith Yamasani12747872015-12-07 14:19:49 -08002215 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
2216 if ("Primary".equals(userData.info.name)) {
2217 userData.info.name =
2218 mContext.getResources().getString(com.android.internal.R.string.owner_name);
Bookatz75f0a072019-08-05 14:12:16 -07002219 userIdsToWrite.add(userData.info.id);
Amith Yamasani6f34b412012-10-22 18:19:27 -07002220 }
2221 userVersion = 1;
2222 }
2223
Amith Yamasanibc9625052012-11-15 14:39:18 -08002224 if (userVersion < 2) {
2225 // Owner should be marked as initialized
Amith Yamasani12747872015-12-07 14:19:49 -08002226 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
2227 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
2228 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
Bookatz75f0a072019-08-05 14:12:16 -07002229 userIdsToWrite.add(userData.info.id);
Amith Yamasanibc9625052012-11-15 14:39:18 -08002230 }
2231 userVersion = 2;
2232 }
2233
Amith Yamasani350962c2013-08-06 11:18:53 -07002234
Amith Yamasani5e486f52013-08-07 11:06:44 -07002235 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -07002236 userVersion = 4;
2237 }
2238
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07002239 if (userVersion < 5) {
2240 initDefaultGuestRestrictions();
2241 userVersion = 5;
2242 }
2243
Fyodor Kupolov1c363152015-09-02 13:27:21 -07002244 if (userVersion < 6) {
2245 final boolean splitSystemUser = UserManager.isSplitSystemUser();
Fyodor Kupolov82402752015-10-28 14:54:51 -07002246 synchronized (mUsersLock) {
2247 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002248 UserData userData = mUsers.valueAt(i);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002249 // In non-split mode, only user 0 can have restricted profiles
Amith Yamasani12747872015-12-07 14:19:49 -08002250 if (!splitSystemUser && userData.info.isRestricted()
2251 && (userData.info.restrictedProfileParentId
2252 == UserInfo.NO_PROFILE_GROUP_ID)) {
2253 userData.info.restrictedProfileParentId = UserHandle.USER_SYSTEM;
Bookatz75f0a072019-08-05 14:12:16 -07002254 userIdsToWrite.add(userData.info.id);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002255 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07002256 }
2257 }
2258 userVersion = 6;
2259 }
2260
Pavel Grafov6a40f092016-10-25 15:46:51 +01002261 if (userVersion < 7) {
2262 // Previously only one user could enforce global restrictions, now it is per-user.
2263 synchronized (mRestrictionsLock) {
2264 if (!UserRestrictionsUtils.isEmpty(oldGlobalUserRestrictions)
2265 && mDeviceOwnerUserId != UserHandle.USER_NULL) {
2266 mDevicePolicyGlobalUserRestrictions.put(
2267 mDeviceOwnerUserId, oldGlobalUserRestrictions);
2268 }
2269 // ENSURE_VERIFY_APPS is now enforced globally even if put by profile owner, so move
2270 // it from local to global bundle for all users who set it.
2271 UserRestrictionsUtils.moveRestriction(UserManager.ENSURE_VERIFY_APPS,
2272 mDevicePolicyLocalUserRestrictions, mDevicePolicyGlobalUserRestrictions
2273 );
2274 }
2275 userVersion = 7;
2276 }
2277
Bookatz75f0a072019-08-05 14:12:16 -07002278 if (userVersion < 8) {
2279 // Added FLAG_FULL and FLAG_SYSTEM flags.
2280 synchronized (mUsersLock) {
2281 UserData userData = mUsers.get(UserHandle.USER_SYSTEM);
2282 userData.info.flags |= UserInfo.FLAG_SYSTEM;
2283 if (!UserManager.isHeadlessSystemUserMode()) {
2284 userData.info.flags |= UserInfo.FLAG_FULL;
2285 }
2286 userIdsToWrite.add(userData.info.id);
2287
2288 // Mark FULL all non-profile users except USER_SYSTEM.
2289 // Start index at 1 since USER_SYSTEM is the smallest userId and we're skipping it.
2290 for (int i = 1; i < mUsers.size(); i++) {
2291 userData = mUsers.valueAt(i);
2292 if ((userData.info.flags & UserInfo.FLAG_MANAGED_PROFILE) == 0) {
2293 userData.info.flags |= UserInfo.FLAG_FULL;
2294 userIdsToWrite.add(userData.info.id);
2295 }
2296 }
2297 }
2298 userVersion = 8;
2299 }
2300
Amith Yamasani6f34b412012-10-22 18:19:27 -07002301 if (userVersion < USER_VERSION) {
2302 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
2303 + USER_VERSION);
2304 } else {
2305 mUserVersion = userVersion;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002306
2307 if (originalVersion < mUserVersion) {
Bookatz75f0a072019-08-05 14:12:16 -07002308 for (int userId : userIdsToWrite) {
2309 UserData userData = getUserDataNoChecks(userId);
2310 if (userData != null) {
2311 writeUserLP(userData);
2312 }
2313 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002314 writeUserListLP();
2315 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07002316 }
2317 }
2318
Andreas Gampe2e8c7672018-07-20 13:01:08 -07002319 @GuardedBy({"mPackagesLock", "mRestrictionsLock"})
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002320 private void fallbackToSingleUserLP() {
Ying Zheng215116f2019-09-11 12:50:09 -07002321 int flags = UserInfo.FLAG_SYSTEM | UserInfo.FLAG_INITIALIZED | UserInfo.FLAG_ADMIN
2322 | UserInfo.FLAG_PRIMARY;
2323 // In headless system user mode, headless system user is not a full user.
Bookatz75f0a072019-08-05 14:12:16 -07002324 if (!UserManager.isHeadlessSystemUserMode()) {
Ying Zheng215116f2019-09-11 12:50:09 -07002325 flags |= UserInfo.FLAG_FULL;
Bookatz75f0a072019-08-05 14:12:16 -07002326 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -07002327 // Create the system user
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07002328 UserInfo system = new UserInfo(UserHandle.USER_SYSTEM, null, null, flags);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002329 UserData userData = putUserInfo(system);
Amith Yamasani634cf312012-10-04 17:34:21 -07002330 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -04002331 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -08002332
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05002333 Bundle restrictions = new Bundle();
Mahaver Chopra3d9805d2016-07-07 16:25:05 +01002334 try {
2335 final String[] defaultFirstUserRestrictions = mContext.getResources().getStringArray(
2336 com.android.internal.R.array.config_defaultFirstUserRestrictions);
2337 for (String userRestriction : defaultFirstUserRestrictions) {
2338 if (UserRestrictionsUtils.isValidRestriction(userRestriction)) {
2339 restrictions.putBoolean(userRestriction, true);
2340 }
2341 }
2342 } catch (Resources.NotFoundException e) {
2343 Log.e(LOG_TAG, "Couldn't find resource: config_defaultFirstUserRestrictions", e);
2344 }
2345
Pavel Grafov6a40f092016-10-25 15:46:51 +01002346 if (!restrictions.isEmpty()) {
2347 synchronized (mRestrictionsLock) {
2348 mBaseUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions);
2349 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07002350 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08002351
Fyodor Kupolov82402752015-10-28 14:54:51 -07002352 updateUserIds();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07002353 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002354
Amith Yamasani12747872015-12-07 14:19:49 -08002355 writeUserLP(userData);
Jeff Sharkeycd575992016-03-29 14:12:49 -06002356 writeUserListLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002357 }
2358
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07002359 private String getOwnerName() {
2360 return mContext.getResources().getString(com.android.internal.R.string.owner_name);
2361 }
2362
Bookatz75f0a072019-08-05 14:12:16 -07002363 private void scheduleWriteUser(UserData userData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002364 if (DBG) {
2365 debug("scheduleWriteUser");
2366 }
Makoto Onuki9e935a32015-11-06 14:24:24 -08002367 // No need to wrap it within a lock -- worst case, we'll just post the same message
2368 // twice.
Bookatz75f0a072019-08-05 14:12:16 -07002369 if (!mHandler.hasMessages(WRITE_USER_MSG, userData)) {
2370 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, userData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002371 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
2372 }
2373 }
2374
Amith Yamasani12747872015-12-07 14:19:49 -08002375 private void writeUserLP(UserData userData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002376 if (DBG) {
Amith Yamasani12747872015-12-07 14:19:49 -08002377 debug("writeUserLP " + userData);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002378 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002379 FileOutputStream fos = null;
Amith Yamasani12747872015-12-07 14:19:49 -08002380 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userData.info.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002381 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07002382 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002383 final BufferedOutputStream bos = new BufferedOutputStream(fos);
Kenny Guy02c89902016-11-15 19:36:38 +00002384 writeUserLP(userData, bos);
Amith Yamasani2a003292012-08-14 18:25:45 -07002385 userFile.finishWrite(fos);
2386 } catch (Exception ioe) {
Jeff Sharkeycd575992016-03-29 14:12:49 -06002387 Slog.e(LOG_TAG, "Error writing user info " + userData.info.id, ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -07002388 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002389 }
2390 }
2391
2392 /*
Kenny Guy02c89902016-11-15 19:36:38 +00002393 * Writes the user file in this format:
2394 *
2395 * <user flags="20039023" id="0">
2396 * <name>Primary</name>
2397 * </user>
2398 */
2399 @VisibleForTesting
2400 void writeUserLP(UserData userData, OutputStream os)
2401 throws IOException, XmlPullParserException {
2402 // XmlSerializer serializer = XmlUtils.serializerInstance();
2403 final XmlSerializer serializer = new FastXmlSerializer();
2404 serializer.setOutput(os, StandardCharsets.UTF_8.name());
2405 serializer.startDocument(null, true);
2406 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2407
2408 final UserInfo userInfo = userData.info;
2409 serializer.startTag(null, TAG_USER);
2410 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
2411 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
2412 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
2413 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
2414 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
2415 Long.toString(userInfo.lastLoggedInTime));
2416 if (userInfo.lastLoggedInFingerprint != null) {
2417 serializer.attribute(null, ATTR_LAST_LOGGED_IN_FINGERPRINT,
2418 userInfo.lastLoggedInFingerprint);
2419 }
2420 if (userInfo.iconPath != null) {
2421 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
2422 }
2423 if (userInfo.partial) {
2424 serializer.attribute(null, ATTR_PARTIAL, "true");
2425 }
Felipe Lemec1ca4412019-09-11 09:23:26 -07002426 if (userInfo.preCreated) {
2427 serializer.attribute(null, ATTR_PRE_CREATED, "true");
2428 }
Kenny Guy02c89902016-11-15 19:36:38 +00002429 if (userInfo.guestToRemove) {
2430 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
2431 }
2432 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
2433 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
2434 Integer.toString(userInfo.profileGroupId));
2435 }
2436 serializer.attribute(null, ATTR_PROFILE_BADGE,
2437 Integer.toString(userInfo.profileBadge));
2438 if (userInfo.restrictedProfileParentId != UserInfo.NO_PROFILE_GROUP_ID) {
2439 serializer.attribute(null, ATTR_RESTRICTED_PROFILE_PARENT_ID,
2440 Integer.toString(userInfo.restrictedProfileParentId));
2441 }
2442 // Write seed data
2443 if (userData.persistSeedData) {
2444 if (userData.seedAccountName != null) {
2445 serializer.attribute(null, ATTR_SEED_ACCOUNT_NAME, userData.seedAccountName);
2446 }
2447 if (userData.seedAccountType != null) {
2448 serializer.attribute(null, ATTR_SEED_ACCOUNT_TYPE, userData.seedAccountType);
2449 }
2450 }
2451 if (userInfo.name != null) {
2452 serializer.startTag(null, TAG_NAME);
2453 serializer.text(userInfo.name);
2454 serializer.endTag(null, TAG_NAME);
2455 }
2456 synchronized (mRestrictionsLock) {
2457 UserRestrictionsUtils.writeRestrictions(serializer,
2458 mBaseUserRestrictions.get(userInfo.id), TAG_RESTRICTIONS);
2459 UserRestrictionsUtils.writeRestrictions(serializer,
2460 mDevicePolicyLocalUserRestrictions.get(userInfo.id),
2461 TAG_DEVICE_POLICY_RESTRICTIONS);
Pavel Grafov6a40f092016-10-25 15:46:51 +01002462 UserRestrictionsUtils.writeRestrictions(serializer,
2463 mDevicePolicyGlobalUserRestrictions.get(userInfo.id),
2464 TAG_DEVICE_POLICY_GLOBAL_RESTRICTIONS);
Kenny Guy02c89902016-11-15 19:36:38 +00002465 }
2466
2467 if (userData.account != null) {
2468 serializer.startTag(null, TAG_ACCOUNT);
2469 serializer.text(userData.account);
2470 serializer.endTag(null, TAG_ACCOUNT);
2471 }
2472
2473 if (userData.persistSeedData && userData.seedAccountOptions != null) {
2474 serializer.startTag(null, TAG_SEED_ACCOUNT_OPTIONS);
2475 userData.seedAccountOptions.saveToXml(serializer);
2476 serializer.endTag(null, TAG_SEED_ACCOUNT_OPTIONS);
2477 }
2478
arangelov9b632d72018-12-07 23:21:22 +00002479 if (userData.getLastRequestQuietModeEnabledMillis() != 0L) {
2480 serializer.startTag(/* namespace */ null, TAG_LAST_REQUEST_QUIET_MODE_ENABLED_CALL);
2481 serializer.text(String.valueOf(userData.getLastRequestQuietModeEnabledMillis()));
2482 serializer.endTag(/* namespace */ null, TAG_LAST_REQUEST_QUIET_MODE_ENABLED_CALL);
2483 }
2484
Kenny Guy02c89902016-11-15 19:36:38 +00002485 serializer.endTag(null, TAG_USER);
2486
2487 serializer.endDocument();
2488 }
2489
2490 /*
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002491 * Writes the user list file in this format:
2492 *
Amith Yamasani2a003292012-08-14 18:25:45 -07002493 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002494 * <user id="0"></user>
2495 * <user id="2"></user>
2496 * </users>
2497 */
Andreas Gampe2e8c7672018-07-20 13:01:08 -07002498 @GuardedBy({"mRestrictionsLock", "mPackagesLock"})
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002499 private void writeUserListLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002500 if (DBG) {
2501 debug("writeUserList");
2502 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002503 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07002504 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002505 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07002506 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002507 final BufferedOutputStream bos = new BufferedOutputStream(fos);
2508
2509 // XmlSerializer serializer = XmlUtils.serializerInstance();
2510 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002511 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002512 serializer.startDocument(null, true);
2513 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2514
2515 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -07002516 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -07002517 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002518
Adam Lesinskieddeb492014-09-08 17:50:03 -07002519 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002520 synchronized (mGuestRestrictions) {
2521 UserRestrictionsUtils
2522 .writeRestrictions(serializer, mGuestRestrictions, TAG_RESTRICTIONS);
2523 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05302524 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Pavel Grafov6a40f092016-10-25 15:46:51 +01002525 serializer.startTag(null, TAG_DEVICE_OWNER_USER_ID);
2526 serializer.attribute(null, ATTR_ID, Integer.toString(mDeviceOwnerUserId));
2527 serializer.endTag(null, TAG_DEVICE_OWNER_USER_ID);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002528 int[] userIdsToWrite;
2529 synchronized (mUsersLock) {
2530 userIdsToWrite = new int[mUsers.size()];
2531 for (int i = 0; i < userIdsToWrite.length; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002532 UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002533 userIdsToWrite[i] = user.id;
2534 }
2535 }
2536 for (int id : userIdsToWrite) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002537 serializer.startTag(null, TAG_USER);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002538 serializer.attribute(null, ATTR_ID, Integer.toString(id));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002539 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002540 }
2541
2542 serializer.endTag(null, TAG_USERS);
2543
2544 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07002545 userListFile.finishWrite(fos);
2546 } catch (Exception e) {
2547 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -07002548 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002549 }
2550 }
2551
Amith Yamasani12747872015-12-07 14:19:49 -08002552 private UserData readUserLP(int id) {
Kenny Guy02c89902016-11-15 19:36:38 +00002553 FileInputStream fis = null;
2554 try {
2555 AtomicFile userFile =
2556 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
2557 fis = userFile.openRead();
2558 return readUserLP(id, fis);
2559 } catch (IOException ioe) {
2560 Slog.e(LOG_TAG, "Error reading user list");
2561 } catch (XmlPullParserException pe) {
2562 Slog.e(LOG_TAG, "Error reading user list");
2563 } finally {
2564 IoUtils.closeQuietly(fis);
2565 }
2566 return null;
2567 }
2568
2569 @VisibleForTesting
2570 UserData readUserLP(int id, InputStream is) throws IOException,
2571 XmlPullParserException {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002572 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -07002573 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002574 String name = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -08002575 String account = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002576 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -07002577 long creationTime = 0L;
2578 long lastLoggedInTime = 0L;
arangelov9b632d72018-12-07 23:21:22 +00002579 long lastRequestQuietModeEnabledTimestamp = 0L;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002580 String lastLoggedInFingerprint = null;
Kenny Guy2a764942014-04-02 13:29:20 +01002581 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Kenny Guy02c89902016-11-15 19:36:38 +00002582 int profileBadge = 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002583 int restrictedProfileParentId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002584 boolean partial = false;
Felipe Lemec1ca4412019-09-11 09:23:26 -07002585 boolean preCreated = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -07002586 boolean guestToRemove = false;
Amith Yamasani12747872015-12-07 14:19:49 -08002587 boolean persistSeedData = false;
2588 String seedAccountName = null;
2589 String seedAccountType = null;
2590 PersistableBundle seedAccountOptions = null;
Pavel Grafov6a40f092016-10-25 15:46:51 +01002591 Bundle baseRestrictions = null;
2592 Bundle localRestrictions = null;
2593 Bundle globalRestrictions = null;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002594
Kenny Guy02c89902016-11-15 19:36:38 +00002595 XmlPullParser parser = Xml.newPullParser();
2596 parser.setInput(is, StandardCharsets.UTF_8.name());
2597 int type;
2598 while ((type = parser.next()) != XmlPullParser.START_TAG
2599 && type != XmlPullParser.END_DOCUMENT) {
2600 // Skip
2601 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002602
Kenny Guy02c89902016-11-15 19:36:38 +00002603 if (type != XmlPullParser.START_TAG) {
2604 Slog.e(LOG_TAG, "Unable to read user " + id);
2605 return null;
2606 }
2607
2608 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
2609 int storedId = readIntAttribute(parser, ATTR_ID, -1);
2610 if (storedId != id) {
2611 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002612 return null;
2613 }
Kenny Guy02c89902016-11-15 19:36:38 +00002614 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
2615 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
2616 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
2617 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
2618 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
2619 lastLoggedInFingerprint = parser.getAttributeValue(null,
2620 ATTR_LAST_LOGGED_IN_FINGERPRINT);
2621 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
2622 UserInfo.NO_PROFILE_GROUP_ID);
2623 profileBadge = readIntAttribute(parser, ATTR_PROFILE_BADGE, 0);
2624 restrictedProfileParentId = readIntAttribute(parser,
2625 ATTR_RESTRICTED_PROFILE_PARENT_ID, UserInfo.NO_PROFILE_GROUP_ID);
2626 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
2627 if ("true".equals(valueString)) {
2628 partial = true;
2629 }
Felipe Lemec1ca4412019-09-11 09:23:26 -07002630 valueString = parser.getAttributeValue(null, ATTR_PRE_CREATED);
2631 if ("true".equals(valueString)) {
2632 preCreated = true;
2633 }
Kenny Guy02c89902016-11-15 19:36:38 +00002634 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
2635 if ("true".equals(valueString)) {
2636 guestToRemove = true;
2637 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002638
Kenny Guy02c89902016-11-15 19:36:38 +00002639 seedAccountName = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_NAME);
2640 seedAccountType = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_TYPE);
2641 if (seedAccountName != null || seedAccountType != null) {
2642 persistSeedData = true;
2643 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002644
Kenny Guy02c89902016-11-15 19:36:38 +00002645 int outerDepth = parser.getDepth();
2646 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2647 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2648 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2649 continue;
2650 }
2651 String tag = parser.getName();
2652 if (TAG_NAME.equals(tag)) {
2653 type = parser.next();
2654 if (type == XmlPullParser.TEXT) {
2655 name = parser.getText();
2656 }
2657 } else if (TAG_RESTRICTIONS.equals(tag)) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01002658 baseRestrictions = UserRestrictionsUtils.readRestrictions(parser);
Kenny Guy02c89902016-11-15 19:36:38 +00002659 } else if (TAG_DEVICE_POLICY_RESTRICTIONS.equals(tag)) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01002660 localRestrictions = UserRestrictionsUtils.readRestrictions(parser);
2661 } else if (TAG_DEVICE_POLICY_GLOBAL_RESTRICTIONS.equals(tag)) {
2662 globalRestrictions = UserRestrictionsUtils.readRestrictions(parser);
Kenny Guy02c89902016-11-15 19:36:38 +00002663 } else if (TAG_ACCOUNT.equals(tag)) {
2664 type = parser.next();
2665 if (type == XmlPullParser.TEXT) {
2666 account = parser.getText();
2667 }
2668 } else if (TAG_SEED_ACCOUNT_OPTIONS.equals(tag)) {
2669 seedAccountOptions = PersistableBundle.restoreFromXml(parser);
Amith Yamasani12747872015-12-07 14:19:49 -08002670 persistSeedData = true;
arangelov9b632d72018-12-07 23:21:22 +00002671 } else if (TAG_LAST_REQUEST_QUIET_MODE_ENABLED_CALL.equals(tag)) {
2672 type = parser.next();
2673 if (type == XmlPullParser.TEXT) {
2674 lastRequestQuietModeEnabledTimestamp = Long.parseLong(parser.getText());
2675 }
Amith Yamasani12747872015-12-07 14:19:49 -08002676 }
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08002677 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002678 }
Kenny Guy02c89902016-11-15 19:36:38 +00002679
2680 // Create the UserInfo object that gets passed around
2681 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
2682 userInfo.serialNumber = serialNumber;
2683 userInfo.creationTime = creationTime;
2684 userInfo.lastLoggedInTime = lastLoggedInTime;
2685 userInfo.lastLoggedInFingerprint = lastLoggedInFingerprint;
2686 userInfo.partial = partial;
Felipe Lemec1ca4412019-09-11 09:23:26 -07002687 userInfo.preCreated = preCreated;
Kenny Guy02c89902016-11-15 19:36:38 +00002688 userInfo.guestToRemove = guestToRemove;
2689 userInfo.profileGroupId = profileGroupId;
2690 userInfo.profileBadge = profileBadge;
2691 userInfo.restrictedProfileParentId = restrictedProfileParentId;
2692
2693 // Create the UserData object that's internal to this class
2694 UserData userData = new UserData();
2695 userData.info = userInfo;
2696 userData.account = account;
2697 userData.seedAccountName = seedAccountName;
2698 userData.seedAccountType = seedAccountType;
2699 userData.persistSeedData = persistSeedData;
2700 userData.seedAccountOptions = seedAccountOptions;
arangelov9b632d72018-12-07 23:21:22 +00002701 userData.setLastRequestQuietModeEnabledMillis(lastRequestQuietModeEnabledTimestamp);
Kenny Guy02c89902016-11-15 19:36:38 +00002702
2703 synchronized (mRestrictionsLock) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01002704 if (baseRestrictions != null) {
2705 mBaseUserRestrictions.put(id, baseRestrictions);
2706 }
2707 if (localRestrictions != null) {
2708 mDevicePolicyLocalUserRestrictions.put(id, localRestrictions);
2709 }
2710 if (globalRestrictions != null) {
2711 mDevicePolicyGlobalUserRestrictions.put(id, globalRestrictions);
2712 }
Kenny Guy02c89902016-11-15 19:36:38 +00002713 }
2714 return userData;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002715 }
2716
Amith Yamasani920ace02012-09-20 22:15:37 -07002717 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
2718 String valueString = parser.getAttributeValue(null, attr);
2719 if (valueString == null) return defaultValue;
2720 try {
2721 return Integer.parseInt(valueString);
2722 } catch (NumberFormatException nfe) {
2723 return defaultValue;
2724 }
2725 }
2726
2727 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
2728 String valueString = parser.getAttributeValue(null, attr);
2729 if (valueString == null) return defaultValue;
2730 try {
2731 return Long.parseLong(valueString);
2732 } catch (NumberFormatException nfe) {
2733 return defaultValue;
2734 }
2735 }
2736
Amith Yamasanib82add22013-07-09 11:24:44 -07002737 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002738 * Removes the app restrictions file for a specific package and user id, if it exists.
2739 */
Bookatzf56f2582019-09-04 16:06:41 -07002740 private static void cleanAppRestrictionsForPackageLAr(String pkg, @UserIdInt int userId) {
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07002741 File dir = Environment.getUserSystemDirectory(userId);
2742 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
2743 if (resFile.exists()) {
2744 resFile.delete();
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002745 }
2746 }
2747
Kenny Guya52dc3e2014-02-11 15:33:14 +00002748 @Override
Bookatzf56f2582019-09-04 16:06:41 -07002749 public UserInfo createProfileForUser(String name, int flags, @UserIdInt int userId,
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002750 String[] disallowedPackages) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002751 checkManageOrCreateUsersPermission(flags);
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002752 return createUserInternal(name, flags, userId, disallowedPackages);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002753 }
2754
Amith Yamasani258848d2012-08-10 17:06:33 -07002755 @Override
Bookatzf56f2582019-09-04 16:06:41 -07002756 public UserInfo createProfileForUserEvenWhenDisallowed(String name, int flags,
2757 @UserIdInt int userId, String[] disallowedPackages) {
Tony Mak6dc428f2016-10-10 15:48:27 +01002758 checkManageOrCreateUsersPermission(flags);
Felipe Lemec1ca4412019-09-11 09:23:26 -07002759 return createUserInternalUnchecked(name, flags, userId, /* preCreate= */ false,
2760 disallowedPackages);
Tony Mak6dc428f2016-10-10 15:48:27 +01002761 }
2762
2763 @Override
Bookatzf56f2582019-09-04 16:06:41 -07002764 public boolean removeUserEvenWhenDisallowed(@UserIdInt int userId) {
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00002765 checkManageOrCreateUsersPermission("Only the system can remove users");
Bookatzf56f2582019-09-04 16:06:41 -07002766 return removeUserUnchecked(userId);
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00002767 }
2768
2769 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07002770 public UserInfo createUser(String name, int flags) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002771 checkManageOrCreateUsersPermission(flags);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00002772 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002773 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07002774
Felipe Lemec1ca4412019-09-11 09:23:26 -07002775 @Override
2776 public UserInfo preCreateUser(int flags) {
2777 checkManageOrCreateUsersPermission(flags);
2778
2779 Preconditions.checkArgument(!UserInfo.isManagedProfile(flags),
2780 "cannot pre-create managed profiles");
2781
Felipe Leme09a7f2d2019-10-02 16:27:46 -07002782 Slog.i(LOG_TAG, "Pre-creating user with flags " + UserInfo.flagsToString(flags));
2783
Felipe Lemec1ca4412019-09-11 09:23:26 -07002784 return createUserInternalUnchecked(/* name= */ null, flags,
2785 /* parentId= */ UserHandle.USER_NULL, /* preCreate= */ true,
2786 /* disallowedPackages= */ null);
2787 }
2788
2789 private UserInfo createUserInternal(@Nullable String name, @UserInfoFlag int flags,
2790 @UserIdInt int parentId) {
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002791 return createUserInternal(name, flags, parentId, null);
2792 }
2793
Felipe Lemec1ca4412019-09-11 09:23:26 -07002794 private UserInfo createUserInternal(@Nullable String name, @UserInfoFlag int flags,
2795 @UserIdInt int parentId, @Nullable String[] disallowedPackages) {
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002796 String restriction = ((flags & UserInfo.FLAG_MANAGED_PROFILE) != 0)
2797 ? UserManager.DISALLOW_ADD_MANAGED_PROFILE
2798 : UserManager.DISALLOW_ADD_USER;
2799 if (hasUserRestriction(restriction, UserHandle.getCallingUserId())) {
2800 Log.w(LOG_TAG, "Cannot add user. " + restriction + " is enabled.");
Julia Reynolds75175022014-06-26 16:35:00 -04002801 return null;
2802 }
Felipe Lemec1ca4412019-09-11 09:23:26 -07002803 return createUserInternalUnchecked(name, flags, parentId, /* preCreate= */ false,
2804 disallowedPackages);
Tony Mak6dc428f2016-10-10 15:48:27 +01002805 }
2806
Felipe Lemec1ca4412019-09-11 09:23:26 -07002807 private UserInfo createUserInternalUnchecked(@Nullable String name, @UserInfoFlag int flags,
2808 @UserIdInt int parentId, boolean preCreate,
2809 @Nullable String[] disallowedPackages) {
2810 final TimingsTraceAndSlog t = new TimingsTraceAndSlog();
2811 t.traceBegin("createUser-" + flags);
2812 try {
2813 return createUserInternalUncheckedNoTracing(name, flags, parentId, preCreate,
2814 disallowedPackages, t);
2815 } finally {
2816 t.traceEnd();
2817 }
jovanakdd7e4752019-09-04 12:35:45 -07002818 }
2819
Felipe Lemec1ca4412019-09-11 09:23:26 -07002820 private UserInfo createUserInternalUncheckedNoTracing(@Nullable String name,
2821 @UserInfoFlag int flags, @UserIdInt int parentId, boolean preCreate,
2822 @Nullable String[] disallowedPackages, @NonNull TimingsTraceAndSlog t) {
2823
2824 // First try to use a pre-created user (if available).
2825 // NOTE: currently we don't support pre-created managed profiles
2826 if (!preCreate && (parentId < 0 && !UserInfo.isManagedProfile(flags))) {
2827 final UserData preCreatedUserData;
2828 synchronized (mUsersLock) {
2829 preCreatedUserData = getPreCreatedUserLU(flags);
2830 }
2831 if (preCreatedUserData != null) {
2832 final UserInfo preCreatedUser = preCreatedUserData.info;
2833 Log.i(LOG_TAG, "Reusing pre-created user " + preCreatedUser.id + " for flags + "
2834 + UserInfo.flagsToString(flags));
2835 if (DBG) {
2836 Log.d(LOG_TAG, "pre-created user flags: "
2837 + UserInfo.flagsToString(preCreatedUser.flags)
2838 + " new-user flags: " + UserInfo.flagsToString(flags));
2839 }
2840 preCreatedUser.name = name;
2841 preCreatedUser.preCreated = false;
2842 preCreatedUser.creationTime = getCreationTime();
2843
2844 dispatchUserAddedIntent(preCreatedUser);
2845
2846 writeUserLP(preCreatedUserData);
2847 writeUserListLP();
2848
2849 return preCreatedUser;
2850 }
2851 }
2852
Suprabh Shuklac5e057c2016-08-08 16:22:44 -07002853 DeviceStorageMonitorInternal dsm = LocalServices
2854 .getService(DeviceStorageMonitorInternal.class);
2855 if (dsm.isMemoryLow()) {
2856 Log.w(LOG_TAG, "Cannot add user. Not enough space on disk.");
2857 return null;
2858 }
jovanakdd7e4752019-09-04 12:35:45 -07002859
Felipe Lemec1ca4412019-09-11 09:23:26 -07002860 final boolean isGuest = UserInfo.isGuest(flags);
2861 final boolean isManagedProfile = UserInfo.isManagedProfile(flags);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002862 final boolean isRestricted = (flags & UserInfo.FLAG_RESTRICTED) != 0;
Amith Yamasani52c21e32016-05-31 09:12:20 -07002863 final boolean isDemo = (flags & UserInfo.FLAG_DEMO) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002864 final long ident = Binder.clearCallingIdentity();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002865 UserInfo userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08002866 UserData userData;
Amith Yamasanibb054c92015-07-09 14:16:27 -07002867 final int userId;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002868 try {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002869 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002870 UserData parent = null;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002871 if (parentId != UserHandle.USER_NULL) {
2872 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002873 parent = getUserDataLU(parentId);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00002874 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002875 if (parent == null) return null;
2876 }
2877 if (isManagedProfile && !canAddMoreManagedProfiles(parentId, false)) {
2878 Log.e(LOG_TAG, "Cannot add more managed profiles for user " + parentId);
2879 return null;
2880 }
Amith Yamasani52c21e32016-05-31 09:12:20 -07002881 if (!isGuest && !isManagedProfile && !isDemo && isUserLimitReached()) {
Felipe Lemec1ca4412019-09-11 09:23:26 -07002882 // If we're not adding a guest/demo user or a managed profile,
2883 // and the limit has been reached, cannot add a user.
jovanaka6763a32018-12-03 17:23:20 -08002884 Log.e(LOG_TAG, "Cannot add user. Maximum user limit is reached.");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002885 return null;
2886 }
2887 // If we're adding a guest and there already exists one, bail.
Felipe Lemee35f5b02019-10-14 15:37:44 -07002888 if (isGuest && !preCreate && findCurrentGuestUser() != null) {
jovanaka6763a32018-12-03 17:23:20 -08002889 Log.e(LOG_TAG, "Cannot add guest user. Guest user already exists.");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002890 return null;
2891 }
2892 // In legacy mode, restricted profile's parent can only be the owner user
2893 if (isRestricted && !UserManager.isSplitSystemUser()
2894 && (parentId != UserHandle.USER_SYSTEM)) {
2895 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
2896 return null;
2897 }
2898 if (isRestricted && UserManager.isSplitSystemUser()) {
2899 if (parent == null) {
2900 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be "
2901 + "specified");
Nicolas Prevot12678a92015-05-13 12:15:03 -07002902 return null;
2903 }
Amith Yamasani12747872015-12-07 14:19:49 -08002904 if (!parent.info.canHaveProfile()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002905 Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be "
2906 + "created for the specified parent user id " + parentId);
Amith Yamasani95ab7842014-08-11 17:09:26 -07002907 return null;
2908 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002909 }
Ying Zheng215116f2019-09-11 12:50:09 -07002910
Bookatz75f0a072019-08-05 14:12:16 -07002911 if (!isManagedProfile) {
2912 // New users cannot be system, and it's not a profile, so per-force it's FULL.
2913 flags |= UserInfo.FLAG_FULL;
2914 }
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002915
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002916 userId = getNextAvailableId();
2917 Environment.getUserSystemDirectory(userId).mkdirs();
Felipe Lemec1ca4412019-09-11 09:23:26 -07002918 boolean ephemeralGuests = areGuestUsersEphemeral();
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002919
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002920 synchronized (mUsersLock) {
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002921 // Add ephemeral flag to guests/users if required. Also inherit it from parent.
2922 if ((isGuest && ephemeralGuests) || mForceEphemeralUsers
2923 || (parent != null && parent.info.isEphemeral())) {
2924 flags |= UserInfo.FLAG_EPHEMERAL;
2925 }
2926
2927 userInfo = new UserInfo(userId, name, null, flags);
2928 userInfo.serialNumber = mNextSerialNumber++;
Felipe Lemec1ca4412019-09-11 09:23:26 -07002929 userInfo.creationTime = getCreationTime();
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002930 userInfo.partial = true;
Felipe Lemec1ca4412019-09-11 09:23:26 -07002931 userInfo.preCreated = preCreate;
Fyodor Kupolov83c24242016-03-31 13:30:42 -07002932 userInfo.lastLoggedInFingerprint = Build.FINGERPRINT;
Kenny Guy02c89902016-11-15 19:36:38 +00002933 if (isManagedProfile && parentId != UserHandle.USER_NULL) {
2934 userInfo.profileBadge = getFreeProfileBadgeLU(parentId);
2935 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002936 userData = new UserData();
2937 userData.info = userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08002938 mUsers.put(userId, userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002939 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06002940 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002941 writeUserListLP();
2942 if (parent != null) {
2943 if (isManagedProfile) {
Amith Yamasani12747872015-12-07 14:19:49 -08002944 if (parent.info.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
2945 parent.info.profileGroupId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002946 writeUserLP(parent);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002947 }
Amith Yamasani12747872015-12-07 14:19:49 -08002948 userInfo.profileGroupId = parent.info.profileGroupId;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002949 } else if (isRestricted) {
Amith Yamasani12747872015-12-07 14:19:49 -08002950 if (parent.info.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) {
2951 parent.info.restrictedProfileParentId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002952 writeUserLP(parent);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002953 }
Amith Yamasani12747872015-12-07 14:19:49 -08002954 userInfo.restrictedProfileParentId = parent.info.restrictedProfileParentId;
Makoto Onuki068c54a2015-10-13 14:34:03 -07002955 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002956 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07002957 }
jovanakdd7e4752019-09-04 12:35:45 -07002958
2959 t.traceBegin("createUserKey");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002960 final StorageManager storage = mContext.getSystemService(StorageManager.class);
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002961 storage.createUserKey(userId, userInfo.serialNumber, userInfo.isEphemeral());
jovanakdd7e4752019-09-04 12:35:45 -07002962 t.traceEnd();
2963
2964 t.traceBegin("prepareUserData");
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -08002965 mUserDataPreparer.prepareUserData(userId, userInfo.serialNumber,
Jeff Sharkey47f71082016-02-01 17:03:54 -07002966 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
jovanakdd7e4752019-09-04 12:35:45 -07002967 t.traceEnd();
2968
Bookatz04d7ae52019-08-05 14:07:12 -07002969 final Set<String> installablePackages =
2970 mSystemPackageInstaller.getInstallablePackagesForUserType(flags);
jovanakdd7e4752019-09-04 12:35:45 -07002971 t.traceBegin("PM.createNewUser");
Bookatz04d7ae52019-08-05 14:07:12 -07002972 mPm.createNewUser(userId, installablePackages, disallowedPackages);
jovanakdd7e4752019-09-04 12:35:45 -07002973 t.traceEnd();
2974
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002975 userInfo.partial = false;
2976 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002977 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002978 }
2979 updateUserIds();
2980 Bundle restrictions = new Bundle();
Fyodor Kupolove04462c2015-11-30 15:02:53 -08002981 if (isGuest) {
2982 synchronized (mGuestRestrictions) {
2983 restrictions.putAll(mGuestRestrictions);
2984 }
2985 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002986 synchronized (mRestrictionsLock) {
2987 mBaseUserRestrictions.append(userId, restrictions);
2988 }
jovanakdd7e4752019-09-04 12:35:45 -07002989
2990 t.traceBegin("PM.onNewUserCreated");
Fyodor Kupolov5fd967d2016-07-12 14:46:19 -07002991 mPm.onNewUserCreated(userId);
jovanakdd7e4752019-09-04 12:35:45 -07002992
Felipe Lemec1ca4412019-09-11 09:23:26 -07002993 if (preCreate) {
2994 // Must start user (which will be stopped right away, through
2995 // UserController.finishUserUnlockedCompleted) so services can properly
2996 // intialize it.
Felipe Lemec6e015d2019-10-21 12:51:08 -07002997 // TODO(b/143092698): in the long-term, it might be better to add a onCreateUser()
2998 // callback on SystemService instead.
Felipe Lemec1ca4412019-09-11 09:23:26 -07002999 Slog.i(LOG_TAG, "starting pre-created user " + userInfo.toFullString());
3000 final IActivityManager am = ActivityManager.getService();
3001 try {
3002 am.startUserInBackground(userId);
3003 } catch (RemoteException e) {
3004 Slog.w(LOG_TAG, "could not start pre-created user " + userId, e);
3005 }
3006 } else {
3007 dispatchUserAddedIntent(userInfo);
3008 }
3009
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07003010 } finally {
3011 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07003012 }
Felipe Lemec1ca4412019-09-11 09:23:26 -07003013
Felipe Lemec6e015d2019-10-21 12:51:08 -07003014 // TODO(b/143092698): it's possible to reach "max users overflow" when the user is created
Felipe Lemec1ca4412019-09-11 09:23:26 -07003015 // "from scratch" (i.e., not from a pre-created user) and reaches the maximum number of
3016 // users without counting the pre-created one. Then when the pre-created is converted, the
3017 // "effective" number of max users is exceeds. Example:
3018 // Max: 3 Current: 2 full (u0 and u10) + 1 pre-created (u11)
3019 // Step 1: create(/* flags doesn't match u11 */): u12 is created, "effective max" is now 3
3020 // (u0, u10, u12) but "real" max is 4 (u0, u10, u11, u12)
3021 // Step 2: create(/* flags match u11 */): u11 is converted, now "effective max" is also 4
3022 // (u0, u10, u11, u12)
3023 // One way to avoid this issue is by removing a pre-created user from the pool when the
3024 // "real" max exceeds the max here.
3025
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003026 return userInfo;
3027 }
3028
Bookatz04d7ae52019-08-05 14:07:12 -07003029 /** Install/uninstall system packages for all users based on their user-type, as applicable. */
3030 boolean installWhitelistedSystemPackages(boolean isFirstBoot, boolean isUpgrade) {
3031 return mSystemPackageInstaller.installWhitelistedSystemPackages(isFirstBoot, isUpgrade);
3032 }
3033
Felipe Lemec1ca4412019-09-11 09:23:26 -07003034 private long getCreationTime() {
3035 final long now = System.currentTimeMillis();
3036 return (now > EPOCH_PLUS_30_YEARS) ? now : 0;
3037 }
3038
3039 private void dispatchUserAddedIntent(@NonNull UserInfo userInfo) {
3040 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
3041 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userInfo.id);
3042 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
3043 android.Manifest.permission.MANAGE_USERS);
3044 MetricsLogger.count(mContext, userInfo.isGuest() ? TRON_GUEST_CREATED
3045 : (userInfo.isDemo() ? TRON_DEMO_CREATED : TRON_USER_CREATED), 1);
3046 }
3047
3048 private boolean areGuestUsersEphemeral() {
3049 return Resources.getSystem()
3050 .getBoolean(com.android.internal.R.bool.config_guestUserEphemeral);
3051 }
3052
3053 /**
3054 * Gets a pre-created user for the given flag.
3055 *
3056 * <p>Should be used only during user creation, so the pre-created user can be used (instead of
3057 * creating and initializing a new user from scratch).
3058 */
Felipe Lemec6e015d2019-10-21 12:51:08 -07003059 // TODO(b/143092698): add unit test
Felipe Lemec1ca4412019-09-11 09:23:26 -07003060 @GuardedBy("mUsersLock")
3061 private @Nullable UserData getPreCreatedUserLU(@UserInfoFlag int flags) {
3062 if (DBG) {
3063 Slog.d(LOG_TAG, "getPreCreatedUser(): initialFlags= " + UserInfo.flagsToString(flags));
3064 }
3065 flags |= UserInfo.FLAG_FULL;
3066 if (UserInfo.isGuest(flags) && areGuestUsersEphemeral()) {
3067 flags |= UserInfo.FLAG_EPHEMERAL;
3068 }
3069 if (DBG) {
3070 Slog.d(LOG_TAG, "getPreCreatedUser(): targetFlags= " + UserInfo.flagsToString(flags));
3071 }
3072 final int userSize = mUsers.size();
3073 for (int i = 0; i < userSize; i++) {
3074 final UserData user = mUsers.valueAt(i);
3075 if (DBG) Slog.d(LOG_TAG, i + ":" + user.info.toFullString());
3076 if (user.info.preCreated
3077 && (user.info.flags & ~UserInfo.FLAG_INITIALIZED) == flags) {
3078 if (!user.info.isInitialized()) {
3079 Slog.w(LOG_TAG, "found pre-created user for flags "
3080 + "" + UserInfo.flagsToString(flags)
3081 + ", but it's not initialized yet: " + user.info.toFullString());
3082 continue;
3083 }
3084 return user;
3085 }
3086 }
3087 return null;
3088 }
3089
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003090 @VisibleForTesting
3091 UserData putUserInfo(UserInfo userInfo) {
3092 final UserData userData = new UserData();
3093 userData.info = userInfo;
3094 synchronized (mUsers) {
3095 mUsers.put(userInfo.id, userData);
3096 }
3097 return userData;
3098 }
3099
3100 @VisibleForTesting
Bookatzf56f2582019-09-04 16:06:41 -07003101 void removeUserInfo(@UserIdInt int userId) {
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003102 synchronized (mUsers) {
3103 mUsers.remove(userId);
3104 }
3105 }
3106
Amith Yamasani0b285492011-04-14 17:35:23 -07003107 /**
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003108 * @hide
3109 */
Amith Yamasani12747872015-12-07 14:19:49 -08003110 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003111 public UserInfo createRestrictedProfile(String name, int parentUserId) {
Sudheer Shanka53d41472016-06-16 09:11:08 -07003112 checkManageOrCreateUsersPermission("setupRestrictedProfile");
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07003113 final UserInfo user = createProfileForUser(
3114 name, UserInfo.FLAG_RESTRICTED, parentUserId, null);
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003115 if (user == null) {
3116 return null;
3117 }
Fyodor Kupolov9e912ba2016-02-09 18:29:43 -08003118 long identity = Binder.clearCallingIdentity();
3119 try {
3120 setUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, true, user.id);
3121 // Change the setting before applying the DISALLOW_SHARE_LOCATION restriction, otherwise
3122 // the putIntForUser() will fail.
3123 android.provider.Settings.Secure.putIntForUser(mContext.getContentResolver(),
3124 android.provider.Settings.Secure.LOCATION_MODE,
3125 android.provider.Settings.Secure.LOCATION_MODE_OFF, user.id);
3126 setUserRestriction(UserManager.DISALLOW_SHARE_LOCATION, true, user.id);
3127 } finally {
3128 Binder.restoreCallingIdentity(identity);
3129 }
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003130 return user;
3131 }
3132
3133 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07003134 * Find the current guest user. If the Guest user is partial,
3135 * then do not include it in the results as it is about to die.
Adam Lesinskieddeb492014-09-08 17:50:03 -07003136 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07003137 private UserInfo findCurrentGuestUser() {
3138 synchronized (mUsersLock) {
3139 final int size = mUsers.size();
3140 for (int i = 0; i < size; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003141 final UserInfo user = mUsers.valueAt(i).info;
Felipe Lemee35f5b02019-10-14 15:37:44 -07003142 if (user.isGuest() && !user.guestToRemove && !user.preCreated
3143 && !mRemovingUserIds.get(user.id)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003144 return user;
3145 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07003146 }
3147 }
3148 return null;
3149 }
3150
3151 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07003152 * Mark this guest user for deletion to allow us to create another guest
3153 * and switch to that user before actually removing this guest.
Bookatzf56f2582019-09-04 16:06:41 -07003154 * @param userId the userid of the current guest
Amith Yamasani1df14732014-08-29 21:37:27 -07003155 * @return whether the user could be marked for deletion
3156 */
Amith Yamasani12747872015-12-07 14:19:49 -08003157 @Override
Bookatzf56f2582019-09-04 16:06:41 -07003158 public boolean markGuestForDeletion(@UserIdInt int userId) {
Amith Yamasani1df14732014-08-29 21:37:27 -07003159 checkManageUsersPermission("Only the system can remove users");
3160 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
3161 UserManager.DISALLOW_REMOVE_USER, false)) {
3162 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
3163 return false;
3164 }
3165
3166 long ident = Binder.clearCallingIdentity();
3167 try {
Amith Yamasani12747872015-12-07 14:19:49 -08003168 final UserData userData;
Amith Yamasani1df14732014-08-29 21:37:27 -07003169 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003170 synchronized (mUsersLock) {
Bookatzf56f2582019-09-04 16:06:41 -07003171 userData = mUsers.get(userId);
3172 if (userId == 0 || userData == null || mRemovingUserIds.get(userId)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003173 return false;
3174 }
Amith Yamasani1df14732014-08-29 21:37:27 -07003175 }
Amith Yamasani12747872015-12-07 14:19:49 -08003176 if (!userData.info.isGuest()) {
Amith Yamasani1df14732014-08-29 21:37:27 -07003177 return false;
3178 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07003179 // We set this to a guest user that is to be removed. This is a temporary state
3180 // where we are allowed to add new Guest users, even if this one is still not
3181 // removed. This user will still show up in getUserInfo() calls.
3182 // If we don't get around to removing this Guest user, it will be purged on next
3183 // startup.
Amith Yamasani12747872015-12-07 14:19:49 -08003184 userData.info.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07003185 // Mark it as disabled, so that it isn't returned any more when
3186 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08003187 userData.info.flags |= UserInfo.FLAG_DISABLED;
3188 writeUserLP(userData);
Amith Yamasani1df14732014-08-29 21:37:27 -07003189 }
3190 } finally {
3191 Binder.restoreCallingIdentity(ident);
3192 }
3193 return true;
3194 }
3195
3196 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07003197 * Removes a user and all data directories created for that user. This method should be called
3198 * after the user's processes have been terminated.
Bookatzf56f2582019-09-04 16:06:41 -07003199 * @param userId the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07003200 */
Amith Yamasani12747872015-12-07 14:19:49 -08003201 @Override
Bookatzf56f2582019-09-04 16:06:41 -07003202 public boolean removeUser(@UserIdInt int userId) {
3203 Slog.i(LOG_TAG, "removeUser u" + userId);
Sudheer Shankaf5cea032016-06-08 17:13:24 -07003204 checkManageOrCreateUsersPermission("Only the system can remove users");
Esteban Talavera6c9116a2016-11-24 16:12:44 +00003205
3206 final boolean isManagedProfile;
3207 synchronized (mUsersLock) {
Bookatzf56f2582019-09-04 16:06:41 -07003208 UserInfo userInfo = getUserInfoLU(userId);
Esteban Talavera6c9116a2016-11-24 16:12:44 +00003209 isManagedProfile = userInfo != null && userInfo.isManagedProfile();
3210 }
3211 String restriction = isManagedProfile
3212 ? UserManager.DISALLOW_REMOVE_MANAGED_PROFILE : UserManager.DISALLOW_REMOVE_USER;
3213 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(restriction, false)) {
3214 Log.w(LOG_TAG, "Cannot remove user. " + restriction + " is enabled.");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04003215 return false;
3216 }
Bookatzf56f2582019-09-04 16:06:41 -07003217 return removeUserUnchecked(userId);
Nicolas Prevotdf1b87d2016-10-25 13:57:08 +01003218 }
Julia Reynolds4ac5f852014-06-23 17:38:51 -04003219
Bookatzf56f2582019-09-04 16:06:41 -07003220 private boolean removeUserUnchecked(@UserIdInt int userId) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01003221 long ident = Binder.clearCallingIdentity();
3222 try {
Amith Yamasani12747872015-12-07 14:19:49 -08003223 final UserData userData;
Fyodor Kupolov0df68cd2015-10-01 13:54:22 -07003224 int currentUser = ActivityManager.getCurrentUser();
Bookatzf56f2582019-09-04 16:06:41 -07003225 if (currentUser == userId) {
jovanaka6763a32018-12-03 17:23:20 -08003226 Log.w(LOG_TAG, "Current user cannot be removed.");
Fyodor Kupolov0df68cd2015-10-01 13:54:22 -07003227 return false;
3228 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01003229 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003230 synchronized (mUsersLock) {
Bookatzf56f2582019-09-04 16:06:41 -07003231 userData = mUsers.get(userId);
3232 if (userId == UserHandle.USER_SYSTEM) {
jovanaka6763a32018-12-03 17:23:20 -08003233 Log.e(LOG_TAG, "System user cannot be removed.");
3234 return false;
3235 }
3236
3237 if (userData == null) {
3238 Log.e(LOG_TAG, String.format(
Bookatzf56f2582019-09-04 16:06:41 -07003239 "Cannot remove user %d, invalid user id provided.", userId));
jovanaka6763a32018-12-03 17:23:20 -08003240 return false;
3241 }
3242
Bookatzf56f2582019-09-04 16:06:41 -07003243 if (mRemovingUserIds.get(userId)) {
jovanaka6763a32018-12-03 17:23:20 -08003244 Log.e(LOG_TAG, String.format(
Bookatzf56f2582019-09-04 16:06:41 -07003245 "User %d is already scheduled for removal.", userId));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003246 return false;
3247 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08003248
Bookatzf56f2582019-09-04 16:06:41 -07003249 addRemovingUserIdLocked(userId);
Fyodor Kupolov82402752015-10-28 14:54:51 -07003250 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08003251
Kenny Guyee58b4f2014-05-23 15:19:53 +01003252 // Set this to a partially created user, so that the user will be purged
3253 // on next startup, in case the runtime stops now before stopping and
3254 // removing the user completely.
Amith Yamasani12747872015-12-07 14:19:49 -08003255 userData.info.partial = true;
Kenny Guyee58b4f2014-05-23 15:19:53 +01003256 // Mark it as disabled, so that it isn't returned any more when
3257 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08003258 userData.info.flags |= UserInfo.FLAG_DISABLED;
3259 writeUserLP(userData);
Kenny Guyee58b4f2014-05-23 15:19:53 +01003260 }
Fyodor Kupolov6c96f7f2017-06-28 18:22:59 -07003261 try {
Bookatzf56f2582019-09-04 16:06:41 -07003262 mAppOpsService.removeUser(userId);
Fyodor Kupolov6c96f7f2017-06-28 18:22:59 -07003263 } catch (RemoteException e) {
jovanaka6763a32018-12-03 17:23:20 -08003264 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user.", e);
Fyodor Kupolov6c96f7f2017-06-28 18:22:59 -07003265 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01003266
Amith Yamasani12747872015-12-07 14:19:49 -08003267 if (userData.info.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
3268 && userData.info.isManagedProfile()) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01003269 // Send broadcast to notify system that the user removed was a
3270 // managed user.
Amith Yamasani12747872015-12-07 14:19:49 -08003271 sendProfileRemovedBroadcast(userData.info.profileGroupId, userData.info.id);
Kenny Guyee58b4f2014-05-23 15:19:53 +01003272 }
3273
Bookatzf56f2582019-09-04 16:06:41 -07003274 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userId);
Kenny Guyee58b4f2014-05-23 15:19:53 +01003275 int res;
3276 try {
Bookatzf56f2582019-09-04 16:06:41 -07003277 res = ActivityManager.getService().stopUser(userId, /* force= */ true,
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07003278 new IStopUserCallback.Stub() {
Kenny Guyee58b4f2014-05-23 15:19:53 +01003279 @Override
Bookatzf56f2582019-09-04 16:06:41 -07003280 public void userStopped(int userIdParam) {
3281 finishRemoveUser(userIdParam);
Kenny Guyee58b4f2014-05-23 15:19:53 +01003282 }
3283 @Override
Bookatzf56f2582019-09-04 16:06:41 -07003284 public void userStopAborted(int userIdParam) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01003285 }
3286 });
3287 } catch (RemoteException e) {
jovanaka6763a32018-12-03 17:23:20 -08003288 Log.w(LOG_TAG, "Failed to stop user during removal.", e);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003289 return false;
3290 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01003291 return res == ActivityManager.USER_OP_SUCCESS;
3292 } finally {
3293 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003294 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003295 }
3296
Andreas Gampea36dc622018-02-05 17:19:22 -08003297 @GuardedBy("mUsersLock")
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003298 @VisibleForTesting
Bookatzf56f2582019-09-04 16:06:41 -07003299 void addRemovingUserIdLocked(@UserIdInt int userId) {
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003300 // We remember deleted user IDs to prevent them from being
3301 // reused during the current boot; they can still be reused
3302 // after a reboot or recycling of userIds.
3303 mRemovingUserIds.put(userId, true);
3304 mRecentlyRemovedIds.add(userId);
3305 // Keep LRU queue of recently removed IDs for recycling
3306 if (mRecentlyRemovedIds.size() > MAX_RECENTLY_REMOVED_IDS_SIZE) {
3307 mRecentlyRemovedIds.removeFirst();
3308 }
3309 }
3310
Bookatzf56f2582019-09-04 16:06:41 -07003311 void finishRemoveUser(final @UserIdInt int userId) {
3312 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userId);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07003313 // Let other services shutdown any activity and clean up their state before completely
3314 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07003315 long ident = Binder.clearCallingIdentity();
3316 try {
3317 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
Bookatzf56f2582019-09-04 16:06:41 -07003318 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07003319 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
3320 android.Manifest.permission.MANAGE_USERS,
3321
3322 new BroadcastReceiver() {
3323 @Override
3324 public void onReceive(Context context, Intent intent) {
3325 if (DBG) {
3326 Slog.i(LOG_TAG,
3327 "USER_REMOVED broadcast sent, cleaning up user data "
Bookatzf56f2582019-09-04 16:06:41 -07003328 + userId);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07003329 }
3330 new Thread() {
Amith Yamasani12747872015-12-07 14:19:49 -08003331 @Override
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07003332 public void run() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003333 // Clean up any ActivityTaskManager state
3334 LocalServices.getService(ActivityTaskManagerInternal.class)
Bookatzf56f2582019-09-04 16:06:41 -07003335 .onUserStopped(userId);
3336 removeUserState(userId);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07003337 }
3338 }.start();
3339 }
3340 },
3341
3342 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07003343 } finally {
3344 Binder.restoreCallingIdentity(ident);
3345 }
Amith Yamasani2a003292012-08-14 18:25:45 -07003346 }
3347
Bookatzf56f2582019-09-04 16:06:41 -07003348 private void removeUserState(final @UserIdInt int userId) {
Paul Crowley91293792016-03-25 15:23:07 -07003349 try {
Bookatzf56f2582019-09-04 16:06:41 -07003350 mContext.getSystemService(StorageManager.class).destroyUserKey(userId);
Paul Crowley91293792016-03-25 15:23:07 -07003351 } catch (IllegalStateException e) {
3352 // This may be simply because the user was partially created.
Bookatzf56f2582019-09-04 16:06:41 -07003353 Slog.i(LOG_TAG, "Destroying key for user " + userId + " failed, continuing anyway", e);
Paul Crowley91293792016-03-25 15:23:07 -07003354 }
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06003355
Amith Yamasanid04aaa32016-06-13 12:09:36 -07003356 // Cleanup gatekeeper secure user id
3357 try {
3358 final IGateKeeperService gk = GateKeeper.getService();
3359 if (gk != null) {
Bookatzf56f2582019-09-04 16:06:41 -07003360 gk.clearSecureUserId(userId);
Amith Yamasanid04aaa32016-06-13 12:09:36 -07003361 }
3362 } catch (Exception ex) {
3363 Slog.w(LOG_TAG, "unable to clear GK secure user id");
3364 }
3365
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003366 // Cleanup package manager settings
Bookatzf56f2582019-09-04 16:06:41 -07003367 mPm.cleanUpUser(this, userId);
Amith Yamasanid04aaa32016-06-13 12:09:36 -07003368
3369 // Clean up all data before removing metadata
Bookatzf56f2582019-09-04 16:06:41 -07003370 mUserDataPreparer.destroyUserData(userId,
Amith Yamasanid04aaa32016-06-13 12:09:36 -07003371 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
3372
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003373 // Remove this user from the list
Fyodor Kupolov82402752015-10-28 14:54:51 -07003374 synchronized (mUsersLock) {
Bookatzf56f2582019-09-04 16:06:41 -07003375 mUsers.remove(userId);
3376 mIsUserManaged.delete(userId);
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003377 }
3378 synchronized (mUserStates) {
Bookatzf56f2582019-09-04 16:06:41 -07003379 mUserStates.delete(userId);
Makoto Onukie7927da2015-11-25 10:05:17 -08003380 }
3381 synchronized (mRestrictionsLock) {
Bookatzf56f2582019-09-04 16:06:41 -07003382 mBaseUserRestrictions.remove(userId);
3383 mAppliedUserRestrictions.remove(userId);
3384 mCachedEffectiveUserRestrictions.remove(userId);
3385 mDevicePolicyLocalUserRestrictions.remove(userId);
3386 if (mDevicePolicyGlobalUserRestrictions.get(userId) != null) {
3387 mDevicePolicyGlobalUserRestrictions.remove(userId);
Pavel Grafov6a40f092016-10-25 15:46:51 +01003388 applyUserRestrictionsForAllUsersLR();
3389 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07003390 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003391 // Update the user list
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003392 synchronized (mPackagesLock) {
3393 writeUserListLP();
3394 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06003395 // Remove user file
Bookatzf56f2582019-09-04 16:06:41 -07003396 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userId + XML_SUFFIX));
Jeff Sharkeycd575992016-03-29 14:12:49 -06003397 userFile.delete();
Fyodor Kupolov82402752015-10-28 14:54:51 -07003398 updateUserIds();
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003399 if (RELEASE_DELETED_USER_ID) {
3400 synchronized (mUsers) {
Bookatzf56f2582019-09-04 16:06:41 -07003401 mRemovingUserIds.delete(userId);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003402 }
3403 }
Amith Yamasani61f57372012-08-31 12:12:28 -07003404 }
3405
Kenny Guyf8d3a232014-05-15 16:09:52 +01003406 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01003407 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01003408 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
3409 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01003410 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
Jeff Sharkeyaf6ec292015-12-17 11:19:00 -07003411 managedProfileIntent.putExtra(Intent.EXTRA_USER_HANDLE, removedUserId);
Kenny Guyf8d3a232014-05-15 16:09:52 +01003412 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01003413 }
3414
Amith Yamasani2a003292012-08-14 18:25:45 -07003415 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07003416 public Bundle getApplicationRestrictions(String packageName) {
3417 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
3418 }
3419
3420 @Override
Bookatzf56f2582019-09-04 16:06:41 -07003421 public Bundle getApplicationRestrictionsForUser(String packageName, @UserIdInt int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003422 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07003423 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07003424 checkSystemOrRoot("get application restrictions for other user/app " + packageName);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003425 }
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003426 synchronized (mAppRestrictionsLock) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003427 // Read the restrictions from XML
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003428 return readApplicationRestrictionsLAr(packageName, userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003429 }
3430 }
3431
3432 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07003433 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Bookatzf56f2582019-09-04 16:06:41 -07003434 @UserIdInt int userId) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00003435 checkSystemOrRoot("set application restrictions");
Fyodor Kupolov0d88d542016-04-19 11:37:22 -07003436 if (restrictions != null) {
3437 restrictions.setDefusable(true);
3438 }
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003439 synchronized (mAppRestrictionsLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01003440 if (restrictions == null || restrictions.isEmpty()) {
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003441 cleanAppRestrictionsForPackageLAr(packageName, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01003442 } else {
3443 // Write the restrictions to XML
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003444 writeApplicationRestrictionsLAr(packageName, restrictions, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01003445 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003446 }
Robin Lee66e5d962014-04-09 16:44:21 +01003447
Fyodor Kupolovd2846122016-02-11 18:06:34 -08003448 // Notify package of changes via an intent - only sent to explicitly registered receivers.
3449 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
3450 changeIntent.setPackage(packageName);
3451 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3452 mContext.sendBroadcastAsUser(changeIntent, UserHandle.of(userId));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003453 }
3454
3455 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07003456 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003457 try {
3458 return mContext.getPackageManager().getApplicationInfo(packageName,
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07003459 PackageManager.MATCH_ANY_USER).uid;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003460 } catch (NameNotFoundException nnfe) {
3461 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07003462 } finally {
3463 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003464 }
3465 }
3466
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003467 @GuardedBy("mAppRestrictionsLock")
Bookatzf56f2582019-09-04 16:06:41 -07003468 private static Bundle readApplicationRestrictionsLAr(String packageName,
3469 @UserIdInt int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003470 AtomicFile restrictionsFile =
3471 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
3472 packageToRestrictionsFileName(packageName)));
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003473 return readApplicationRestrictionsLAr(restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003474 }
3475
3476 @VisibleForTesting
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003477 @GuardedBy("mAppRestrictionsLock")
3478 static Bundle readApplicationRestrictionsLAr(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07003479 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003480 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07003481 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07003482 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07003483 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003484
3485 FileInputStream fis = null;
3486 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003487 fis = restrictionsFile.openRead();
3488 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01003489 parser.setInput(fis, StandardCharsets.UTF_8.name());
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003490 XmlUtils.nextElement(parser);
3491 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003492 Slog.e(LOG_TAG, "Unable to read restrictions file "
3493 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07003494 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003495 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003496 while (parser.next() != XmlPullParser.END_DOCUMENT) {
3497 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003498 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003499 } catch (IOException|XmlPullParserException e) {
3500 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003501 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003502 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003503 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07003504 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003505 }
3506
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003507 private static void readEntry(Bundle restrictions, ArrayList<String> values,
3508 XmlPullParser parser) throws XmlPullParserException, IOException {
3509 int type = parser.getEventType();
3510 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
3511 String key = parser.getAttributeValue(null, ATTR_KEY);
3512 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
3513 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
3514 if (multiple != null) {
3515 values.clear();
3516 int count = Integer.parseInt(multiple);
3517 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
3518 if (type == XmlPullParser.START_TAG
3519 && parser.getName().equals(TAG_VALUE)) {
3520 values.add(parser.nextText().trim());
3521 count--;
3522 }
3523 }
3524 String [] valueStrings = new String[values.size()];
3525 values.toArray(valueStrings);
3526 restrictions.putStringArray(key, valueStrings);
3527 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
3528 restrictions.putBundle(key, readBundleEntry(parser, values));
3529 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
3530 final int outerDepth = parser.getDepth();
3531 ArrayList<Bundle> bundleList = new ArrayList<>();
3532 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
3533 Bundle childBundle = readBundleEntry(parser, values);
3534 bundleList.add(childBundle);
3535 }
3536 restrictions.putParcelableArray(key,
3537 bundleList.toArray(new Bundle[bundleList.size()]));
3538 } else {
3539 String value = parser.nextText().trim();
3540 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
3541 restrictions.putBoolean(key, Boolean.parseBoolean(value));
3542 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
3543 restrictions.putInt(key, Integer.parseInt(value));
3544 } else {
3545 restrictions.putString(key, value);
3546 }
3547 }
3548 }
3549 }
3550
3551 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
3552 throws IOException, XmlPullParserException {
3553 Bundle childBundle = new Bundle();
3554 final int outerDepth = parser.getDepth();
3555 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
3556 readEntry(childBundle, values, parser);
3557 }
3558 return childBundle;
3559 }
3560
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003561 @GuardedBy("mAppRestrictionsLock")
3562 private static void writeApplicationRestrictionsLAr(String packageName,
Bookatzf56f2582019-09-04 16:06:41 -07003563 Bundle restrictions, @UserIdInt int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003564 AtomicFile restrictionsFile = new AtomicFile(
3565 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07003566 packageToRestrictionsFileName(packageName)));
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003567 writeApplicationRestrictionsLAr(restrictions, restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003568 }
3569
3570 @VisibleForTesting
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003571 @GuardedBy("mAppRestrictionsLock")
3572 static void writeApplicationRestrictionsLAr(Bundle restrictions, AtomicFile restrictionsFile) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003573 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003574 try {
3575 fos = restrictionsFile.startWrite();
3576 final BufferedOutputStream bos = new BufferedOutputStream(fos);
3577
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003578 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01003579 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003580 serializer.startDocument(null, true);
3581 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
3582
3583 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003584 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003585 serializer.endTag(null, TAG_RESTRICTIONS);
3586
3587 serializer.endDocument();
3588 restrictionsFile.finishWrite(fos);
3589 } catch (Exception e) {
3590 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003591 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
3592 }
3593 }
3594
3595 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
3596 throws IOException {
3597 for (String key : restrictions.keySet()) {
3598 Object value = restrictions.get(key);
3599 serializer.startTag(null, TAG_ENTRY);
3600 serializer.attribute(null, ATTR_KEY, key);
3601
3602 if (value instanceof Boolean) {
3603 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
3604 serializer.text(value.toString());
3605 } else if (value instanceof Integer) {
3606 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
3607 serializer.text(value.toString());
3608 } else if (value == null || value instanceof String) {
3609 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
3610 serializer.text(value != null ? (String) value : "");
3611 } else if (value instanceof Bundle) {
3612 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
3613 writeBundle((Bundle) value, serializer);
3614 } else if (value instanceof Parcelable[]) {
3615 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
3616 Parcelable[] array = (Parcelable[]) value;
3617 for (Parcelable parcelable : array) {
3618 if (!(parcelable instanceof Bundle)) {
3619 throw new IllegalArgumentException("bundle-array can only hold Bundles");
3620 }
3621 serializer.startTag(null, TAG_ENTRY);
3622 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
3623 writeBundle((Bundle) parcelable, serializer);
3624 serializer.endTag(null, TAG_ENTRY);
3625 }
3626 } else {
3627 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
3628 String[] values = (String[]) value;
3629 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
3630 for (String choice : values) {
3631 serializer.startTag(null, TAG_VALUE);
3632 serializer.text(choice != null ? choice : "");
3633 serializer.endTag(null, TAG_VALUE);
3634 }
3635 }
3636 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003637 }
3638 }
3639
3640 @Override
Bookatzf56f2582019-09-04 16:06:41 -07003641 public int getUserSerialNumber(@UserIdInt int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003642 synchronized (mUsersLock) {
Bookatzf56f2582019-09-04 16:06:41 -07003643 final UserInfo userInfo = getUserInfoLU(userId);
Pavel Grafov9c295d42019-03-26 19:42:08 +00003644 return userInfo != null ? userInfo.serialNumber : -1;
Amith Yamasani2a003292012-08-14 18:25:45 -07003645 }
3646 }
3647
3648 @Override
Bookatzf56f2582019-09-04 16:06:41 -07003649 public boolean isUserNameSet(@UserIdInt int userId) {
Fyodor Kupolov605b12a2017-05-10 15:58:09 -07003650 synchronized (mUsersLock) {
Bookatzf56f2582019-09-04 16:06:41 -07003651 final UserInfo userInfo = getUserInfoLU(userId);
Fyodor Kupolov605b12a2017-05-10 15:58:09 -07003652 return userInfo != null && userInfo.name != null;
3653 }
3654 }
3655
3656 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07003657 public int getUserHandle(int userSerialNumber) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003658 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07003659 for (int userId : mUserIds) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003660 UserInfo info = getUserInfoLU(userId);
Kenny Guy945f8832015-02-10 15:17:26 +00003661 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07003662 }
3663 // Not found
3664 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07003665 }
3666 }
3667
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003668 @Override
Bookatzf56f2582019-09-04 16:06:41 -07003669 public long getUserCreationTime(@UserIdInt int userId) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003670 int callingUserId = UserHandle.getCallingUserId();
3671 UserInfo userInfo = null;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003672 synchronized (mUsersLock) {
Bookatzf56f2582019-09-04 16:06:41 -07003673 if (callingUserId == userId) {
3674 userInfo = getUserInfoLU(userId);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003675 } else {
Bookatzf56f2582019-09-04 16:06:41 -07003676 UserInfo parent = getProfileParentLU(userId);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003677 if (parent != null && parent.id == callingUserId) {
Bookatzf56f2582019-09-04 16:06:41 -07003678 userInfo = getUserInfoLU(userId);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003679 }
3680 }
3681 }
3682 if (userInfo == null) {
Bookatzf56f2582019-09-04 16:06:41 -07003683 throw new SecurityException("userId can only be the calling user or a managed "
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003684 + "profile associated with this user");
3685 }
3686 return userInfo.creationTime;
3687 }
3688
Amith Yamasani0b285492011-04-14 17:35:23 -07003689 /**
3690 * Caches the list of user ids in an array, adjusting the array size when necessary.
3691 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07003692 private void updateUserIds() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003693 int num = 0;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003694 synchronized (mUsersLock) {
3695 final int userSize = mUsers.size();
3696 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003697 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003698 num++;
3699 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003700 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07003701 final int[] newUsers = new int[num];
3702 int n = 0;
3703 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003704 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003705 newUsers[n++] = mUsers.keyAt(i);
3706 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003707 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07003708 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07003709 }
3710 }
3711
3712 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003713 * Called right before a user is started. This gives us a chance to prepare
3714 * app storage and apply any user restrictions.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003715 */
Bookatzf56f2582019-09-04 16:06:41 -07003716 public void onBeforeStartUser(@UserIdInt int userId) {
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003717 UserInfo userInfo = getUserInfo(userId);
3718 if (userInfo == null) {
3719 return;
3720 }
Felipe Leme3aad1be2019-05-31 11:43:12 -07003721 TimingsTraceAndSlog t = new TimingsTraceAndSlog();
3722 t.traceBegin("onBeforeStartUser-" + userId);
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003723 final int userSerial = userInfo.serialNumber;
3724 // Migrate only if build fingerprints mismatch
3725 boolean migrateAppsData = !Build.FINGERPRINT.equals(userInfo.lastLoggedInFingerprint);
Felipe Leme3aad1be2019-05-31 11:43:12 -07003726 t.traceBegin("prepareUserData");
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -08003727 mUserDataPreparer.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_DE);
Felipe Leme3aad1be2019-05-31 11:43:12 -07003728 t.traceEnd();
3729 t.traceBegin("reconcileAppsData");
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003730 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_DE, migrateAppsData);
Felipe Leme3aad1be2019-05-31 11:43:12 -07003731 t.traceEnd();
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003732
3733 if (userId != UserHandle.USER_SYSTEM) {
Felipe Leme3aad1be2019-05-31 11:43:12 -07003734 t.traceBegin("applyUserRestrictions");
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003735 synchronized (mRestrictionsLock) {
3736 applyUserRestrictionsLR(userId);
3737 }
Felipe Leme3aad1be2019-05-31 11:43:12 -07003738 t.traceEnd();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003739 }
Felipe Leme3aad1be2019-05-31 11:43:12 -07003740 t.traceEnd(); // onBeforeStartUser
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003741 }
3742
3743 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003744 * Called right before a user is unlocked. This gives us a chance to prepare
3745 * app storage.
3746 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003747 public void onBeforeUnlockUser(@UserIdInt int userId) {
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003748 UserInfo userInfo = getUserInfo(userId);
3749 if (userInfo == null) {
3750 return;
3751 }
3752 final int userSerial = userInfo.serialNumber;
3753 // Migrate only if build fingerprints mismatch
3754 boolean migrateAppsData = !Build.FINGERPRINT.equals(userInfo.lastLoggedInFingerprint);
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -08003755 mUserDataPreparer.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_CE);
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003756 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_CE, migrateAppsData);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003757 }
3758
3759 /**
Fyodor Kupolov50979d12017-01-27 17:36:32 -08003760 * Examine all users present on given mounted volume, and destroy data
3761 * belonging to users that are no longer valid, or whose user ID has been
3762 * recycled.
3763 */
3764 void reconcileUsers(String volumeUuid) {
3765 mUserDataPreparer.reconcileUsers(volumeUuid, getUsers(true /* excludeDying */));
3766 }
3767
3768 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07003769 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasanieb437d42016-04-29 09:31:25 -07003770 * This is called with ActivityManagerService lock held.
Amith Yamasani920ace02012-09-20 22:15:37 -07003771 * @param userId the user that was just foregrounded
3772 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003773 public void onUserLoggedIn(@UserIdInt int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -08003774 UserData userData = getUserDataNoChecks(userId);
3775 if (userData == null || userData.info.partial) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003776 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
3777 return;
3778 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003779
3780 final long now = System.currentTimeMillis();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003781 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani12747872015-12-07 14:19:49 -08003782 userData.info.lastLoggedInTime = now;
Amith Yamasani920ace02012-09-20 22:15:37 -07003783 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003784 userData.info.lastLoggedInFingerprint = Build.FINGERPRINT;
3785 scheduleWriteUser(userData);
Amith Yamasani920ace02012-09-20 22:15:37 -07003786 }
3787
3788 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07003789 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani0b285492011-04-14 17:35:23 -07003790 */
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003791 @VisibleForTesting
3792 int getNextAvailableId() {
3793 int nextId;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003794 synchronized (mUsersLock) {
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003795 nextId = scanNextAvailableIdLocked();
3796 if (nextId >= 0) {
3797 return nextId;
3798 }
3799 // All ids up to MAX_USER_ID were used. Remove all mRemovingUserIds,
3800 // except most recently removed
3801 if (mRemovingUserIds.size() > 0) {
3802 Slog.i(LOG_TAG, "All available IDs are used. Recycling LRU ids.");
3803 mRemovingUserIds.clear();
3804 for (Integer recentlyRemovedId : mRecentlyRemovedIds) {
3805 mRemovingUserIds.put(recentlyRemovedId, true);
Amith Yamasani195263742012-08-21 15:40:12 -07003806 }
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003807 nextId = scanNextAvailableIdLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003808 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003809 }
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003810 if (nextId < 0) {
3811 throw new IllegalStateException("No user id available!");
3812 }
3813 return nextId;
3814 }
3815
Andreas Gampea36dc622018-02-05 17:19:22 -08003816 @GuardedBy("mUsersLock")
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003817 private int scanNextAvailableIdLocked() {
3818 for (int i = MIN_USER_ID; i < MAX_USER_ID; i++) {
3819 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
3820 return i;
3821 }
3822 }
3823 return -1;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003824 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003825
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003826 private static String packageToRestrictionsFileName(String packageName) {
Amith Yamasanifc95e702013-09-26 13:20:17 -07003827 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
3828 }
3829
Amith Yamasani920ace02012-09-20 22:15:37 -07003830 @Override
Bookatzf56f2582019-09-04 16:06:41 -07003831 public void setSeedAccountData(@UserIdInt int userId, String accountName, String accountType,
Amith Yamasani12747872015-12-07 14:19:49 -08003832 PersistableBundle accountOptions, boolean persist) {
3833 checkManageUsersPermission("Require MANAGE_USERS permission to set user seed data");
3834 synchronized (mPackagesLock) {
3835 final UserData userData;
3836 synchronized (mUsersLock) {
3837 userData = getUserDataLU(userId);
3838 if (userData == null) {
3839 Slog.e(LOG_TAG, "No such user for settings seed data u=" + userId);
3840 return;
3841 }
3842 userData.seedAccountName = accountName;
3843 userData.seedAccountType = accountType;
3844 userData.seedAccountOptions = accountOptions;
3845 userData.persistSeedData = persist;
3846 }
3847 if (persist) {
3848 writeUserLP(userData);
3849 }
3850 }
3851 }
3852
3853 @Override
3854 public String getSeedAccountName() throws RemoteException {
3855 checkManageUsersPermission("Cannot get seed account information");
3856 synchronized (mUsersLock) {
3857 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3858 return userData.seedAccountName;
3859 }
3860 }
3861
3862 @Override
3863 public String getSeedAccountType() throws RemoteException {
3864 checkManageUsersPermission("Cannot get seed account information");
3865 synchronized (mUsersLock) {
3866 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3867 return userData.seedAccountType;
3868 }
3869 }
3870
3871 @Override
3872 public PersistableBundle getSeedAccountOptions() throws RemoteException {
3873 checkManageUsersPermission("Cannot get seed account information");
3874 synchronized (mUsersLock) {
3875 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3876 return userData.seedAccountOptions;
3877 }
3878 }
3879
3880 @Override
3881 public void clearSeedAccountData() throws RemoteException {
3882 checkManageUsersPermission("Cannot clear seed account information");
3883 synchronized (mPackagesLock) {
3884 UserData userData;
3885 synchronized (mUsersLock) {
3886 userData = getUserDataLU(UserHandle.getCallingUserId());
3887 if (userData == null) return;
3888 userData.clearSeedAccountData();
3889 }
3890 writeUserLP(userData);
3891 }
3892 }
3893
3894 @Override
3895 public boolean someUserHasSeedAccount(String accountName, String accountType)
3896 throws RemoteException {
3897 checkManageUsersPermission("Cannot check seed account information");
3898 synchronized (mUsersLock) {
3899 final int userSize = mUsers.size();
3900 for (int i = 0; i < userSize; i++) {
3901 final UserData data = mUsers.valueAt(i);
3902 if (data.info.isInitialized()) continue;
3903 if (data.seedAccountName == null || !data.seedAccountName.equals(accountName)) {
3904 continue;
3905 }
3906 if (data.seedAccountType == null || !data.seedAccountType.equals(accountType)) {
3907 continue;
3908 }
3909 return true;
3910 }
3911 }
3912 return false;
3913 }
3914
3915 @Override
Todd Kennedy60459ab2015-10-30 11:32:16 -07003916 public void onShellCommand(FileDescriptor in, FileDescriptor out,
Dianne Hackborn354736e2016-08-22 17:00:05 -07003917 FileDescriptor err, String[] args, ShellCallback callback,
3918 ResultReceiver resultReceiver) {
3919 (new Shell()).exec(this, in, out, err, args, callback, resultReceiver);
Todd Kennedy60459ab2015-10-30 11:32:16 -07003920 }
3921
3922 int onShellCommand(Shell shell, String cmd) {
3923 if (cmd == null) {
3924 return shell.handleDefaultCommands(cmd);
3925 }
3926
3927 final PrintWriter pw = shell.getOutPrintWriter();
3928 try {
3929 switch(cmd) {
3930 case "list":
Felipe Lemec1ca4412019-09-11 09:23:26 -07003931 return runList(pw, shell);
Hui Yu8ba65972018-04-16 18:45:48 -07003932 default:
3933 return shell.handleDefaultCommands(cmd);
Todd Kennedy60459ab2015-10-30 11:32:16 -07003934 }
3935 } catch (RemoteException e) {
3936 pw.println("Remote exception: " + e);
3937 }
3938 return -1;
3939 }
3940
Felipe Lemec1ca4412019-09-11 09:23:26 -07003941 private int runList(PrintWriter pw, Shell shell) throws RemoteException {
3942 boolean all = false;
3943 boolean verbose = false;
3944 String opt;
3945 while ((opt = shell.getNextOption()) != null) {
3946 switch (opt) {
3947 case "-v":
3948 verbose = true;
3949 break;
3950 case "--all":
3951 all = true;
3952 break;
3953 default:
3954 pw.println("Invalid option: " + opt);
3955 return -1;
3956 }
3957 }
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003958 final IActivityManager am = ActivityManager.getService();
Felipe Lemec1ca4412019-09-11 09:23:26 -07003959 final List<UserInfo> users = getUsers(/* excludePartial= */ !all,
3960 /* excludingDying=*/ false, /* excludePreCreated= */ !all);
Todd Kennedy60459ab2015-10-30 11:32:16 -07003961 if (users == null) {
3962 pw.println("Error: couldn't get users");
3963 return 1;
3964 } else {
Felipe Lemec1ca4412019-09-11 09:23:26 -07003965 final int size = users.size();
3966 int currentUser = UserHandle.USER_NULL;
3967 if (verbose) {
3968 pw.printf("%d users:\n\n", size);
3969 currentUser = am.getCurrentUser().id;
3970 } else {
3971 // NOTE: the standard "list users" command is used by integration tests and
3972 // hence should not be changed. If you need to add more info, use the
3973 // verbose option.
3974 pw.println("Users:");
3975 }
3976 for (int i = 0; i < size; i++) {
3977 final UserInfo user = users.get(i);
3978 final boolean running = am.isUserRunning(user.id, 0);
3979 final boolean current = user.id == currentUser;
3980 if (verbose) {
3981 pw.printf("%d: id=%d, name=%s, flags=%s%s%s%s%s\n", i, user.id, user.name,
3982 UserInfo.flagsToString(user.flags),
3983 running ? " (running)" : "",
3984 user.partial ? " (partial)" : "",
3985 user.preCreated ? " (pre-created)" : "",
3986 current ? " (current)" : "");
3987 } else {
3988 // NOTE: the standard "list users" command is used by integration tests and
3989 // hence should not be changed. If you need to add more info, use the
3990 // verbose option.
3991 pw.printf("\t%s%s\n", user, running ? " running" : "");
3992 }
Todd Kennedy60459ab2015-10-30 11:32:16 -07003993 }
3994 return 0;
3995 }
3996 }
3997
3998 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -07003999 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06004000 if (!DumpUtils.checkDumpPermission(mContext, LOG_TAG, pw)) return;
Amith Yamasani920ace02012-09-20 22:15:37 -07004001
4002 long now = System.currentTimeMillis();
Makoto Onuki73dded22017-12-20 13:14:48 +09004003 final long nowRealtime = SystemClock.elapsedRealtime();
Felipe Lemed7b88382019-06-12 17:40:53 -07004004
Felipe Leme5b8dc762019-10-04 16:23:16 -07004005 final ActivityManagerInternal amInternal = LocalServices
4006 .getService(ActivityManagerInternal.class);
4007 pw.print("Current user: ");
4008 if (amInternal != null) {
4009 pw.println(amInternal.getCurrentUserId());
4010 } else {
4011 pw.println("N/A");
4012 }
Felipe Lemed7b88382019-06-12 17:40:53 -07004013
Amith Yamasani920ace02012-09-20 22:15:37 -07004014 StringBuilder sb = new StringBuilder();
4015 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07004016 synchronized (mUsersLock) {
4017 pw.println("Users:");
4018 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08004019 UserData userData = mUsers.valueAt(i);
4020 if (userData == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07004021 continue;
4022 }
Amith Yamasani12747872015-12-07 14:19:49 -08004023 UserInfo userInfo = userData.info;
4024 final int userId = userInfo.id;
4025 pw.print(" "); pw.print(userInfo);
4026 pw.print(" serialNo="); pw.print(userInfo.serialNumber);
Felipe Lemed7b88382019-06-12 17:40:53 -07004027 pw.print(" isPrimary="); pw.print(userInfo.isPrimary());
Makoto Onukie7927da2015-11-25 10:05:17 -08004028 if (mRemovingUserIds.get(userId)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07004029 pw.print(" <removing> ");
4030 }
Amith Yamasani12747872015-12-07 14:19:49 -08004031 if (userInfo.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07004032 pw.print(" <partial>");
4033 }
Felipe Lemec1ca4412019-09-11 09:23:26 -07004034 if (userInfo.preCreated) {
4035 pw.print(" <pre-created>");
4036 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07004037 pw.println();
Felipe Lemee5434c32019-08-13 09:28:33 -07004038 pw.print(" Flags: "); pw.print(userInfo.flags); pw.print(" (");
4039 pw.print(UserInfo.flagsToString(userInfo.flags)); pw.println(")");
Makoto Onuki88aef752017-03-29 16:52:03 -07004040 pw.print(" State: ");
4041 final int state;
4042 synchronized (mUserStates) {
4043 state = mUserStates.get(userId, -1);
4044 }
4045 pw.println(UserState.stateToString(state));
Fyodor Kupolov82402752015-10-28 14:54:51 -07004046 pw.print(" Created: ");
Makoto Onuki73dded22017-12-20 13:14:48 +09004047 dumpTimeAgo(pw, sb, now, userInfo.creationTime);
4048
Fyodor Kupolov82402752015-10-28 14:54:51 -07004049 pw.print(" Last logged in: ");
Makoto Onuki73dded22017-12-20 13:14:48 +09004050 dumpTimeAgo(pw, sb, now, userInfo.lastLoggedInTime);
4051
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06004052 pw.print(" Last logged in fingerprint: ");
4053 pw.println(userInfo.lastLoggedInFingerprint);
Makoto Onuki73dded22017-12-20 13:14:48 +09004054
4055 pw.print(" Start time: ");
4056 dumpTimeAgo(pw, sb, nowRealtime, userData.startRealtime);
4057
4058 pw.print(" Unlock time: ");
4059 dumpTimeAgo(pw, sb, nowRealtime, userData.unlockRealtime);
4060
Makoto Onukie7927da2015-11-25 10:05:17 -08004061 pw.print(" Has profile owner: ");
4062 pw.println(mIsUserManaged.get(userId));
Fyodor Kupolov82402752015-10-28 14:54:51 -07004063 pw.println(" Restrictions:");
4064 synchronized (mRestrictionsLock) {
4065 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08004066 pw, " ", mBaseUserRestrictions.get(userInfo.id));
Pavel Grafov6a40f092016-10-25 15:46:51 +01004067 pw.println(" Device policy global restrictions:");
4068 UserRestrictionsUtils.dumpRestrictions(
4069 pw, " ", mDevicePolicyGlobalUserRestrictions.get(userInfo.id));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08004070 pw.println(" Device policy local restrictions:");
4071 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08004072 pw, " ", mDevicePolicyLocalUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07004073 pw.println(" Effective restrictions:");
4074 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08004075 pw, " ", mCachedEffectiveUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07004076 }
Amith Yamasani12747872015-12-07 14:19:49 -08004077
4078 if (userData.account != null) {
4079 pw.print(" Account name: " + userData.account);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08004080 pw.println();
4081 }
Amith Yamasani12747872015-12-07 14:19:49 -08004082
4083 if (userData.seedAccountName != null) {
4084 pw.print(" Seed account name: " + userData.seedAccountName);
4085 pw.println();
4086 if (userData.seedAccountType != null) {
4087 pw.print(" account type: " + userData.seedAccountType);
4088 pw.println();
4089 }
4090 if (userData.seedAccountOptions != null) {
4091 pw.print(" account options exist");
4092 pw.println();
4093 }
4094 }
Amith Yamasani920ace02012-09-20 22:15:37 -07004095 }
Amith Yamasani920ace02012-09-20 22:15:37 -07004096 }
Amith Yamasani12747872015-12-07 14:19:49 -08004097 pw.println();
Pavel Grafov6a40f092016-10-25 15:46:51 +01004098 pw.println(" Device owner id:" + mDeviceOwnerUserId);
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01004099 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08004100 pw.println(" Guest restrictions:");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08004101 synchronized (mGuestRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08004102 UserRestrictionsUtils.dumpRestrictions(pw, " ", mGuestRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08004103 }
Makoto Onukie7927da2015-11-25 10:05:17 -08004104 synchronized (mUsersLock) {
4105 pw.println();
4106 pw.println(" Device managed: " + mIsDeviceManaged);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07004107 if (mRemovingUserIds.size() > 0) {
4108 pw.println();
4109 pw.println(" Recently removed userIds: " + mRecentlyRemovedIds);
4110 }
Makoto Onukie7927da2015-11-25 10:05:17 -08004111 }
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00004112 synchronized (mUserStates) {
4113 pw.println(" Started users state: " + mUserStates);
4114 }
Felipe Lemed7b88382019-06-12 17:40:53 -07004115 } // synchronized (mPackagesLock)
4116
4117 // Dump some capabilities
4118 pw.println();
Felipe Lemec1ca4412019-09-11 09:23:26 -07004119 pw.print(" Max users: " + UserManager.getMaxSupportedUsers());
4120 pw.println(" (limit reached: " + isUserLimitReached() + ")");
Felipe Lemed7b88382019-06-12 17:40:53 -07004121 pw.println(" Supports switchable users: " + UserManager.supportsMultipleUsers());
Felipe Lemec1ca4412019-09-11 09:23:26 -07004122 pw.println(" All guests ephemeral: " + areGuestUsersEphemeral());
Felipe Lemed7b88382019-06-12 17:40:53 -07004123 pw.println(" Is split-system user: " + UserManager.isSplitSystemUser());
Felipe Lemee5434c32019-08-13 09:28:33 -07004124 pw.println(" Is headless-system mode: " + UserManager.isHeadlessSystemUserMode());
4125 pw.println(" User version: " + mUserVersion);
Bookatz04d7ae52019-08-05 14:07:12 -07004126
4127 // Dump package whitelist
4128 pw.println();
4129 mSystemPackageInstaller.dump(pw);
Amith Yamasani920ace02012-09-20 22:15:37 -07004130 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08004131
Makoto Onuki73dded22017-12-20 13:14:48 +09004132 private static void dumpTimeAgo(PrintWriter pw, StringBuilder sb, long nowTime, long time) {
4133 if (time == 0) {
4134 pw.println("<unknown>");
4135 } else {
4136 sb.setLength(0);
4137 TimeUtils.formatDuration(nowTime - time, sb);
4138 sb.append(" ago");
4139 pw.println(sb);
4140 }
4141 }
4142
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08004143 final class MainHandler extends Handler {
4144
4145 @Override
4146 public void handleMessage(Message msg) {
4147 switch (msg.what) {
4148 case WRITE_USER_MSG:
4149 removeMessages(WRITE_USER_MSG, msg.obj);
4150 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08004151 int userId = ((UserData) msg.obj).info.id;
4152 UserData userData = getUserDataNoChecks(userId);
4153 if (userData != null) {
4154 writeUserLP(userData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08004155 }
4156 }
4157 }
4158 }
4159 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07004160
4161 /**
4162 * @param userId
4163 * @return whether the user has been initialized yet
4164 */
Bookatzf56f2582019-09-04 16:06:41 -07004165 boolean isUserInitialized(@UserIdInt int userId) {
Todd Kennedy0eb97382017-10-03 16:57:22 -07004166 return mLocalService.isUserInitialized(userId);
Amith Yamasanibb054c92015-07-09 14:16:27 -07004167 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07004168
4169 private class LocalService extends UserManagerInternal {
Makoto Onuki068c54a2015-10-13 14:34:03 -07004170 @Override
Bookatzf56f2582019-09-04 16:06:41 -07004171 public void setDevicePolicyUserRestrictions(@UserIdInt int userId,
4172 @Nullable Bundle restrictions, boolean isDeviceOwner, int cameraRestrictionScope) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01004173 UserManagerService.this.setDevicePolicyUserRestrictionsInner(userId, restrictions,
4174 isDeviceOwner, cameraRestrictionScope);
Makoto Onuki068c54a2015-10-13 14:34:03 -07004175 }
4176
4177 @Override
Bookatzf56f2582019-09-04 16:06:41 -07004178 public Bundle getBaseUserRestrictions(@UserIdInt int userId) {
Makoto Onuki068c54a2015-10-13 14:34:03 -07004179 synchronized (mRestrictionsLock) {
4180 return mBaseUserRestrictions.get(userId);
4181 }
4182 }
4183
4184 @Override
4185 public void setBaseUserRestrictionsByDpmsForMigration(
Bookatzf56f2582019-09-04 16:06:41 -07004186 @UserIdInt int userId, Bundle baseRestrictions) {
Makoto Onuki068c54a2015-10-13 14:34:03 -07004187 synchronized (mRestrictionsLock) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01004188 if (updateRestrictionsIfNeededLR(
4189 userId, new Bundle(baseRestrictions), mBaseUserRestrictions)) {
4190 invalidateEffectiveUserRestrictionsLR(userId);
4191 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07004192 }
4193
Amith Yamasani12747872015-12-07 14:19:49 -08004194 final UserData userData = getUserDataNoChecks(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07004195 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08004196 if (userData != null) {
4197 writeUserLP(userData);
Makoto Onuki068c54a2015-10-13 14:34:03 -07004198 } else {
4199 Slog.w(LOG_TAG, "UserInfo not found for " + userId);
4200 }
4201 }
4202 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08004203
4204 @Override
Bookatzf56f2582019-09-04 16:06:41 -07004205 public boolean getUserRestriction(@UserIdInt int userId, String key) {
Makoto Onukid45a4a22015-11-02 17:17:38 -08004206 return getUserRestrictions(userId).getBoolean(key);
4207 }
4208
4209 @Override
4210 public void addUserRestrictionsListener(UserRestrictionsListener listener) {
4211 synchronized (mUserRestrictionsListeners) {
4212 mUserRestrictionsListeners.add(listener);
4213 }
4214 }
4215
4216 @Override
4217 public void removeUserRestrictionsListener(UserRestrictionsListener listener) {
4218 synchronized (mUserRestrictionsListeners) {
4219 mUserRestrictionsListeners.remove(listener);
4220 }
4221 }
Makoto Onukie7927da2015-11-25 10:05:17 -08004222
4223 @Override
4224 public void setDeviceManaged(boolean isManaged) {
4225 synchronized (mUsersLock) {
4226 mIsDeviceManaged = isManaged;
4227 }
4228 }
4229
4230 @Override
Rubin Xu0f1e56d2019-08-23 13:34:25 +01004231 public boolean isDeviceManaged() {
4232 synchronized (mUsersLock) {
4233 return mIsDeviceManaged;
4234 }
4235 }
4236
4237 @Override
Bookatzf56f2582019-09-04 16:06:41 -07004238 public void setUserManaged(@UserIdInt int userId, boolean isManaged) {
Makoto Onukie7927da2015-11-25 10:05:17 -08004239 synchronized (mUsersLock) {
4240 mIsUserManaged.put(userId, isManaged);
4241 }
4242 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01004243
4244 @Override
Rubin Xu0f1e56d2019-08-23 13:34:25 +01004245 public boolean isUserManaged(@UserIdInt int userId) {
4246 synchronized (mUsersLock) {
4247 return mIsUserManaged.get(userId);
4248 }
4249 }
4250
4251 @Override
Bookatzf56f2582019-09-04 16:06:41 -07004252 public void setUserIcon(@UserIdInt int userId, Bitmap bitmap) {
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01004253 long ident = Binder.clearCallingIdentity();
4254 try {
4255 synchronized (mPackagesLock) {
4256 UserData userData = getUserDataNoChecks(userId);
4257 if (userData == null || userData.info.partial) {
4258 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
4259 return;
4260 }
4261 writeBitmapLP(userData.info, bitmap);
4262 writeUserLP(userData);
4263 }
4264 sendUserInfoChangedBroadcast(userId);
4265 } finally {
4266 Binder.restoreCallingIdentity(ident);
4267 }
4268 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01004269
4270 @Override
4271 public void setForceEphemeralUsers(boolean forceEphemeralUsers) {
4272 synchronized (mUsersLock) {
4273 mForceEphemeralUsers = forceEphemeralUsers;
4274 }
4275 }
4276
4277 @Override
4278 public void removeAllUsers() {
4279 if (UserHandle.USER_SYSTEM == ActivityManager.getCurrentUser()) {
4280 // Remove the non-system users straight away.
4281 removeNonSystemUsers();
4282 } else {
4283 // Switch to the system user first and then remove the other users.
4284 BroadcastReceiver userSwitchedReceiver = new BroadcastReceiver() {
4285 @Override
4286 public void onReceive(Context context, Intent intent) {
4287 int userId =
4288 intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
4289 if (userId != UserHandle.USER_SYSTEM) {
4290 return;
4291 }
4292 mContext.unregisterReceiver(this);
4293 removeNonSystemUsers();
4294 }
4295 };
4296 IntentFilter userSwitchedFilter = new IntentFilter();
4297 userSwitchedFilter.addAction(Intent.ACTION_USER_SWITCHED);
4298 mContext.registerReceiver(
4299 userSwitchedReceiver, userSwitchedFilter, null, mHandler);
4300
4301 // Switch to the system user.
4302 ActivityManager am =
4303 (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
4304 am.switchUser(UserHandle.USER_SYSTEM);
4305 }
4306 }
phweisse9c44062016-02-10 12:57:38 +01004307
4308 @Override
Bookatzf56f2582019-09-04 16:06:41 -07004309 public void onEphemeralUserStop(@UserIdInt int userId) {
Lenka Trochtova1ddda472016-02-12 10:42:12 +01004310 synchronized (mUsersLock) {
4311 UserInfo userInfo = getUserInfoLU(userId);
4312 if (userInfo != null && userInfo.isEphemeral()) {
4313 // Do not allow switching back to the ephemeral user again as the user is going
4314 // to be deleted.
4315 userInfo.flags |= UserInfo.FLAG_DISABLED;
4316 if (userInfo.isGuest()) {
4317 // Indicate that the guest will be deleted after it stops.
4318 userInfo.guestToRemove = true;
4319 }
4320 }
4321 }
4322 }
4323
4324 @Override
Alex Chaub6a9f942017-11-07 11:28:56 +08004325 public UserInfo createUserEvenWhenDisallowed(String name, int flags,
4326 String[] disallowedPackages) {
4327 UserInfo user = createUserInternalUnchecked(name, flags, UserHandle.USER_NULL,
Felipe Lemec1ca4412019-09-11 09:23:26 -07004328 /* preCreated= */ false, disallowedPackages);
phweisse9c44062016-02-10 12:57:38 +01004329 // Keep this in sync with UserManager.createUser
Christine Franks97a54802017-08-09 10:06:43 -07004330 if (user != null && !user.isAdmin() && !user.isDemo()) {
phweisse9c44062016-02-10 12:57:38 +01004331 setUserRestriction(UserManager.DISALLOW_SMS, true, user.id);
4332 setUserRestriction(UserManager.DISALLOW_OUTGOING_CALLS, true, user.id);
4333 }
4334 return user;
4335 }
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07004336
4337 @Override
Bookatzf56f2582019-09-04 16:06:41 -07004338 public boolean removeUserEvenWhenDisallowed(@UserIdInt int userId) {
Nicolas Prevotdf1b87d2016-10-25 13:57:08 +01004339 return removeUserUnchecked(userId);
4340 }
4341
4342 @Override
Bookatzf56f2582019-09-04 16:06:41 -07004343 public boolean isUserRunning(@UserIdInt int userId) {
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00004344 synchronized (mUserStates) {
4345 return mUserStates.get(userId, -1) >= 0;
4346 }
4347 }
4348
4349 @Override
Bookatzf56f2582019-09-04 16:06:41 -07004350 public void setUserState(@UserIdInt int userId, int userState) {
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00004351 synchronized (mUserStates) {
4352 mUserStates.put(userId, userState);
4353 }
4354 }
4355
4356 @Override
Bookatzf56f2582019-09-04 16:06:41 -07004357 public void removeUserState(@UserIdInt int userId) {
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00004358 synchronized (mUserStates) {
4359 mUserStates.delete(userId);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07004360 }
4361 }
4362
4363 @Override
Michael Wachenschwanz3f2b6552017-05-15 13:53:09 -07004364 public int[] getUserIds() {
4365 return UserManagerService.this.getUserIds();
4366 }
4367
4368 @Override
Bookatzf56f2582019-09-04 16:06:41 -07004369 public boolean isUserUnlockingOrUnlocked(@UserIdInt int userId) {
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07004370 int state;
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00004371 synchronized (mUserStates) {
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07004372 state = mUserStates.get(userId, -1);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07004373 }
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07004374 // Special case, in the stopping/shutdown state user key can still be unlocked
4375 if (state == UserState.STATE_STOPPING || state == UserState.STATE_SHUTDOWN) {
4376 return StorageManager.isUserKeyUnlocked(userId);
4377 }
4378 return (state == UserState.STATE_RUNNING_UNLOCKING)
4379 || (state == UserState.STATE_RUNNING_UNLOCKED);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07004380 }
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08004381
4382 @Override
Bookatzf56f2582019-09-04 16:06:41 -07004383 public boolean isUserUnlocked(@UserIdInt int userId) {
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07004384 int state;
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08004385 synchronized (mUserStates) {
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07004386 state = mUserStates.get(userId, -1);
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08004387 }
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07004388 // Special case, in the stopping/shutdown state user key can still be unlocked
4389 if (state == UserState.STATE_STOPPING || state == UserState.STATE_SHUTDOWN) {
4390 return StorageManager.isUserKeyUnlocked(userId);
4391 }
4392 return state == UserState.STATE_RUNNING_UNLOCKED;
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08004393 }
Todd Kennedy0eb97382017-10-03 16:57:22 -07004394
4395 @Override
Bookatzf56f2582019-09-04 16:06:41 -07004396 public boolean isUserInitialized(@UserIdInt int userId) {
Todd Kennedy0eb97382017-10-03 16:57:22 -07004397 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
4398 }
4399
4400 @Override
Bookatzf56f2582019-09-04 16:06:41 -07004401 public boolean exists(@UserIdInt int userId) {
Todd Kennedy0eb97382017-10-03 16:57:22 -07004402 return getUserInfoNoChecks(userId) != null;
4403 }
Sunny Goyal145c8f82018-02-15 14:27:09 -08004404
4405 @Override
4406 public boolean isProfileAccessible(int callingUserId, int targetUserId, String debugMsg,
4407 boolean throwSecurityException) {
4408 if (targetUserId == callingUserId) {
4409 return true;
4410 }
4411 synchronized (mUsersLock) {
4412 UserInfo callingUserInfo = getUserInfoLU(callingUserId);
4413 if (callingUserInfo == null || callingUserInfo.isManagedProfile()) {
4414 if (throwSecurityException) {
4415 throw new SecurityException(
4416 debugMsg + " for another profile "
4417 + targetUserId + " from " + callingUserId);
4418 }
4419 }
4420
4421 UserInfo targetUserInfo = getUserInfoLU(targetUserId);
4422 if (targetUserInfo == null || !targetUserInfo.isEnabled()) {
4423 // Do not throw any exception here as this could happen due to race conditions
4424 // between the system updating its state and the client getting notified.
4425 if (throwSecurityException) {
4426 Slog.w(LOG_TAG, debugMsg + " for disabled profile "
4427 + targetUserId + " from " + callingUserId);
4428 }
4429 return false;
4430 }
4431
4432 if (targetUserInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID ||
4433 targetUserInfo.profileGroupId != callingUserInfo.profileGroupId) {
4434 if (throwSecurityException) {
4435 throw new SecurityException(
4436 debugMsg + " for unrelated profile " + targetUserId);
4437 }
4438 return false;
4439 }
4440 }
4441 return true;
4442 }
4443
4444 @Override
Bookatzf56f2582019-09-04 16:06:41 -07004445 public int getProfileParentId(@UserIdInt int userId) {
Sunny Goyal145c8f82018-02-15 14:27:09 -08004446 synchronized (mUsersLock) {
4447 UserInfo profileParent = getProfileParentLU(userId);
4448 if (profileParent == null) {
4449 return userId;
4450 }
4451 return profileParent.id;
4452 }
4453 }
yuemingw1d13eae2018-01-30 17:27:54 +00004454
4455 @Override
4456 public boolean isSettingRestrictedForUser(String setting, @UserIdInt int userId,
4457 String value, int callingUid) {
Christopher Tate65fb2e42019-10-11 17:00:23 -07004458 return UserManagerService.this.isSettingRestrictedForUser(setting, userId,
yuemingw1d13eae2018-01-30 17:27:54 +00004459 value, callingUid);
4460 }
Patrick Baumann2f2fd712019-07-31 15:18:53 -07004461
4462 @Override
Bookatzf56f2582019-09-04 16:06:41 -07004463 public boolean hasUserRestriction(String restrictionKey, @UserIdInt int userId) {
Patrick Baumann2f2fd712019-07-31 15:18:53 -07004464 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
4465 return false;
4466 }
4467 Bundle restrictions = getEffectiveUserRestrictions(userId);
4468 return restrictions != null && restrictions.getBoolean(restrictionKey);
4469 }
Felipe Lemee5434c32019-08-13 09:28:33 -07004470
Rubin Xu0f1e56d2019-08-23 13:34:25 +01004471 @Override
Felipe Lemee5434c32019-08-13 09:28:33 -07004472 public @Nullable UserInfo getUserInfo(@UserIdInt int userId) {
4473 UserData userData;
4474 synchronized (mUsersLock) {
4475 userData = mUsers.get(userId);
4476 }
4477 return userData == null ? null : userData.info;
4478 }
Felipe Leme987655d2019-08-26 10:45:24 -07004479
4480 public @NonNull UserInfo[] getUserInfos() {
4481 synchronized (mUsersLock) {
4482 int userSize = mUsers.size();
4483 UserInfo[] allInfos = new UserInfo[userSize];
4484 for (int i = 0; i < userSize; i++) {
4485 allInfos[i] = mUsers.valueAt(i).info;
4486 }
4487 return allInfos;
4488 }
4489 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01004490 }
4491
4492 /* Remove all the users except of the system one. */
4493 private void removeNonSystemUsers() {
4494 ArrayList<UserInfo> usersToRemove = new ArrayList<>();
4495 synchronized (mUsersLock) {
4496 final int userSize = mUsers.size();
4497 for (int i = 0; i < userSize; i++) {
4498 UserInfo ui = mUsers.valueAt(i).info;
4499 if (ui.id != UserHandle.USER_SYSTEM) {
4500 usersToRemove.add(ui);
4501 }
4502 }
4503 }
4504 for (UserInfo ui: usersToRemove) {
4505 removeUser(ui.id);
4506 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07004507 }
Todd Kennedy60459ab2015-10-30 11:32:16 -07004508
4509 private class Shell extends ShellCommand {
4510 @Override
4511 public int onCommand(String cmd) {
4512 return onShellCommand(this, cmd);
4513 }
4514
4515 @Override
4516 public void onHelp() {
4517 final PrintWriter pw = getOutPrintWriter();
4518 pw.println("User manager (user) commands:");
4519 pw.println(" help");
4520 pw.println(" Print this help text.");
4521 pw.println("");
Felipe Lemec1ca4412019-09-11 09:23:26 -07004522 pw.println(" list [-v] [-all]");
Todd Kennedy60459ab2015-10-30 11:32:16 -07004523 pw.println(" Prints all users on the system.");
4524 }
4525 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08004526
4527 private static void debug(String message) {
4528 Log.d(LOG_TAG, message +
4529 (DBG_WITH_STACKTRACE ? " called at\n" + Debug.getCallers(10, " ") : ""));
4530 }
Kenny Guy02c89902016-11-15 19:36:38 +00004531
4532 @VisibleForTesting
4533 static int getMaxManagedProfiles() {
4534 // Allow overriding max managed profiles on debuggable builds for testing
4535 // of multiple profiles.
4536 if (!Build.IS_DEBUGGABLE) {
4537 return MAX_MANAGED_PROFILES;
4538 } else {
4539 return SystemProperties.getInt("persist.sys.max_profiles",
4540 MAX_MANAGED_PROFILES);
4541 }
4542 }
4543
Andreas Gampe2e8c7672018-07-20 13:01:08 -07004544 @GuardedBy("mUsersLock")
Kenny Guy02c89902016-11-15 19:36:38 +00004545 @VisibleForTesting
4546 int getFreeProfileBadgeLU(int parentUserId) {
4547 int maxManagedProfiles = getMaxManagedProfiles();
4548 boolean[] usedBadges = new boolean[maxManagedProfiles];
4549 final int userSize = mUsers.size();
4550 for (int i = 0; i < userSize; i++) {
4551 UserInfo ui = mUsers.valueAt(i).info;
4552 // Check which badge indexes are already used by this profile group.
4553 if (ui.isManagedProfile()
4554 && ui.profileGroupId == parentUserId
4555 && !mRemovingUserIds.get(ui.id)
4556 && ui.profileBadge < maxManagedProfiles) {
4557 usedBadges[ui.profileBadge] = true;
4558 }
4559 }
4560 for (int i = 0; i < maxManagedProfiles; i++) {
4561 if (!usedBadges[i]) {
4562 return i;
4563 }
4564 }
4565 return 0;
4566 }
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07004567
4568 /**
4569 * Checks if the given user has a managed profile associated with it.
4570 * @param userId The parent user
4571 * @return
4572 */
Bookatzf56f2582019-09-04 16:06:41 -07004573 boolean hasManagedProfile(@UserIdInt int userId) {
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07004574 synchronized (mUsersLock) {
4575 UserInfo userInfo = getUserInfoLU(userId);
4576 final int userSize = mUsers.size();
4577 for (int i = 0; i < userSize; i++) {
4578 UserInfo profile = mUsers.valueAt(i).info;
4579 if (userId != profile.id && isProfileOf(userInfo, profile)) {
4580 return true;
4581 }
4582 }
4583 return false;
4584 }
4585 }
Tony Makd390ae92017-12-28 13:23:10 +00004586
4587 /**
4588 * Check if the calling package name matches with the calling UID, throw
4589 * {@link SecurityException} if not.
4590 */
4591 private void verifyCallingPackage(String callingPackage, int callingUid) {
4592 int packageUid = mPm.getPackageUid(callingPackage, 0, UserHandle.getUserId(callingUid));
4593 if (packageUid != callingUid) {
4594 throw new SecurityException("Specified package " + callingPackage
4595 + " does not match the calling uid " + callingUid);
4596 }
4597 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07004598}