blob: 9fcce59c10d19d85b2e152b43932472d20c7fb77 [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;
Bookatz029832a2019-10-04 16:50:22 -070023import android.annotation.ColorRes;
24import android.annotation.DrawableRes;
Xiaohui Chen594f2082015-08-18 11:04:20 -070025import android.annotation.NonNull;
Makoto Onuki068c54a2015-10-13 14:34:03 -070026import android.annotation.Nullable;
Bookatz029832a2019-10-04 16:50:22 -070027import android.annotation.StringRes;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -060028import android.annotation.UserIdInt;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070029import android.app.Activity;
Amith Yamasani2a003292012-08-14 18:25:45 -070030import android.app.ActivityManager;
Amith Yamasani515d4062015-09-28 11:30:06 -070031import android.app.ActivityManagerInternal;
Andrew Scull85a63bc2016-10-24 13:47:47 +010032import android.app.ActivityManagerNative;
Todd Kennedy60459ab2015-10-30 11:32:16 -070033import android.app.IActivityManager;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070034import android.app.IStopUserCallback;
Benjamin Franzf02420c2016-04-04 18:52:21 +010035import android.app.KeyguardManager;
Ricky Waib1dd80b2016-06-07 18:00:55 +010036import android.app.PendingIntent;
arangelov9b632d72018-12-07 23:21:22 +000037import android.app.admin.DevicePolicyEventLogger;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070038import android.content.BroadcastReceiver;
Amith Yamasani258848d2012-08-10 17:06:33 -070039import android.content.Context;
40import android.content.Intent;
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +010041import android.content.IntentFilter;
Benjamin Franzf02420c2016-04-04 18:52:21 +010042import android.content.IntentSender;
Amith Yamasani0b285492011-04-14 17:35:23 -070043import android.content.pm.PackageManager;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -080044import android.content.pm.PackageManager.NameNotFoundException;
Tony Make3d1f652017-12-12 11:00:37 +000045import android.content.pm.ShortcutServiceInternal;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070046import android.content.pm.UserInfo;
Felipe Lemec1ca4412019-09-11 09:23:26 -070047import android.content.pm.UserInfo.UserInfoFlag;
Lenka Trochtova02fee152015-12-22 14:26:18 +010048import android.content.res.Resources;
Amith Yamasanie928d7d2012-09-17 21:46:51 -070049import android.graphics.Bitmap;
Amith Yamasani258848d2012-08-10 17:06:33 -070050import android.os.Binder;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -060051import android.os.Build;
Amith Yamasanie4cf7342012-12-17 11:12:09 -080052import android.os.Bundle;
Makoto Onuki1a2cd742015-11-16 13:51:27 -080053import android.os.Debug;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070054import android.os.Environment;
55import android.os.FileUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080056import android.os.Handler;
Svet Ganov9cea80cd2016-02-16 11:47:00 -080057import android.os.IBinder;
Tony Mak64fd8c02017-12-01 19:11:59 +000058import android.os.IProgressListener;
Amith Yamasani258848d2012-08-10 17:06:33 -070059import android.os.IUserManager;
Christopher Tate65fb2e42019-10-11 17:00:23 -070060import android.os.IUserRestrictionsListener;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -080061import android.os.Message;
Adrian Roos1bdff912015-02-17 15:51:35 +010062import android.os.ParcelFileDescriptor;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070063import android.os.Parcelable;
Amith Yamasani12747872015-12-07 14:19:49 -080064import android.os.PersistableBundle;
Amith Yamasani258848d2012-08-10 17:06:33 -070065import android.os.Process;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070066import android.os.RemoteException;
Todd Kennedy60459ab2015-10-30 11:32:16 -070067import android.os.ResultReceiver;
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +010068import android.os.SELinux;
Jason Monk62062992014-05-06 09:55:28 -040069import android.os.ServiceManager;
Dianne Hackborn354736e2016-08-22 17:00:05 -070070import android.os.ShellCallback;
Todd Kennedy60459ab2015-10-30 11:32:16 -070071import android.os.ShellCommand;
Makoto Onuki73dded22017-12-20 13:14:48 +090072import android.os.SystemClock;
Kenny Guy02c89902016-11-15 19:36:38 +000073import android.os.SystemProperties;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070074import android.os.UserHandle;
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070075import android.os.UserManager;
Pavel Grafov6a40f092016-10-25 15:46:51 +010076import android.os.UserManager.EnforcingUser;
Makoto Onuki068c54a2015-10-13 14:34:03 -070077import android.os.UserManagerInternal;
Makoto Onukid45a4a22015-11-02 17:17:38 -080078import android.os.UserManagerInternal.UserRestrictionsListener;
Paul Crowley85e4e812015-05-19 12:42:00 +010079import android.os.storage.StorageManager;
Amith Yamasanid04aaa32016-06-13 12:09:36 -070080import android.security.GateKeeper;
81import android.service.gatekeeper.IGateKeeperService;
arangelov9b632d72018-12-07 23:21:22 +000082import android.stats.devicepolicy.DevicePolicyEnums;
Bookatz029832a2019-10-04 16:50:22 -070083import android.util.ArrayMap;
Bookatz75f0a072019-08-05 14:12:16 -070084import android.util.ArraySet;
Amith Yamasani2a003292012-08-14 18:25:45 -070085import android.util.AtomicFile;
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -070086import android.util.IntArray;
Amith Yamasani655d0e22013-06-12 14:19:10 -070087import android.util.Log;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070088import android.util.Slog;
89import android.util.SparseArray;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080090import android.util.SparseBooleanArray;
Amith Yamasaniea1b9d72016-05-27 15:57:38 +000091import android.util.SparseIntArray;
Amith Yamasani920ace02012-09-20 22:15:37 -070092import android.util.TimeUtils;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070093import android.util.Xml;
94
Makoto Onuki068c54a2015-10-13 14:34:03 -070095import com.android.internal.annotations.GuardedBy;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070096import com.android.internal.annotations.VisibleForTesting;
Jason Monk62062992014-05-06 09:55:28 -040097import com.android.internal.app.IAppOpsService;
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -080098import com.android.internal.logging.MetricsLogger;
Fyodor Kupolova68a2862018-01-30 18:22:00 -080099import com.android.internal.os.BackgroundThread;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -0600100import com.android.internal.util.DumpUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800101import com.android.internal.util.FastXmlSerializer;
Makoto Onuki068c54a2015-10-13 14:34:03 -0700102import com.android.internal.util.Preconditions;
Fyodor Kupolov262f9952015-03-23 18:55:11 -0700103import com.android.internal.util.XmlUtils;
Clara Bayarri10ad84a2015-12-01 17:38:05 +0000104import com.android.internal.widget.LockPatternUtils;
Amith Yamasani515d4062015-09-28 11:30:06 -0700105import com.android.server.LocalServices;
Jeff Sharkey5f3e9342017-03-13 14:53:11 -0600106import com.android.server.LockGuard;
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700107import com.android.server.SystemService;
Amith Yamasaniea1b9d72016-05-27 15:57:38 +0000108import com.android.server.am.UserState;
Suprabh Shuklac5e057c2016-08-08 16:22:44 -0700109import com.android.server.storage.DeviceStorageMonitorInternal;
Felipe Leme3aad1be2019-05-31 11:43:12 -0700110import com.android.server.utils.TimingsTraceAndSlog;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700111import com.android.server.wm.ActivityTaskManagerInternal;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800112
arangelov9b632d72018-12-07 23:21:22 +0000113import libcore.io.IoUtils;
114
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800115import org.xmlpull.v1.XmlPullParser;
116import org.xmlpull.v1.XmlPullParserException;
117import org.xmlpull.v1.XmlSerializer;
118
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700119import java.io.BufferedOutputStream;
120import java.io.File;
Amith Yamasani920ace02012-09-20 22:15:37 -0700121import java.io.FileDescriptor;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700122import java.io.FileInputStream;
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700123import java.io.FileNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700124import java.io.FileOutputStream;
Tony Mak64fd8c02017-12-01 19:11:59 +0000125import java.io.IOException;
Kenny Guy02c89902016-11-15 19:36:38 +0000126import java.io.InputStream;
127import java.io.OutputStream;
Amith Yamasani920ace02012-09-20 22:15:37 -0700128import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100129import java.nio.charset.StandardCharsets;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700130import java.util.ArrayList;
Pavel Grafov6a40f092016-10-25 15:46:51 +0100131import java.util.Collections;
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700132import java.util.LinkedList;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700133import java.util.List;
Narayan Kamath607223f2018-02-19 14:09:02 +0000134import java.util.Objects;
Bookatz75f0a072019-08-05 14:12:16 -0700135import java.util.Set;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700136
Makoto Onuki068c54a2015-10-13 14:34:03 -0700137/**
138 * Service for {@link UserManager}.
139 *
140 * Method naming convention:
Fyodor Kupolov82402752015-10-28 14:54:51 -0700141 * <ul>
Fyodor Kupolovd31cee92017-09-05 16:31:08 -0700142 * <li> Methods suffixed with "LAr" should be called within the {@link #mAppRestrictionsLock} lock.
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800143 * <li> Methods suffixed with "LP" should be called within the {@link #mPackagesLock} lock.
Fyodor Kupolov82402752015-10-28 14:54:51 -0700144 * <li> Methods suffixed with "LR" should be called within the {@link #mRestrictionsLock} lock.
145 * <li> Methods suffixed with "LU" should be called within the {@link #mUsersLock} lock.
146 * </ul>
Makoto Onuki068c54a2015-10-13 14:34:03 -0700147 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700148public class UserManagerService extends IUserManager.Stub {
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700149
Amith Yamasani2a003292012-08-14 18:25:45 -0700150 private static final String LOG_TAG = "UserManagerService";
Makoto Onuki81c61ea2016-01-22 11:22:26 -0800151 static final boolean DBG = false; // DO NOT SUBMIT WITH TRUE
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800152 private static final boolean DBG_WITH_STACKTRACE = false; // DO NOT SUBMIT WITH TRUE
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700153 // Can be used for manual testing of id recycling
154 private static final boolean RELEASE_DELETED_USER_ID = false; // DO NOT SUBMIT WITH TRUE
Amith Yamasani16389312012-10-17 21:20:14 -0700155
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700156 private static final String TAG_NAME = "name";
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800157 private static final String TAG_ACCOUNT = "account";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700158 private static final String ATTR_FLAGS = "flags";
Bookatz029832a2019-10-04 16:50:22 -0700159 private static final String ATTR_TYPE = "type";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700160 private static final String ATTR_ICON_PATH = "icon";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700161 private static final String ATTR_ID = "id";
Amith Yamasani920ace02012-09-20 22:15:37 -0700162 private static final String ATTR_CREATION_TIME = "created";
163 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -0600164 private static final String ATTR_LAST_LOGGED_IN_FINGERPRINT = "lastLoggedInFingerprint";
Amith Yamasani2a003292012-08-14 18:25:45 -0700165 private static final String ATTR_SERIAL_NO = "serialNumber";
166 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700167 private static final String ATTR_PARTIAL = "partial";
Felipe Lemec1ca4412019-09-11 09:23:26 -0700168 private static final String ATTR_PRE_CREATED = "preCreated";
Adam Lesinskieddeb492014-09-08 17:50:03 -0700169 private static final String ATTR_GUEST_TO_REMOVE = "guestToRemove";
Amith Yamasani6f34b412012-10-22 18:19:27 -0700170 private static final String ATTR_USER_VERSION = "version";
Kenny Guy2a764942014-04-02 13:29:20 +0100171 private static final String ATTR_PROFILE_GROUP_ID = "profileGroupId";
Kenny Guy02c89902016-11-15 19:36:38 +0000172 private static final String ATTR_PROFILE_BADGE = "profileBadge";
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700173 private static final String ATTR_RESTRICTED_PROFILE_PARENT_ID = "restrictedProfileParentId";
Amith Yamasani12747872015-12-07 14:19:49 -0800174 private static final String ATTR_SEED_ACCOUNT_NAME = "seedAccountName";
175 private static final String ATTR_SEED_ACCOUNT_TYPE = "seedAccountType";
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530176 private static final String TAG_GUEST_RESTRICTIONS = "guestRestrictions";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700177 private static final String TAG_USERS = "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700178 private static final String TAG_USER = "user";
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800179 private static final String TAG_RESTRICTIONS = "restrictions";
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800180 private static final String TAG_DEVICE_POLICY_RESTRICTIONS = "device_policy_restrictions";
Pavel Grafov6a40f092016-10-25 15:46:51 +0100181 private static final String TAG_DEVICE_POLICY_GLOBAL_RESTRICTIONS =
182 "device_policy_global_restrictions";
183 /** Legacy name for device owner id tag. */
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +0100184 private static final String TAG_GLOBAL_RESTRICTION_OWNER_ID = "globalRestrictionOwnerUserId";
Pavel Grafov6a40f092016-10-25 15:46:51 +0100185 private static final String TAG_DEVICE_OWNER_USER_ID = "deviceOwnerUserId";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800186 private static final String TAG_ENTRY = "entry";
187 private static final String TAG_VALUE = "value";
Amith Yamasani12747872015-12-07 14:19:49 -0800188 private static final String TAG_SEED_ACCOUNT_OPTIONS = "seedAccountOptions";
arangelov9b632d72018-12-07 23:21:22 +0000189 private static final String TAG_LAST_REQUEST_QUIET_MODE_ENABLED_CALL =
190 "lastRequestQuietModeEnabledCall";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800191 private static final String ATTR_KEY = "key";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700192 private static final String ATTR_VALUE_TYPE = "type";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800193 private static final String ATTR_MULTIPLE = "m";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700194
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700195 private static final String ATTR_TYPE_STRING_ARRAY = "sa";
196 private static final String ATTR_TYPE_STRING = "s";
197 private static final String ATTR_TYPE_BOOLEAN = "b";
Amith Yamasani5b5aa402014-06-01 20:10:14 -0700198 private static final String ATTR_TYPE_INTEGER = "i";
Fyodor Kupolov262f9952015-03-23 18:55:11 -0700199 private static final String ATTR_TYPE_BUNDLE = "B";
200 private static final String ATTR_TYPE_BUNDLE_ARRAY = "BA";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700201
Amith Yamasani0b285492011-04-14 17:35:23 -0700202 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700203 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700204 private static final String USER_PHOTO_FILENAME = "photo.png";
Adrian Roos1bdff912015-02-17 15:51:35 +0100205 private static final String USER_PHOTO_FILENAME_TMP = USER_PHOTO_FILENAME + ".tmp";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700206
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800207 private static final String RESTRICTIONS_FILE_PREFIX = "res_";
Amith Yamasanifc95e702013-09-26 13:20:17 -0700208 private static final String XML_SUFFIX = ".xml";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800209
Sudheer Shankaf5cea032016-06-08 17:13:24 -0700210 private static final int ALLOWED_FLAGS_FOR_CREATE_USERS_PERMISSION =
211 UserInfo.FLAG_MANAGED_PROFILE
212 | UserInfo.FLAG_EPHEMERAL
213 | UserInfo.FLAG_RESTRICTED
Sudheer Shanka234d1af2016-08-26 15:42:53 -0700214 | UserInfo.FLAG_GUEST
215 | UserInfo.FLAG_DEMO;
Sudheer Shankaf5cea032016-06-08 17:13:24 -0700216
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700217 @VisibleForTesting
Makoto Onukiacf38582019-10-04 11:53:42 -0700218 static final int MIN_USER_ID = UserHandle.MIN_SECONDARY_USER_ID;
219
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700220 // We need to keep process uid within Integer.MAX_VALUE.
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700221 @VisibleForTesting
222 static final int MAX_USER_ID = Integer.MAX_VALUE / UserHandle.PER_USER_RANGE;
223
224 // Max size of the queue of recently removed users
225 @VisibleForTesting
226 static final int MAX_RECENTLY_REMOVED_IDS_SIZE = 100;
Amith Yamasani634cf312012-10-04 17:34:21 -0700227
Bookatz029832a2019-10-04 16:50:22 -0700228 private static final int USER_VERSION = 9;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700229
Amith Yamasani920ace02012-09-20 22:15:37 -0700230 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
231
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 /**
Bookatz029832a2019-10-04 16:50:22 -0700307 * Map of user type names to their corresponding {@link UserTypeDetails}.
308 * Should not be modified after UserManagerService constructor finishes.
309 */
310 private final ArrayMap<String, UserTypeDetails> mUserTypes;
311
312 /**
Makoto Onuki068c54a2015-10-13 14:34:03 -0700313 * User restrictions set via UserManager. This doesn't include restrictions set by
Pavel Grafov6a40f092016-10-25 15:46:51 +0100314 * device owner / profile owners. Only non-empty restriction bundles are stored.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700315 *
316 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
317 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
318 * maybe shared between {@link #mBaseUserRestrictions} and
319 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
320 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700321 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700322 */
323 @GuardedBy("mRestrictionsLock")
324 private final SparseArray<Bundle> mBaseUserRestrictions = new SparseArray<>();
325
326 /**
327 * Cached user restrictions that are in effect -- i.e. {@link #mBaseUserRestrictions} combined
328 * with device / profile owner restrictions. We'll initialize it lazily; use
329 * {@link #getEffectiveUserRestrictions} to access it.
330 *
331 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
332 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
333 * maybe shared between {@link #mBaseUserRestrictions} and
334 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
335 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700336 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700337 */
338 @GuardedBy("mRestrictionsLock")
339 private final SparseArray<Bundle> mCachedEffectiveUserRestrictions = new SparseArray<>();
340
Makoto Onuki4f160732015-10-27 17:15:38 -0700341 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800342 * User restrictions that have already been applied in
343 * {@link #updateUserRestrictionsInternalLR(Bundle, int)}. We use it to detect restrictions
344 * that have changed since the last
345 * {@link #updateUserRestrictionsInternalLR(Bundle, int)} call.
Makoto Onuki4f160732015-10-27 17:15:38 -0700346 */
347 @GuardedBy("mRestrictionsLock")
348 private final SparseArray<Bundle> mAppliedUserRestrictions = new SparseArray<>();
349
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800350 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800351 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
Pavel Grafov6a40f092016-10-25 15:46:51 +0100352 * that should be applied to all users, including guests. Only non-empty restriction bundles are
353 * stored.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800354 */
355 @GuardedBy("mRestrictionsLock")
Pavel Grafov6a40f092016-10-25 15:46:51 +0100356 private final SparseArray<Bundle> mDevicePolicyGlobalUserRestrictions = new SparseArray<>();
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800357
358 /**
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +0100359 * Id of the user that set global restrictions.
360 */
361 @GuardedBy("mRestrictionsLock")
Pavel Grafov6a40f092016-10-25 15:46:51 +0100362 private int mDeviceOwnerUserId = UserHandle.USER_NULL;
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +0100363
364 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800365 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
Pavel Grafov6a40f092016-10-25 15:46:51 +0100366 * for each user. Only non-empty restriction bundles are stored.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800367 */
368 @GuardedBy("mRestrictionsLock")
369 private final SparseArray<Bundle> mDevicePolicyLocalUserRestrictions = new SparseArray<>();
370
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800371 @GuardedBy("mGuestRestrictions")
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530372 private final Bundle mGuestRestrictions = new Bundle();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800373
374 /**
375 * Set of user IDs being actively removed. Removed IDs linger in this set
376 * for several seconds to work around a VFS caching issue.
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700377 * Use {@link #addRemovingUserIdLocked(int)} to add elements to this array
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800378 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700379 @GuardedBy("mUsersLock")
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800380 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700381
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700382 /**
383 * Queue of recently removed userIds. Used for recycling of userIds
384 */
385 @GuardedBy("mUsersLock")
386 private final LinkedList<Integer> mRecentlyRemovedIds = new LinkedList<>();
387
Fyodor Kupolov82402752015-10-28 14:54:51 -0700388 @GuardedBy("mUsersLock")
Amith Yamasani0b285492011-04-14 17:35:23 -0700389 private int[] mUserIds;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800390 @GuardedBy("mPackagesLock")
Amith Yamasani2a003292012-08-14 18:25:45 -0700391 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700392 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700393
Jason Monk62062992014-05-06 09:55:28 -0400394 private IAppOpsService mAppOpsService;
395
Makoto Onuki068c54a2015-10-13 14:34:03 -0700396 private final LocalService mLocalService;
397
Makoto Onukie7927da2015-11-25 10:05:17 -0800398 @GuardedBy("mUsersLock")
399 private boolean mIsDeviceManaged;
400
401 @GuardedBy("mUsersLock")
402 private final SparseBooleanArray mIsUserManaged = new SparseBooleanArray();
403
Makoto Onukid45a4a22015-11-02 17:17:38 -0800404 @GuardedBy("mUserRestrictionsListeners")
405 private final ArrayList<UserRestrictionsListener> mUserRestrictionsListeners =
406 new ArrayList<>();
407
Clara Bayarria1771112015-12-18 16:29:18 +0000408 private final LockPatternUtils mLockPatternUtils;
409
Ricky Waib1dd80b2016-06-07 18:00:55 +0100410 private final String ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK =
411 "com.android.server.pm.DISABLE_QUIET_MODE_AFTER_UNLOCK";
412
413 private final BroadcastReceiver mDisableQuietModeCallback = new BroadcastReceiver() {
414 @Override
415 public void onReceive(Context context, Intent intent) {
Tony Mak64fd8c02017-12-01 19:11:59 +0000416 if (!ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK.equals(intent.getAction())) {
417 return;
Ricky Waib1dd80b2016-06-07 18:00:55 +0100418 }
Tony Mak64fd8c02017-12-01 19:11:59 +0000419 final IntentSender target = intent.getParcelableExtra(Intent.EXTRA_INTENT);
Bookatzf56f2582019-09-04 16:06:41 -0700420 final int userId = intent.getIntExtra(Intent.EXTRA_USER_ID, UserHandle.USER_NULL);
Fyodor Kupolova68a2862018-01-30 18:22:00 -0800421 // Call setQuietModeEnabled on bg thread to avoid ANR
arangelov9b632d72018-12-07 23:21:22 +0000422 BackgroundThread.getHandler().post(() ->
Bookatzf56f2582019-09-04 16:06:41 -0700423 setQuietModeEnabled(userId, false, target, /* callingPackage */ null));
Ricky Waib1dd80b2016-06-07 18:00:55 +0100424 }
425 };
426
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +0100427 /**
Tony Mak64fd8c02017-12-01 19:11:59 +0000428 * Start an {@link IntentSender} when user is unlocked after disabling quiet mode.
429 *
Tony Makbece85d2018-01-12 12:10:17 +0000430 * @see {@link #requestQuietModeEnabled(String, boolean, int, IntentSender)}
Tony Mak64fd8c02017-12-01 19:11:59 +0000431 */
432 private class DisableQuietModeUserUnlockedCallback extends IProgressListener.Stub {
433 private final IntentSender mTarget;
434
435 public DisableQuietModeUserUnlockedCallback(IntentSender target) {
436 Preconditions.checkNotNull(target);
437 mTarget = target;
438 }
439
440 @Override
441 public void onStarted(int id, Bundle extras) {}
442
443 @Override
444 public void onProgress(int id, int progress, Bundle extras) {}
445
446 @Override
447 public void onFinished(int id, Bundle extras) {
448 try {
449 mContext.startIntentSender(mTarget, null, 0, 0, 0);
450 } catch (IntentSender.SendIntentException e) {
451 Slog.e(LOG_TAG, "Failed to start the target in the callback", e);
452 }
453 }
454 }
455
456 /**
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +0100457 * Whether all users should be created ephemeral.
458 */
459 @GuardedBy("mUsersLock")
460 private boolean mForceEphemeralUsers;
461
Amith Yamasaniea1b9d72016-05-27 15:57:38 +0000462 @GuardedBy("mUserStates")
463 private final SparseIntArray mUserStates = new SparseIntArray();
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -0700464
Amith Yamasani258848d2012-08-10 17:06:33 -0700465 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700466
Dianne Hackborn4428e172012-08-24 17:43:05 -0700467 public static UserManagerService getInstance() {
468 synchronized (UserManagerService.class) {
469 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700470 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700471 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700472
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700473 public static class LifeCycle extends SystemService {
474
475 private UserManagerService mUms;
476
477 /**
478 * @param context
479 */
480 public LifeCycle(Context context) {
481 super(context);
482 }
483
484 @Override
485 public void onStart() {
486 mUms = UserManagerService.getInstance();
487 publishBinderService(Context.USER_SERVICE, mUms);
488 }
489
490 @Override
491 public void onBootPhase(int phase) {
492 if (phase == SystemService.PHASE_ACTIVITY_MANAGER_READY) {
493 mUms.cleanupPartialUsers();
494 }
495 }
Makoto Onuki73dded22017-12-20 13:14:48 +0900496
497 @Override
Bookatzf56f2582019-09-04 16:06:41 -0700498 public void onStartUser(@UserIdInt int userId) {
Makoto Onuki73dded22017-12-20 13:14:48 +0900499 synchronized (mUms.mUsersLock) {
Bookatzf56f2582019-09-04 16:06:41 -0700500 final UserData user = mUms.getUserDataLU(userId);
Makoto Onuki73dded22017-12-20 13:14:48 +0900501 if (user != null) {
502 user.startRealtime = SystemClock.elapsedRealtime();
503 }
504 }
505 }
506
507 @Override
Bookatzf56f2582019-09-04 16:06:41 -0700508 public void onUnlockUser(@UserIdInt int userId) {
Makoto Onuki73dded22017-12-20 13:14:48 +0900509 synchronized (mUms.mUsersLock) {
Bookatzf56f2582019-09-04 16:06:41 -0700510 final UserData user = mUms.getUserDataLU(userId);
Makoto Onuki73dded22017-12-20 13:14:48 +0900511 if (user != null) {
512 user.unlockRealtime = SystemClock.elapsedRealtime();
513 }
514 }
515 }
516
517 @Override
Bookatzf56f2582019-09-04 16:06:41 -0700518 public void onStopUser(@UserIdInt int userId) {
Makoto Onuki73dded22017-12-20 13:14:48 +0900519 synchronized (mUms.mUsersLock) {
Bookatzf56f2582019-09-04 16:06:41 -0700520 final UserData user = mUms.getUserDataLU(userId);
Makoto Onuki73dded22017-12-20 13:14:48 +0900521 if (user != null) {
522 user.startRealtime = 0;
523 user.unlockRealtime = 0;
524 }
525 }
526 }
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700527 }
528
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700529 // TODO b/28848102 Add support for test dependencies injection
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800530 @VisibleForTesting
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700531 UserManagerService(Context context) {
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800532 this(context, null, null, new Object(), context.getCacheDir());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700533 }
534
Dianne Hackborn4428e172012-08-24 17:43:05 -0700535 /**
536 * Called by package manager to create the service. This is closely
537 * associated with the package manager, and the given lock is the
538 * package manager's own lock.
539 */
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800540 UserManagerService(Context context, PackageManagerService pm, UserDataPreparer userDataPreparer,
541 Object packagesLock) {
542 this(context, pm, userDataPreparer, packagesLock, Environment.getDataDirectory());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700543 }
544
Dianne Hackborn4428e172012-08-24 17:43:05 -0700545 private UserManagerService(Context context, PackageManagerService pm,
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800546 UserDataPreparer userDataPreparer, Object packagesLock, File dataDir) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700547 mContext = context;
548 mPm = pm;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700549 mPackagesLock = packagesLock;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800550 mHandler = new MainHandler();
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800551 mUserDataPreparer = userDataPreparer;
Bookatz029832a2019-10-04 16:50:22 -0700552 mUserTypes = UserTypeFactory.getUserTypes();
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800553 synchronized (mPackagesLock) {
554 mUsersDir = new File(dataDir, USER_INFO_DIR);
555 mUsersDir.mkdirs();
556 // Make zeroth user directory, for services to migrate their files to that location
557 File userZeroDir = new File(mUsersDir, String.valueOf(UserHandle.USER_SYSTEM));
558 userZeroDir.mkdirs();
559 FileUtils.setPermissions(mUsersDir.toString(),
560 FileUtils.S_IRWXU | FileUtils.S_IRWXG | FileUtils.S_IROTH | FileUtils.S_IXOTH,
561 -1, -1);
562 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
563 initDefaultGuestRestrictions();
564 readUserListLP();
565 sInstance = this;
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700566 }
Bookatza8c2d2a2019-11-13 10:10:18 -0800567 mSystemPackageInstaller = new UserSystemPackageInstaller(this, mUserTypes);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700568 mLocalService = new LocalService();
569 LocalServices.addService(UserManagerInternal.class, mLocalService);
Clara Bayarria1771112015-12-18 16:29:18 +0000570 mLockPatternUtils = new LockPatternUtils(mContext);
Amith Yamasaniea1b9d72016-05-27 15:57:38 +0000571 mUserStates.put(UserHandle.USER_SYSTEM, UserState.STATE_BOOTING);
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700572 }
573
574 void systemReady() {
Jason Monk62062992014-05-06 09:55:28 -0400575 mAppOpsService = IAppOpsService.Stub.asInterface(
576 ServiceManager.getService(Context.APP_OPS_SERVICE));
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800577
578 synchronized (mRestrictionsLock) {
579 applyUserRestrictionsLR(UserHandle.USER_SYSTEM);
Jason Monk62062992014-05-06 09:55:28 -0400580 }
Samuel Tand9453b82016-03-14 15:57:02 -0700581
582 UserInfo currentGuestUser = findCurrentGuestUser();
583 if (currentGuestUser != null && !hasUserRestriction(
584 UserManager.DISALLOW_CONFIG_WIFI, currentGuestUser.id)) {
585 // If a guest user currently exists, apply the DISALLOW_CONFIG_WIFI option
586 // to it, in case this guest was created in a previous version where this
587 // user restriction was not a default guest restriction.
588 setUserRestriction(UserManager.DISALLOW_CONFIG_WIFI, true, currentGuestUser.id);
589 }
Amith Yamasanieb437d42016-04-29 09:31:25 -0700590
Ricky Waib1dd80b2016-06-07 18:00:55 +0100591 mContext.registerReceiver(mDisableQuietModeCallback,
592 new IntentFilter(ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK),
593 null, mHandler);
Amith Yamasani258848d2012-08-10 17:06:33 -0700594 }
595
Patrick Baumann6ae7afc2019-07-30 13:11:28 -0700596 /**
597 * This method retrieves the {@link UserManagerInternal} only for the purpose of
598 * PackageManagerService construction.
599 */
600 UserManagerInternal getInternalForInjectorOnly() {
601 return mLocalService;
602 }
603
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700604 void cleanupPartialUsers() {
605 // Prune out any partially created, partially removed and ephemeral users.
606 ArrayList<UserInfo> partials = new ArrayList<>();
607 synchronized (mUsersLock) {
608 final int userSize = mUsers.size();
609 for (int i = 0; i < userSize; i++) {
610 UserInfo ui = mUsers.valueAt(i).info;
Felipe Lemec1ca4412019-09-11 09:23:26 -0700611 if ((ui.partial || ui.guestToRemove || (ui.isEphemeral() && !ui.preCreated))
612 && i != 0) {
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700613 partials.add(ui);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700614 addRemovingUserIdLocked(ui.id);
Amith Yamasaniae261892016-06-27 10:40:09 -0700615 ui.partial = true;
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700616 }
617 }
618 }
619 final int partialsSize = partials.size();
620 for (int i = 0; i < partialsSize; i++) {
621 UserInfo ui = partials.get(i);
622 Slog.w(LOG_TAG, "Removing partially created user " + ui.id
623 + " (name=" + ui.name + ")");
624 removeUserState(ui.id);
625 }
626 }
627
Amith Yamasani258848d2012-08-10 17:06:33 -0700628 @Override
Bookatzf56f2582019-09-04 16:06:41 -0700629 public String getUserAccount(@UserIdInt int userId) {
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800630 checkManageUserAndAcrossUsersFullPermission("get user account");
631 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800632 return mUsers.get(userId).account;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800633 }
634 }
635
636 @Override
Bookatzf56f2582019-09-04 16:06:41 -0700637 public void setUserAccount(@UserIdInt int userId, String accountName) {
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800638 checkManageUserAndAcrossUsersFullPermission("set user account");
Amith Yamasani12747872015-12-07 14:19:49 -0800639 UserData userToUpdate = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800640 synchronized (mPackagesLock) {
641 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800642 final UserData userData = mUsers.get(userId);
643 if (userData == null) {
644 Slog.e(LOG_TAG, "User not found for setting user account: u" + userId);
645 return;
646 }
647 String currentAccount = userData.account;
Narayan Kamath607223f2018-02-19 14:09:02 +0000648 if (!Objects.equals(currentAccount, accountName)) {
Amith Yamasani12747872015-12-07 14:19:49 -0800649 userData.account = accountName;
650 userToUpdate = userData;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800651 }
652 }
653
654 if (userToUpdate != null) {
655 writeUserLP(userToUpdate);
656 }
657 }
658 }
659
660 @Override
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700661 public UserInfo getPrimaryUser() {
662 checkManageUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700663 synchronized (mUsersLock) {
Amith Yamasani515d4062015-09-28 11:30:06 -0700664 final int userSize = mUsers.size();
665 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800666 UserInfo ui = mUsers.valueAt(i).info;
Xiaohui Chend3e9e182015-11-18 13:37:32 -0800667 if (ui.isPrimary() && !mRemovingUserIds.get(ui.id)) {
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700668 return ui;
669 }
670 }
671 }
672 return null;
673 }
674
Xiaohui Chen594f2082015-08-18 11:04:20 -0700675 public @NonNull List<UserInfo> getUsers(boolean excludeDying) {
Felipe Lemec1ca4412019-09-11 09:23:26 -0700676 return getUsers(/*excludePartial= */ true, excludeDying, /* excludePreCreated= */ true);
677 }
678
Felipe Leme09a7f2d2019-10-02 16:27:46 -0700679 @Override
680 public @NonNull List<UserInfo> getUsers(boolean excludePartial, boolean excludeDying,
Felipe Lemec1ca4412019-09-11 09:23:26 -0700681 boolean excludePreCreated) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -0700682 checkManageOrCreateUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700683 synchronized (mUsersLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700684 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasani515d4062015-09-28 11:30:06 -0700685 final int userSize = mUsers.size();
686 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800687 UserInfo ui = mUsers.valueAt(i).info;
Felipe Lemec1ca4412019-09-11 09:23:26 -0700688 if ((excludePartial && ui.partial)
689 || (excludeDying && mRemovingUserIds.get(ui.id))
690 || (excludePreCreated && ui.preCreated)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700691 continue;
692 }
Felipe Lemec1ca4412019-09-11 09:23:26 -0700693 users.add(userWithName(ui));
Amith Yamasani13593602012-03-22 16:16:17 -0700694 }
695 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700696 }
Amith Yamasani13593602012-03-22 16:16:17 -0700697 }
698
Amith Yamasani258848d2012-08-10 17:06:33 -0700699 @Override
Bookatzf56f2582019-09-04 16:06:41 -0700700 public List<UserInfo> getProfiles(@UserIdInt int userId, boolean enabledOnly) {
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700701 boolean returnFullInfo = true;
Amith Yamasani4f582632014-02-19 14:31:52 -0800702 if (userId != UserHandle.getCallingUserId()) {
Sudheer Shanka74680912016-07-29 11:03:37 -0700703 checkManageOrCreateUsersPermission("getting profiles related to user " + userId);
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700704 } else {
705 returnFullInfo = hasManageUsersPermission();
Amith Yamasani4f582632014-02-19 14:31:52 -0800706 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700707 final long ident = Binder.clearCallingIdentity();
708 try {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700709 synchronized (mUsersLock) {
Bookatz029832a2019-10-04 16:50:22 -0700710 return getProfilesLU(userId, /* userType */ null, enabledOnly, returnFullInfo);
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100711 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700712 } finally {
713 Binder.restoreCallingIdentity(ident);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000714 }
715 }
716
Bookatz029832a2019-10-04 16:50:22 -0700717 // TODO(b/142482943): Will probably need a getProfiles(userType). But permissions may vary.
718
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700719 @Override
Bookatzf56f2582019-09-04 16:06:41 -0700720 public int[] getProfileIds(@UserIdInt int userId, boolean enabledOnly) {
Bookatz029832a2019-10-04 16:50:22 -0700721 return getProfileIds(userId, null, enabledOnly);
722 }
723
724 // TODO(b/142482943): Probably @Override and make this accessible in UserManager.
725 /**
726 * Returns all the users of type userType that are in the same profile group as userId
727 * (including userId itself, if it is of the appropriate user type).
728 *
729 * <p>If userType is non-{@code null}, only returns users that are of type userType.
730 * If enabledOnly, only returns users that are not {@link UserInfo#FLAG_DISABLED}.
731 */
732 public int[] getProfileIds(@UserIdInt int userId, @Nullable String userType,
733 boolean enabledOnly) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700734 if (userId != UserHandle.getCallingUserId()) {
bohu12d23a12016-09-26 16:20:07 -0700735 checkManageOrCreateUsersPermission("getting profiles related to user " + userId);
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700736 }
737 final long ident = Binder.clearCallingIdentity();
738 try {
739 synchronized (mUsersLock) {
Bookatz029832a2019-10-04 16:50:22 -0700740 return getProfileIdsLU(userId, userType, enabledOnly).toArray();
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700741 }
742 } finally {
743 Binder.restoreCallingIdentity(ident);
744 }
745 }
746
Amith Yamasanibe465322014-04-24 13:45:17 -0700747 /** Assume permissions already checked and caller's identity cleared */
Andreas Gampe2e8c7672018-07-20 13:01:08 -0700748 @GuardedBy("mUsersLock")
Bookatz029832a2019-10-04 16:50:22 -0700749 private List<UserInfo> getProfilesLU(@UserIdInt int userId, @Nullable String userType,
750 boolean enabledOnly, boolean fullInfo) {
751 IntArray profileIds = getProfileIdsLU(userId, userType, enabledOnly);
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700752 ArrayList<UserInfo> users = new ArrayList<>(profileIds.size());
753 for (int i = 0; i < profileIds.size(); i++) {
754 int profileId = profileIds.get(i);
755 UserInfo userInfo = mUsers.get(profileId).info;
756 // If full info is not required - clear PII data to prevent 3P apps from reading it
757 if (!fullInfo) {
758 userInfo = new UserInfo(userInfo);
759 userInfo.name = null;
760 userInfo.iconPath = null;
761 } else {
762 userInfo = userWithName(userInfo);
763 }
764 users.add(userInfo);
765 }
766 return users;
767 }
768
769 /**
770 * Assume permissions already checked and caller's identity cleared
Bookatz029832a2019-10-04 16:50:22 -0700771 * <p>If userType is {@code null}, returns all profiles for user; else, only returns
772 * profiles of that type.
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700773 */
Andreas Gampe2e8c7672018-07-20 13:01:08 -0700774 @GuardedBy("mUsersLock")
Bookatz029832a2019-10-04 16:50:22 -0700775 private IntArray getProfileIdsLU(@UserIdInt int userId, @Nullable String userType,
776 boolean enabledOnly) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700777 UserInfo user = getUserInfoLU(userId);
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700778 IntArray result = new IntArray(mUsers.size());
Amith Yamasanidda003f2014-08-28 18:06:51 -0700779 if (user == null) {
780 // Probably a dying user
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700781 return result;
Amith Yamasanidda003f2014-08-28 18:06:51 -0700782 }
Amith Yamasani515d4062015-09-28 11:30:06 -0700783 final int userSize = mUsers.size();
784 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800785 UserInfo profile = mUsers.valueAt(i).info;
Amith Yamasanibe465322014-04-24 13:45:17 -0700786 if (!isProfileOf(user, profile)) {
787 continue;
788 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100789 if (enabledOnly && !profile.isEnabled()) {
790 continue;
Amith Yamasanibe465322014-04-24 13:45:17 -0700791 }
Amith Yamasani70fcf0c2014-07-11 08:40:19 -0700792 if (mRemovingUserIds.get(profile.id)) {
793 continue;
794 }
Tony Mak80189cd2016-04-05 17:21:42 +0100795 if (profile.partial) {
796 continue;
797 }
Bookatz029832a2019-10-04 16:50:22 -0700798 if (userType != null && !userType.equals(profile.userType)) {
799 continue;
800 }
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700801 result.add(profile.id);
Amith Yamasanibe465322014-04-24 13:45:17 -0700802 }
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700803 return result;
Amith Yamasanibe465322014-04-24 13:45:17 -0700804 }
805
Jessica Hummelbe81c802014-04-22 15:49:22 +0100806 @Override
Bookatzf56f2582019-09-04 16:06:41 -0700807 public int getCredentialOwnerProfile(@UserIdInt int userId) {
Andres Moralesc5548c02015-08-05 10:23:12 -0700808 checkManageUsersPermission("get the credential owner");
Bookatzf56f2582019-09-04 16:06:41 -0700809 if (!mLockPatternUtils.isSeparateProfileChallengeEnabled(userId)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700810 synchronized (mUsersLock) {
Bookatzf56f2582019-09-04 16:06:41 -0700811 UserInfo profileParent = getProfileParentLU(userId);
Andres Moralesc5548c02015-08-05 10:23:12 -0700812 if (profileParent != null) {
813 return profileParent.id;
814 }
815 }
816 }
817
Bookatzf56f2582019-09-04 16:06:41 -0700818 return userId;
Andres Moralesc5548c02015-08-05 10:23:12 -0700819 }
820
821 @Override
Bookatzf56f2582019-09-04 16:06:41 -0700822 public boolean isSameProfileGroup(@UserIdInt int userId, int otherUserId) {
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700823 if (userId == otherUserId) return true;
824 checkManageUsersPermission("check if in the same profile group");
Fyodor Kupolov0fb772e2016-10-13 16:27:34 -0700825 return isSameProfileGroupNoChecks(userId, otherUserId);
826 }
827
Bookatzf56f2582019-09-04 16:06:41 -0700828 private boolean isSameProfileGroupNoChecks(@UserIdInt int userId, int otherUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700829 synchronized (mUsersLock) {
830 UserInfo userInfo = getUserInfoLU(userId);
831 if (userInfo == null || userInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
832 return false;
833 }
834 UserInfo otherUserInfo = getUserInfoLU(otherUserId);
835 if (otherUserInfo == null
836 || otherUserInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
837 return false;
838 }
839 return userInfo.profileGroupId == otherUserInfo.profileGroupId;
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700840 }
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700841 }
842
843 @Override
Bookatzf56f2582019-09-04 16:06:41 -0700844 public UserInfo getProfileParent(@UserIdInt int userId) {
Jessica Hummelbe81c802014-04-22 15:49:22 +0100845 checkManageUsersPermission("get the profile parent");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700846 synchronized (mUsersLock) {
Bookatzf56f2582019-09-04 16:06:41 -0700847 return getProfileParentLU(userId);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700848 }
849 }
850
Jakub Pawlowski0f1f5b72017-11-15 14:50:43 -0800851 @Override
Bookatzf56f2582019-09-04 16:06:41 -0700852 public int getProfileParentId(@UserIdInt int userId) {
Jakub Pawlowski0f1f5b72017-11-15 14:50:43 -0800853 checkManageUsersPermission("get the profile parent");
Bookatzf56f2582019-09-04 16:06:41 -0700854 return mLocalService.getProfileParentId(userId);
Jakub Pawlowski0f1f5b72017-11-15 14:50:43 -0800855 }
856
Andreas Gampe2e8c7672018-07-20 13:01:08 -0700857 @GuardedBy("mUsersLock")
Bookatzf56f2582019-09-04 16:06:41 -0700858 private UserInfo getProfileParentLU(@UserIdInt int userId) {
859 UserInfo profile = getUserInfoLU(userId);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700860 if (profile == null) {
861 return null;
862 }
863 int parentUserId = profile.profileGroupId;
Bookatzf56f2582019-09-04 16:06:41 -0700864 if (parentUserId == userId || parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700865 return null;
866 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700867 return getUserInfoLU(parentUserId);
Jessica Hummelbe81c802014-04-22 15:49:22 +0100868 }
869 }
870
Fyodor Kupolov82402752015-10-28 14:54:51 -0700871 private static boolean isProfileOf(UserInfo user, UserInfo profile) {
Kenny Guy2a764942014-04-02 13:29:20 +0100872 return user.id == profile.id ||
873 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
874 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000875 }
876
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000877 private void broadcastProfileAvailabilityChanges(UserHandle profileHandle,
Rubin Xuf13c9802016-01-21 18:06:00 +0000878 UserHandle parentHandle, boolean inQuietMode) {
Rubin Xue95057a2016-04-01 16:49:25 +0100879 Intent intent = new Intent();
880 if (inQuietMode) {
881 intent.setAction(Intent.ACTION_MANAGED_PROFILE_UNAVAILABLE);
882 } else {
883 intent.setAction(Intent.ACTION_MANAGED_PROFILE_AVAILABLE);
884 }
Rubin Xuf13c9802016-01-21 18:06:00 +0000885 intent.putExtra(Intent.EXTRA_QUIET_MODE, inQuietMode);
886 intent.putExtra(Intent.EXTRA_USER, profileHandle);
887 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileHandle.getIdentifier());
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000888 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Rubin Xuf13c9802016-01-21 18:06:00 +0000889 mContext.sendBroadcastAsUser(intent, parentHandle);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000890 }
891
892 @Override
Tony Makbece85d2018-01-12 12:10:17 +0000893 public boolean requestQuietModeEnabled(@NonNull String callingPackage, boolean enableQuietMode,
Bookatzf56f2582019-09-04 16:06:41 -0700894 @UserIdInt int userId, @Nullable IntentSender target) {
Tony Make3d1f652017-12-12 11:00:37 +0000895 Preconditions.checkNotNull(callingPackage);
896
Tony Makb7e6fd42017-12-05 19:40:28 +0000897 if (enableQuietMode && target != null) {
898 throw new IllegalArgumentException(
899 "target should only be specified when we are disabling quiet mode.");
900 }
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000901
Bookatz3cb67df2019-10-16 17:20:06 -0400902 ensureCanModifyQuietMode(callingPackage, Binder.getCallingUid(), userId, target != null);
Tony Makb7e6fd42017-12-05 19:40:28 +0000903 final long identity = Binder.clearCallingIdentity();
904 try {
arangelov9b632d72018-12-07 23:21:22 +0000905 boolean result = false;
Tony Makb7e6fd42017-12-05 19:40:28 +0000906 if (enableQuietMode) {
arangelov9b632d72018-12-07 23:21:22 +0000907 setQuietModeEnabled(
Bookatzf56f2582019-09-04 16:06:41 -0700908 userId, true /* enableQuietMode */, target, callingPackage);
arangelov9b632d72018-12-07 23:21:22 +0000909 result = true;
Tony Makb7e6fd42017-12-05 19:40:28 +0000910 } else {
911 boolean needToShowConfirmCredential =
Bookatzf56f2582019-09-04 16:06:41 -0700912 mLockPatternUtils.isSecure(userId)
913 && !StorageManager.isUserKeyUnlocked(userId);
Tony Makb7e6fd42017-12-05 19:40:28 +0000914 if (needToShowConfirmCredential) {
Bookatzf56f2582019-09-04 16:06:41 -0700915 showConfirmCredentialToDisableQuietMode(userId, target);
Tony Makb7e6fd42017-12-05 19:40:28 +0000916 } else {
arangelov9b632d72018-12-07 23:21:22 +0000917 setQuietModeEnabled(
Bookatzf56f2582019-09-04 16:06:41 -0700918 userId, false /* enableQuietMode */, target, callingPackage);
arangelov9b632d72018-12-07 23:21:22 +0000919 result = true;
Tony Makb7e6fd42017-12-05 19:40:28 +0000920 }
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000921 }
arangelov9b632d72018-12-07 23:21:22 +0000922 return result;
Tony Makb7e6fd42017-12-05 19:40:28 +0000923 } finally {
924 Binder.restoreCallingIdentity(identity);
925 }
926 }
927
Tony Make3d1f652017-12-12 11:00:37 +0000928 /**
Tony Makd390ae92017-12-28 13:23:10 +0000929 * The caller can modify quiet mode if it meets one of these conditions:
Tony Make3d1f652017-12-12 11:00:37 +0000930 * <ul>
931 * <li>Has system UID or root UID</li>
932 * <li>Has {@link Manifest.permission#MODIFY_QUIET_MODE}</li>
933 * <li>Has {@link Manifest.permission#MANAGE_USERS}</li>
Bookatz3cb67df2019-10-16 17:20:06 -0400934 * <li>Is the foreground default launcher app</li>
Tony Make3d1f652017-12-12 11:00:37 +0000935 * </ul>
Tony Makd390ae92017-12-28 13:23:10 +0000936 * <p>
Bookatz3cb67df2019-10-16 17:20:06 -0400937 * If caller wants to start an intent after disabling the quiet mode, or if it is targeting a
938 * user in a different profile group from the caller, it must have
Tony Makd390ae92017-12-28 13:23:10 +0000939 * {@link Manifest.permission#MANAGE_USERS}.
Tony Make3d1f652017-12-12 11:00:37 +0000940 */
Tony Makd390ae92017-12-28 13:23:10 +0000941 private void ensureCanModifyQuietMode(String callingPackage, int callingUid,
Bookatz3cb67df2019-10-16 17:20:06 -0400942 @UserIdInt int targetUserId, boolean startIntent) {
Tony Make3d1f652017-12-12 11:00:37 +0000943 if (hasManageUsersPermission()) {
Tony Makd390ae92017-12-28 13:23:10 +0000944 return;
Tony Make3d1f652017-12-12 11:00:37 +0000945 }
Tony Makd390ae92017-12-28 13:23:10 +0000946 if (startIntent) {
947 throw new SecurityException("MANAGE_USERS permission is required to start intent "
948 + "after disabling quiet mode.");
949 }
Bookatz3cb67df2019-10-16 17:20:06 -0400950 if (!isSameProfileGroupNoChecks(UserHandle.getUserId(callingUid), targetUserId)) {
951 throw new SecurityException("MANAGE_USERS permission is required to modify quiet mode "
952 + "for a different profile group.");
953 }
jovanakf24ad492018-05-18 12:15:59 -0700954 final boolean hasModifyQuietModePermission = hasPermissionGranted(
955 Manifest.permission.MODIFY_QUIET_MODE, callingUid);
Tony Make3d1f652017-12-12 11:00:37 +0000956 if (hasModifyQuietModePermission) {
Tony Makd390ae92017-12-28 13:23:10 +0000957 return;
Tony Make3d1f652017-12-12 11:00:37 +0000958 }
959
Tony Makd390ae92017-12-28 13:23:10 +0000960 verifyCallingPackage(callingPackage, callingUid);
Tony Make3d1f652017-12-12 11:00:37 +0000961 final ShortcutServiceInternal shortcutInternal =
962 LocalServices.getService(ShortcutServiceInternal.class);
963 if (shortcutInternal != null) {
964 boolean isForegroundLauncher =
965 shortcutInternal.isForegroundDefaultLauncher(callingPackage, callingUid);
966 if (isForegroundLauncher) {
Tony Makd390ae92017-12-28 13:23:10 +0000967 return;
Tony Make3d1f652017-12-12 11:00:37 +0000968 }
969 }
Tony Makd390ae92017-12-28 13:23:10 +0000970 throw new SecurityException("Can't modify quiet mode, caller is neither foreground "
971 + "default launcher nor has MANAGE_USERS/MODIFY_QUIET_MODE permission");
Tony Make3d1f652017-12-12 11:00:37 +0000972 }
973
Bookatzf56f2582019-09-04 16:06:41 -0700974 private void setQuietModeEnabled(@UserIdInt int userId, boolean enableQuietMode,
arangelov9b632d72018-12-07 23:21:22 +0000975 IntentSender target, @Nullable String callingPackage) {
Tony Makb7e6fd42017-12-05 19:40:28 +0000976 final UserInfo profile, parent;
977 final UserData profileUserData;
978 synchronized (mUsersLock) {
Bookatzf56f2582019-09-04 16:06:41 -0700979 profile = getUserInfoLU(userId);
980 parent = getProfileParentLU(userId);
Tony Makb7e6fd42017-12-05 19:40:28 +0000981
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000982 if (profile == null || !profile.isManagedProfile()) {
Bookatzf56f2582019-09-04 16:06:41 -0700983 throw new IllegalArgumentException("User " + userId + " is not a profile");
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000984 }
Tony Makb7e6fd42017-12-05 19:40:28 +0000985 if (profile.isQuietModeEnabled() == enableQuietMode) {
986 Slog.i(LOG_TAG, "Quiet mode is already " + enableQuietMode);
987 return;
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000988 }
Tony Makb7e6fd42017-12-05 19:40:28 +0000989 profile.flags ^= UserInfo.FLAG_QUIET_MODE;
990 profileUserData = getUserDataLU(profile.id);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000991 }
Tony Makb7e6fd42017-12-05 19:40:28 +0000992 synchronized (mPackagesLock) {
993 writeUserLP(profileUserData);
994 }
995 try {
996 if (enableQuietMode) {
Bookatzf56f2582019-09-04 16:06:41 -0700997 ActivityManager.getService().stopUser(userId, /* force */true, null);
Tony Makb7e6fd42017-12-05 19:40:28 +0000998 LocalServices.getService(ActivityManagerInternal.class)
Bookatzf56f2582019-09-04 16:06:41 -0700999 .killForegroundAppsForUser(userId);
Tony Makb7e6fd42017-12-05 19:40:28 +00001000 } else {
1001 IProgressListener callback = target != null
1002 ? new DisableQuietModeUserUnlockedCallback(target)
1003 : null;
1004 ActivityManager.getService().startUserInBackgroundWithListener(
Bookatzf56f2582019-09-04 16:06:41 -07001005 userId, callback);
Rubin Xuf13c9802016-01-21 18:06:00 +00001006 }
Bookatzf56f2582019-09-04 16:06:41 -07001007 logQuietModeEnabled(userId, enableQuietMode, callingPackage);
Tony Makb7e6fd42017-12-05 19:40:28 +00001008 } catch (RemoteException e) {
1009 // Should not happen, same process.
1010 e.rethrowAsRuntimeException();
Rubin Xu0a29ecd2015-11-04 15:11:48 +00001011 }
Tony Makb7e6fd42017-12-05 19:40:28 +00001012 broadcastProfileAvailabilityChanges(profile.getUserHandle(), parent.getUserHandle(),
1013 enableQuietMode);
Rubin Xu0a29ecd2015-11-04 15:11:48 +00001014 }
1015
Bookatzf56f2582019-09-04 16:06:41 -07001016 private void logQuietModeEnabled(@UserIdInt int userId, boolean enableQuietMode,
arangelov9b632d72018-12-07 23:21:22 +00001017 @Nullable String callingPackage) {
1018 UserData userData;
1019 synchronized (mUsersLock) {
Bookatzf56f2582019-09-04 16:06:41 -07001020 userData = getUserDataLU(userId);
arangelov9b632d72018-12-07 23:21:22 +00001021 }
1022 if (userData == null) {
1023 return;
1024 }
1025 final long now = System.currentTimeMillis();
1026 final long period = (userData.getLastRequestQuietModeEnabledMillis() != 0L
1027 ? now - userData.getLastRequestQuietModeEnabledMillis()
1028 : now - userData.info.creationTime);
1029 DevicePolicyEventLogger
1030 .createEvent(DevicePolicyEnums.REQUEST_QUIET_MODE_ENABLED)
1031 .setStrings(callingPackage)
1032 .setBoolean(enableQuietMode)
1033 .setTimePeriod(period)
1034 .write();
1035 userData.setLastRequestQuietModeEnabledMillis(now);
1036 }
1037
Rubin Xu0a29ecd2015-11-04 15:11:48 +00001038 @Override
Bookatzf56f2582019-09-04 16:06:41 -07001039 public boolean isQuietModeEnabled(@UserIdInt int userId) {
Rubin Xu0a29ecd2015-11-04 15:11:48 +00001040 synchronized (mPackagesLock) {
1041 UserInfo info;
1042 synchronized (mUsersLock) {
Bookatzf56f2582019-09-04 16:06:41 -07001043 info = getUserInfoLU(userId);
Rubin Xu0a29ecd2015-11-04 15:11:48 +00001044 }
1045 if (info == null || !info.isManagedProfile()) {
Rubin Xuf13c9802016-01-21 18:06:00 +00001046 return false;
Rubin Xu0a29ecd2015-11-04 15:11:48 +00001047 }
1048 return info.isQuietModeEnabled();
1049 }
1050 }
1051
Tony Makb7e6fd42017-12-05 19:40:28 +00001052 /**
1053 * Show confirm credential screen to unlock user in order to turn off quiet mode.
1054 */
1055 private void showConfirmCredentialToDisableQuietMode(
Bookatzf56f2582019-09-04 16:06:41 -07001056 @UserIdInt int userId, @Nullable IntentSender target) {
Tony Makb7e6fd42017-12-05 19:40:28 +00001057 // otherwise, we show a profile challenge to trigger decryption of the user
1058 final KeyguardManager km = (KeyguardManager) mContext.getSystemService(
1059 Context.KEYGUARD_SERVICE);
Bookatzf56f2582019-09-04 16:06:41 -07001060 // We should use userId not credentialOwnerUserId here, as even if it is unified
Tony Makb7e6fd42017-12-05 19:40:28 +00001061 // lock, confirm screenlock page will know and show personal challenge, and unlock
1062 // work profile when personal challenge is correct
Bookatzf56f2582019-09-04 16:06:41 -07001063 final Intent unlockIntent = km.createConfirmDeviceCredentialIntent(null, null, userId);
Tony Makb7e6fd42017-12-05 19:40:28 +00001064 if (unlockIntent == null) {
1065 return;
Benjamin Franzf02420c2016-04-04 18:52:21 +01001066 }
Tony Makb7e6fd42017-12-05 19:40:28 +00001067 final Intent callBackIntent = new Intent(
1068 ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK);
1069 if (target != null) {
1070 callBackIntent.putExtra(Intent.EXTRA_INTENT, target);
Benjamin Franzf02420c2016-04-04 18:52:21 +01001071 }
Bookatzf56f2582019-09-04 16:06:41 -07001072 callBackIntent.putExtra(Intent.EXTRA_USER_ID, userId);
Tony Makb7e6fd42017-12-05 19:40:28 +00001073 callBackIntent.setPackage(mContext.getPackageName());
1074 callBackIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1075 final PendingIntent pendingIntent = PendingIntent.getBroadcast(
1076 mContext,
1077 0,
1078 callBackIntent,
1079 PendingIntent.FLAG_CANCEL_CURRENT |
1080 PendingIntent.FLAG_ONE_SHOT |
1081 PendingIntent.FLAG_IMMUTABLE);
1082 // After unlocking the challenge, it will disable quiet mode and run the original
1083 // intentSender
1084 unlockIntent.putExtra(Intent.EXTRA_INTENT, pendingIntent.getIntentSender());
1085 unlockIntent.setFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
1086 mContext.startActivity(unlockIntent);
Benjamin Franzf02420c2016-04-04 18:52:21 +01001087 }
1088
1089 @Override
Bookatzf56f2582019-09-04 16:06:41 -07001090 public void setUserEnabled(@UserIdInt int userId) {
Alexandra Gherghinadf35d572014-04-09 13:54:39 +01001091 checkManageUsersPermission("enable user");
1092 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001093 UserInfo info;
1094 synchronized (mUsersLock) {
1095 info = getUserInfoLU(userId);
1096 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +01001097 if (info != null && !info.isEnabled()) {
1098 info.flags ^= UserInfo.FLAG_DISABLED;
Amith Yamasani12747872015-12-07 14:19:49 -08001099 writeUserLP(getUserDataLU(info.id));
Alexandra Gherghinadf35d572014-04-09 13:54:39 +01001100 }
1101 }
1102 }
1103
jovanakf24ad492018-05-18 12:15:59 -07001104 @Override
Bookatzf56f2582019-09-04 16:06:41 -07001105 public void setUserAdmin(@UserIdInt int userId) {
jovanakf24ad492018-05-18 12:15:59 -07001106 checkManageUserAndAcrossUsersFullPermission("set user admin");
1107
1108 synchronized (mPackagesLock) {
1109 UserInfo info;
1110 synchronized (mUsersLock) {
1111 info = getUserInfoLU(userId);
1112 }
1113 if (info == null || info.isAdmin()) {
1114 // Exit if no user found with that id, or the user is already an Admin.
1115 return;
1116 }
1117
1118 info.flags ^= UserInfo.FLAG_ADMIN;
1119 writeUserLP(getUserDataLU(info.id));
1120 }
1121
1122 // Remove non-admin restrictions.
1123 // Keep synchronized with createUserEvenWhenDisallowed.
1124 setUserRestriction(UserManager.DISALLOW_SMS, false, userId);
1125 setUserRestriction(UserManager.DISALLOW_OUTGOING_CALLS, false, userId);
1126 }
1127
Andrew Scull85a63bc2016-10-24 13:47:47 +01001128 /**
1129 * Evicts a user's CE key by stopping and restarting the user.
1130 *
1131 * The key is evicted automatically by the user controller when the user has stopped.
1132 */
1133 @Override
1134 public void evictCredentialEncryptionKey(@UserIdInt int userId) {
1135 checkManageUsersPermission("evict CE key");
1136 final IActivityManager am = ActivityManagerNative.getDefault();
1137 final long identity = Binder.clearCallingIdentity();
1138 try {
1139 am.restartUserInBackground(userId);
1140 } catch (RemoteException re) {
1141 throw re.rethrowAsRuntimeException();
1142 } finally {
1143 Binder.restoreCallingIdentity(identity);
1144 }
1145 }
1146
Bookatz029832a2019-10-04 16:50:22 -07001147 /**
1148 * Returns the user type, e.g. {@link UserManager#USER_TYPE_FULL_GUEST}, of the given userId,
1149 * or null if the user doesn't exist.
1150 */
1151 @Override
1152 public @Nullable String getUserTypeForUser(@UserIdInt int userId) {
1153 // TODO(b/142482943): Decide on the appropriate permission requirements.
1154 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "getUserTypeForUser");
1155 return getUserTypeNoChecks(userId);
1156 }
1157
1158 /**
1159 * Returns the user type of the given userId, or null if the user doesn't exist.
1160 * <p>No permissions checks are made (but userId checks may be made).
1161 */
1162 private @Nullable String getUserTypeNoChecks(@UserIdInt int userId) {
1163 synchronized (mUsersLock) {
1164 final UserInfo userInfo = getUserInfoLU(userId);
1165 return userInfo != null ? userInfo.userType : null;
1166 }
1167 }
1168
1169 /**
1170 * Returns the UserTypeDetails of the given userId's user type, or null if the no such user.
1171 * <p>No permissions checks are made (but userId checks may be made).
1172 */
1173 private @Nullable UserTypeDetails getUserTypeDetailsNoChecks(@UserIdInt int userId) {
1174 final String typeStr = getUserTypeNoChecks(userId);
1175 return typeStr != null ? mUserTypes.get(typeStr) : null;
1176 }
1177
1178 /**
1179 * Returns the UserTypeDetails of the given userInfo's user type (or null for a null userInfo).
1180 */
1181 private @Nullable UserTypeDetails getUserTypeDetails(@Nullable UserInfo userInfo) {
1182 final String typeStr = userInfo != null ? userInfo.userType : null;
1183 return typeStr != null ? mUserTypes.get(typeStr) : null;
1184 }
1185
Alexandra Gherghinadf35d572014-04-09 13:54:39 +01001186 @Override
Bookatzf56f2582019-09-04 16:06:41 -07001187 public UserInfo getUserInfo(@UserIdInt int userId) {
Sudheer Shankaaccaa082016-06-14 16:22:57 -07001188 checkManageOrCreateUsersPermission("query user");
Tony Mak8673b282016-03-21 21:10:59 +00001189 synchronized (mUsersLock) {
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001190 return userWithName(getUserInfoLU(userId));
1191 }
1192 }
1193
1194 /**
1195 * Returns a UserInfo object with the name filled in, for Owner, or the original
1196 * if the name is already set.
1197 */
1198 private UserInfo userWithName(UserInfo orig) {
1199 if (orig != null && orig.name == null && orig.id == UserHandle.USER_SYSTEM) {
1200 UserInfo withName = new UserInfo(orig);
1201 withName.name = getOwnerName();
1202 return withName;
1203 } else {
1204 return orig;
Tony Mak8673b282016-03-21 21:10:59 +00001205 }
1206 }
1207
Bookatza8c2d2a2019-11-13 10:10:18 -08001208 /** Returns whether the given user type is one of the FULL user types. */
1209 boolean isUserTypeSubtypeOfFull(String userType) {
1210 UserTypeDetails userTypeDetails = mUserTypes.get(userType);
1211 return userTypeDetails != null && userTypeDetails.isFull();
1212 }
1213
1214 /** Returns whether the given user type is one of the PROFILE user types. */
1215 boolean isUserTypeSubtypeOfProfile(String userType) {
1216 UserTypeDetails userTypeDetails = mUserTypes.get(userType);
1217 return userTypeDetails != null && userTypeDetails.isProfile();
1218 }
1219
1220 /** Returns whether the given user type is one of the SYSTEM user types. */
1221 boolean isUserTypeSubtypeOfSystem(String userType) {
1222 UserTypeDetails userTypeDetails = mUserTypes.get(userType);
1223 return userTypeDetails != null && userTypeDetails.isSystem();
1224 }
1225
Tony Mak8673b282016-03-21 21:10:59 +00001226 @Override
Bookatz029832a2019-10-04 16:50:22 -07001227 public boolean hasBadge(@UserIdInt int userId) {
1228 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "hasBadge");
1229 final UserTypeDetails userTypeDetails = getUserTypeDetailsNoChecks(userId);
1230 return userTypeDetails != null && userTypeDetails.hasBadge();
1231 }
1232
1233 @Override
1234 public @StringRes int getUserBadgeLabelResId(@UserIdInt int userId) {
1235 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "getUserBadgeLabelResId");
1236 final UserInfo userInfo = getUserInfoNoChecks(userId);
1237 final UserTypeDetails userTypeDetails = getUserTypeDetails(userInfo);
1238 if (userInfo == null || userTypeDetails == null || !userTypeDetails.hasBadge()) {
1239 Slog.e(LOG_TAG, "Requested badge label for non-badged user " + userId);
1240 return Resources.ID_NULL;
1241 }
1242 final int badgeIndex = userInfo.profileBadge;
1243 return userTypeDetails.getBadgeLabel(badgeIndex);
1244 }
1245
1246 @Override
1247 public @ColorRes int getUserBadgeColorResId(@UserIdInt int userId) {
1248 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "getUserBadgeColorResId");
1249 final UserInfo userInfo = getUserInfoNoChecks(userId);
1250 final UserTypeDetails userTypeDetails = getUserTypeDetails(userInfo);
1251 if (userInfo == null || userTypeDetails == null || !userTypeDetails.hasBadge()) {
1252 Slog.e(LOG_TAG, "Requested badge color for non-badged user " + userId);
1253 return Resources.ID_NULL;
1254 }
1255 final int badgeIndex = userInfo.profileBadge;
1256 return userTypeDetails.getBadgeColor(badgeIndex);
1257 }
1258
1259 @Override
1260 public @DrawableRes int getUserIconBadgeResId(@UserIdInt int userId) {
1261 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "getUserIconBadgeResId");
1262 final UserTypeDetails userTypeDetails = getUserTypeDetailsNoChecks(userId);
1263 if (userTypeDetails == null || !userTypeDetails.hasBadge()) {
1264 Slog.e(LOG_TAG, "Requested icon badge for non-badged user " + userId);
1265 return Resources.ID_NULL;
1266 }
1267 return userTypeDetails.getIconBadge();
1268 }
1269
1270 @Override
1271 public @DrawableRes int getUserBadgeResId(@UserIdInt int userId) {
1272 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "getUserBadgeResId");
1273 final UserTypeDetails userTypeDetails = getUserTypeDetailsNoChecks(userId);
1274 if (userTypeDetails == null || !userTypeDetails.hasBadge()) {
1275 Slog.e(LOG_TAG, "Requested badge for non-badged user " + userId);
1276 return Resources.ID_NULL;
1277 }
1278 return userTypeDetails.getBadgePlain();
1279 }
1280
1281 @Override
1282 public @DrawableRes int getUserBadgeNoBackgroundResId(@UserIdInt int userId) {
1283 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId,
1284 "getUserBadgeNoBackgroundResId");
1285 final UserTypeDetails userTypeDetails = getUserTypeDetailsNoChecks(userId);
1286 if (userTypeDetails == null || !userTypeDetails.hasBadge()) {
1287 Slog.e(LOG_TAG, "Requested badge (no background) for non-badged user " + userId);
1288 return Resources.ID_NULL;
1289 }
1290 return userTypeDetails.getBadgeNoBackground();
1291 }
1292
1293 @Override
1294 public boolean isProfile(@UserIdInt int userId) {
1295 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isProfile");
Kenny Guy02c89902016-11-15 19:36:38 +00001296 synchronized (mUsersLock) {
1297 UserInfo userInfo = getUserInfoLU(userId);
Bookatz029832a2019-10-04 16:50:22 -07001298 return userInfo != null && userInfo.isProfile();
Kenny Guy02c89902016-11-15 19:36:38 +00001299 }
1300 }
1301
1302 @Override
Bookatzf56f2582019-09-04 16:06:41 -07001303 public boolean isManagedProfile(@UserIdInt int userId) {
Jon Miranda2b340a22019-01-25 14:03:49 -08001304 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isManagedProfile");
Fyodor Kupolov82402752015-10-28 14:54:51 -07001305 synchronized (mUsersLock) {
Amith Yamasani1c41dc82016-06-28 16:13:15 -07001306 UserInfo userInfo = getUserInfoLU(userId);
Tony Mak8673b282016-03-21 21:10:59 +00001307 return userInfo != null && userInfo.isManagedProfile();
Amith Yamasani13593602012-03-22 16:16:17 -07001308 }
1309 }
1310
Amith Yamasani71e6c692013-03-24 17:39:28 -07001311 @Override
Bookatzf56f2582019-09-04 16:06:41 -07001312 public boolean isUserUnlockingOrUnlocked(@UserIdInt int userId) {
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08001313 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isUserUnlockingOrUnlocked");
Fyodor Kupolovc413f702016-10-06 17:11:14 -07001314 return mLocalService.isUserUnlockingOrUnlocked(userId);
1315 }
1316
1317 @Override
Bookatzf56f2582019-09-04 16:06:41 -07001318 public boolean isUserUnlocked(@UserIdInt int userId) {
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08001319 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isUserUnlocked");
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07001320 return mLocalService.isUserUnlocked(userId);
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08001321 }
1322
1323 @Override
Bookatzf56f2582019-09-04 16:06:41 -07001324 public boolean isUserRunning(@UserIdInt int userId) {
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08001325 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isUserRunning");
1326 return mLocalService.isUserRunning(userId);
1327 }
1328
Makoto Onuki73dded22017-12-20 13:14:48 +09001329 @Override
Bookatzcde3d922019-03-08 14:30:00 -08001330 public String getUserName() {
1331 if (!hasManageUsersOrPermission(android.Manifest.permission.GET_ACCOUNTS_PRIVILEGED)) {
1332 throw new SecurityException("You need MANAGE_USERS or GET_ACCOUNTS_PRIVILEGED "
1333 + "permissions to: get user name");
1334 }
1335 final int userId = UserHandle.getUserId(Binder.getCallingUid());
1336 synchronized (mUsersLock) {
1337 UserInfo userInfo = userWithName(getUserInfoLU(userId));
1338 return userInfo == null ? "" : userInfo.name;
1339 }
1340 }
1341
1342 @Override
Makoto Onuki73dded22017-12-20 13:14:48 +09001343 public long getUserStartRealtime() {
1344 final int userId = UserHandle.getUserId(Binder.getCallingUid());
1345 synchronized (mUsersLock) {
1346 final UserData user = getUserDataLU(userId);
1347 if (user != null) {
1348 return user.startRealtime;
1349 }
1350 return 0;
1351 }
1352 }
1353
1354 @Override
1355 public long getUserUnlockRealtime() {
1356 synchronized (mUsersLock) {
1357 final UserData user = getUserDataLU(UserHandle.getUserId(Binder.getCallingUid()));
1358 if (user != null) {
1359 return user.unlockRealtime;
1360 }
1361 return 0;
1362 }
1363 }
1364
Bookatzf56f2582019-09-04 16:06:41 -07001365 private void checkManageOrInteractPermIfCallerInOtherProfileGroup(@UserIdInt int userId,
1366 String name) {
Felipe Lemec1ca4412019-09-11 09:23:26 -07001367 final int callingUserId = UserHandle.getCallingUserId();
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08001368 if (callingUserId == userId || isSameProfileGroupNoChecks(callingUserId, userId) ||
1369 hasManageUsersPermission()) {
1370 return;
1371 }
jovanakf24ad492018-05-18 12:15:59 -07001372 if (!hasPermissionGranted(Manifest.permission.INTERACT_ACROSS_USERS,
1373 Binder.getCallingUid())) {
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08001374 throw new SecurityException("You need INTERACT_ACROSS_USERS or MANAGE_USERS permission "
1375 + "to: check " + name);
1376 }
1377 }
1378
1379 @Override
Bookatzf56f2582019-09-04 16:06:41 -07001380 public boolean isDemoUser(@UserIdInt int userId) {
Felipe Lemec1ca4412019-09-11 09:23:26 -07001381 final int callingUserId = UserHandle.getCallingUserId();
Amith Yamasani1c41dc82016-06-28 16:13:15 -07001382 if (callingUserId != userId && !hasManageUsersPermission()) {
1383 throw new SecurityException("You need MANAGE_USERS permission to query if u=" + userId
1384 + " is a demo user");
1385 }
1386 synchronized (mUsersLock) {
1387 UserInfo userInfo = getUserInfoLU(userId);
1388 return userInfo != null && userInfo.isDemo();
1389 }
1390 }
1391
1392 @Override
Felipe Lemec1ca4412019-09-11 09:23:26 -07001393 public boolean isPreCreated(@UserIdInt int userId) {
1394 final int callingUserId = UserHandle.getCallingUserId();
1395 if (callingUserId != userId && !hasManageUsersPermission()) {
1396 throw new SecurityException("You need MANAGE_USERS permission to query if u=" + userId
1397 + " is pre-created");
1398 }
1399 synchronized (mUsersLock) {
1400 UserInfo userInfo = getUserInfoLU(userId);
1401 return userInfo != null && userInfo.preCreated;
1402 }
1403 }
1404
1405 @Override
Amith Yamasani71e6c692013-03-24 17:39:28 -07001406 public boolean isRestricted() {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001407 synchronized (mUsersLock) {
1408 return getUserInfoLU(UserHandle.getCallingUserId()).isRestricted();
Amith Yamasani71e6c692013-03-24 17:39:28 -07001409 }
1410 }
1411
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001412 @Override
Bookatzf56f2582019-09-04 16:06:41 -07001413 public boolean canHaveRestrictedProfile(@UserIdInt int userId) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001414 checkManageUsersPermission("canHaveRestrictedProfile");
Fyodor Kupolov82402752015-10-28 14:54:51 -07001415 synchronized (mUsersLock) {
1416 final UserInfo userInfo = getUserInfoLU(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001417 if (userInfo == null || !userInfo.canHaveProfile()) {
1418 return false;
1419 }
1420 if (!userInfo.isAdmin()) {
1421 return false;
1422 }
Makoto Onukie7927da2015-11-25 10:05:17 -08001423 // restricted profile can be created if there is no DO set and the admin user has no PO;
1424 return !mIsDeviceManaged && !mIsUserManaged.get(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001425 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001426 }
1427
Fyodor Kupolovca177562017-11-09 17:43:01 -08001428 @Override
1429 public boolean hasRestrictedProfiles() {
1430 checkManageUsersPermission("hasRestrictedProfiles");
1431 final int callingUserId = UserHandle.getCallingUserId();
1432 synchronized (mUsersLock) {
1433 final int userSize = mUsers.size();
1434 for (int i = 0; i < userSize; i++) {
1435 UserInfo profile = mUsers.valueAt(i).info;
1436 if (callingUserId != profile.id
1437 && profile.restrictedProfileParentId == callingUserId) {
1438 return true;
1439 }
1440 }
1441 return false;
1442 }
1443 }
1444
Amith Yamasani195263742012-08-21 15:40:12 -07001445 /*
1446 * Should be locked on mUsers before calling this.
1447 */
Andreas Gampe2e8c7672018-07-20 13:01:08 -07001448 @GuardedBy("mUsersLock")
Bookatzf56f2582019-09-04 16:06:41 -07001449 private UserInfo getUserInfoLU(@UserIdInt int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -08001450 final UserData userData = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -07001451 // If it is partial and not in the process of being removed, return as unknown user.
Amith Yamasani12747872015-12-07 14:19:49 -08001452 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001453 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
1454 return null;
1455 }
Amith Yamasani12747872015-12-07 14:19:49 -08001456 return userData != null ? userData.info : null;
1457 }
1458
Andreas Gampe2e8c7672018-07-20 13:01:08 -07001459 @GuardedBy("mUsersLock")
Bookatzf56f2582019-09-04 16:06:41 -07001460 private UserData getUserDataLU(@UserIdInt int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -08001461 final UserData userData = mUsers.get(userId);
1462 // If it is partial and not in the process of being removed, return as unknown user.
1463 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
1464 return null;
1465 }
1466 return userData;
Amith Yamasani195263742012-08-21 15:40:12 -07001467 }
1468
Fyodor Kupolov82402752015-10-28 14:54:51 -07001469 /**
1470 * Obtains {@link #mUsersLock} and return UserInfo from mUsers.
1471 * <p>No permissions checking or any addition checks are made</p>
1472 */
Bookatzf56f2582019-09-04 16:06:41 -07001473 private UserInfo getUserInfoNoChecks(@UserIdInt int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001474 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001475 final UserData userData = mUsers.get(userId);
1476 return userData != null ? userData.info : null;
1477 }
1478 }
1479
1480 /**
1481 * Obtains {@link #mUsersLock} and return UserData from mUsers.
1482 * <p>No permissions checking or any addition checks are made</p>
1483 */
Bookatzf56f2582019-09-04 16:06:41 -07001484 private UserData getUserDataNoChecks(@UserIdInt int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -08001485 synchronized (mUsersLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001486 return mUsers.get(userId);
1487 }
1488 }
1489
Amith Yamasani236b2b52015-08-18 14:32:14 -07001490 /** Called by PackageManagerService */
Bookatzf56f2582019-09-04 16:06:41 -07001491 public boolean exists(@UserIdInt int userId) {
Todd Kennedy0eb97382017-10-03 16:57:22 -07001492 return mLocalService.exists(userId);
Amith Yamasani13593602012-03-22 16:16:17 -07001493 }
1494
Amith Yamasani258848d2012-08-10 17:06:33 -07001495 @Override
Bookatzf56f2582019-09-04 16:06:41 -07001496 public void setUserName(@UserIdInt int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001497 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001498 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -07001499 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001500 UserData userData = getUserDataNoChecks(userId);
1501 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001502 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
1503 return;
1504 }
Amith Yamasani12747872015-12-07 14:19:49 -08001505 if (name != null && !name.equals(userData.info.name)) {
1506 userData.info.name = name;
1507 writeUserLP(userData);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001508 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -07001509 }
1510 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001511 if (changed) {
Bookatzf9368552019-03-14 11:57:09 -07001512 long ident = Binder.clearCallingIdentity();
1513 try {
1514 sendUserInfoChangedBroadcast(userId);
1515 } finally {
1516 Binder.restoreCallingIdentity(ident);
1517 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001518 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001519 }
1520
Amith Yamasani258848d2012-08-10 17:06:33 -07001521 @Override
Bookatzf56f2582019-09-04 16:06:41 -07001522 public void setUserIcon(@UserIdInt int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001523 checkManageUsersPermission("update users");
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01001524 if (hasUserRestriction(UserManager.DISALLOW_SET_USER_ICON, userId)) {
1525 Log.w(LOG_TAG, "Cannot set user icon. DISALLOW_SET_USER_ICON is enabled.");
1526 return;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001527 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01001528 mLocalService.setUserIcon(userId, bitmap);
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001529 }
1530
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01001531
1532
Bookatzf56f2582019-09-04 16:06:41 -07001533 private void sendUserInfoChangedBroadcast(@UserIdInt int userId) {
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001534 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
1535 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
1536 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -07001537 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001538 }
1539
Amith Yamasani258848d2012-08-10 17:06:33 -07001540 @Override
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001541 public ParcelFileDescriptor getUserIcon(int targetUserId) {
Bookatzcde3d922019-03-08 14:30:00 -08001542 if (!hasManageUsersOrPermission(android.Manifest.permission.GET_ACCOUNTS_PRIVILEGED)) {
1543 throw new SecurityException("You need MANAGE_USERS or GET_ACCOUNTS_PRIVILEGED "
1544 + "permissions to: get user icon");
1545 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001546 String iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001547 synchronized (mPackagesLock) {
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001548 UserInfo targetUserInfo = getUserInfoNoChecks(targetUserId);
1549 if (targetUserInfo == null || targetUserInfo.partial) {
1550 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + targetUserId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001551 return null;
1552 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001553
1554 final int callingUserId = UserHandle.getCallingUserId();
1555 final int callingGroupId = getUserInfoNoChecks(callingUserId).profileGroupId;
1556 final int targetGroupId = targetUserInfo.profileGroupId;
1557 final boolean sameGroup = (callingGroupId != UserInfo.NO_PROFILE_GROUP_ID
1558 && callingGroupId == targetGroupId);
1559 if ((callingUserId != targetUserId) && !sameGroup) {
Nicolas Prevot88cc3462014-05-14 14:51:48 +01001560 checkManageUsersPermission("get the icon of a user who is not related");
1561 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001562
1563 if (targetUserInfo.iconPath == null) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001564 return null;
1565 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001566 iconPath = targetUserInfo.iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001567 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001568
1569 try {
1570 return ParcelFileDescriptor.open(
1571 new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
1572 } catch (FileNotFoundException e) {
1573 Log.e(LOG_TAG, "Couldn't find icon file", e);
1574 }
1575 return null;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001576 }
1577
Bookatzf56f2582019-09-04 16:06:41 -07001578 public void makeInitialized(@UserIdInt int userId) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001579 checkManageUsersPermission("makeInitialized");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001580 boolean scheduleWriteUser = false;
Amith Yamasani12747872015-12-07 14:19:49 -08001581 UserData userData;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001582 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001583 userData = mUsers.get(userId);
1584 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001585 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001586 return;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001587 }
Amith Yamasani12747872015-12-07 14:19:49 -08001588 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1589 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001590 scheduleWriteUser = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001591 }
1592 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001593 if (scheduleWriteUser) {
Amith Yamasani12747872015-12-07 14:19:49 -08001594 scheduleWriteUser(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001595 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001596 }
1597
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001598 /**
1599 * If default guest restrictions haven't been initialized yet, add the basic
1600 * restrictions.
1601 */
1602 private void initDefaultGuestRestrictions() {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001603 synchronized (mGuestRestrictions) {
1604 if (mGuestRestrictions.isEmpty()) {
Samuel Tand9453b82016-03-14 15:57:02 -07001605 mGuestRestrictions.putBoolean(UserManager.DISALLOW_CONFIG_WIFI, true);
Fyodor Kupolove04462c2015-11-30 15:02:53 -08001606 mGuestRestrictions.putBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, true);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001607 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
1608 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
1609 }
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001610 }
1611 }
1612
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001613 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301614 public Bundle getDefaultGuestRestrictions() {
1615 checkManageUsersPermission("getDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001616 synchronized (mGuestRestrictions) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301617 return new Bundle(mGuestRestrictions);
1618 }
1619 }
1620
1621 @Override
1622 public void setDefaultGuestRestrictions(Bundle restrictions) {
1623 checkManageUsersPermission("setDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001624 synchronized (mGuestRestrictions) {
1625 mGuestRestrictions.clear();
1626 mGuestRestrictions.putAll(restrictions);
1627 }
1628 synchronized (mPackagesLock) {
1629 writeUserListLP();
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301630 }
1631 }
1632
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001633 /**
Pavel Grafov6a40f092016-10-25 15:46:51 +01001634 * See {@link UserManagerInternal#setDevicePolicyUserRestrictions}
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001635 */
Bookatzf56f2582019-09-04 16:06:41 -07001636 private void setDevicePolicyUserRestrictionsInner(@UserIdInt int userId,
1637 @Nullable Bundle restrictions, boolean isDeviceOwner, int cameraRestrictionScope) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001638 final Bundle global = new Bundle();
1639 final Bundle local = new Bundle();
1640
1641 // Sort restrictions into local and global ensuring they don't overlap.
1642 UserRestrictionsUtils.sortToGlobalAndLocal(restrictions, isDeviceOwner,
1643 cameraRestrictionScope, global, local);
1644
1645 boolean globalChanged, localChanged;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001646 synchronized (mRestrictionsLock) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001647 // Update global and local restrictions if they were changed.
1648 globalChanged = updateRestrictionsIfNeededLR(
1649 userId, global, mDevicePolicyGlobalUserRestrictions);
1650 localChanged = updateRestrictionsIfNeededLR(
1651 userId, local, mDevicePolicyLocalUserRestrictions);
1652
1653 if (isDeviceOwner) {
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001654 // Remember the global restriction owner userId to be able to make a distinction
1655 // in getUserRestrictionSource on who set local policies.
Pavel Grafov6a40f092016-10-25 15:46:51 +01001656 mDeviceOwnerUserId = userId;
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001657 } else {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001658 if (mDeviceOwnerUserId == userId) {
Zoltan Szatmary-Ban8a5536d2016-05-27 17:56:44 +01001659 // When profile owner sets restrictions it passes null global bundle and we
1660 // reset global restriction owner userId.
1661 // This means this user used to have DO, but now the DO is gone and the user
1662 // instead has PO.
Pavel Grafov6a40f092016-10-25 15:46:51 +01001663 mDeviceOwnerUserId = UserHandle.USER_NULL;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001664 }
1665 }
1666 }
1667 if (DBG) {
1668 Log.d(LOG_TAG, "setDevicePolicyUserRestrictions: userId=" + userId
1669 + " global=" + global + (globalChanged ? " (changed)" : "")
1670 + " local=" + local + (localChanged ? " (changed)" : "")
1671 );
1672 }
1673 // Don't call them within the mRestrictionsLock.
1674 synchronized (mPackagesLock) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001675 if (localChanged || globalChanged) {
Amith Yamasani12747872015-12-07 14:19:49 -08001676 writeUserLP(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001677 }
1678 }
1679
1680 synchronized (mRestrictionsLock) {
1681 if (globalChanged) {
1682 applyUserRestrictionsForAllUsersLR();
1683 } else if (localChanged) {
1684 applyUserRestrictionsLR(userId);
1685 }
1686 }
1687 }
1688
Pavel Grafov6a40f092016-10-25 15:46:51 +01001689 /**
1690 * Updates restriction bundle for a given user in a given restriction array. If new bundle is
1691 * empty, record is removed from the array.
1692 * @return whether restrictions bundle is different from the old one.
1693 */
Bookatzf56f2582019-09-04 16:06:41 -07001694 private boolean updateRestrictionsIfNeededLR(@UserIdInt int userId,
1695 @Nullable Bundle restrictions, SparseArray<Bundle> restrictionsArray) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001696 final boolean changed =
1697 !UserRestrictionsUtils.areEqual(restrictionsArray.get(userId), restrictions);
1698 if (changed) {
1699 if (!UserRestrictionsUtils.isEmpty(restrictions)) {
1700 restrictionsArray.put(userId, restrictions);
1701 } else {
1702 restrictionsArray.delete(userId);
1703 }
1704 }
1705 return changed;
1706 }
1707
Makoto Onuki068c54a2015-10-13 14:34:03 -07001708 @GuardedBy("mRestrictionsLock")
Bookatzf56f2582019-09-04 16:06:41 -07001709 private Bundle computeEffectiveUserRestrictionsLR(@UserIdInt int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001710 final Bundle baseRestrictions =
1711 UserRestrictionsUtils.nonNull(mBaseUserRestrictions.get(userId));
Pavel Grafov6a40f092016-10-25 15:46:51 +01001712 final Bundle global = UserRestrictionsUtils.mergeAll(mDevicePolicyGlobalUserRestrictions);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001713 final Bundle local = mDevicePolicyLocalUserRestrictions.get(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001714
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001715 if (UserRestrictionsUtils.isEmpty(global) && UserRestrictionsUtils.isEmpty(local)) {
1716 // Common case first.
1717 return baseRestrictions;
Makoto Onuki068c54a2015-10-13 14:34:03 -07001718 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001719 final Bundle effective = UserRestrictionsUtils.clone(baseRestrictions);
1720 UserRestrictionsUtils.merge(effective, global);
1721 UserRestrictionsUtils.merge(effective, local);
1722
Makoto Onuki068c54a2015-10-13 14:34:03 -07001723 return effective;
1724 }
1725
1726 @GuardedBy("mRestrictionsLock")
Bookatzf56f2582019-09-04 16:06:41 -07001727 private void invalidateEffectiveUserRestrictionsLR(@UserIdInt int userId) {
Makoto Onuki068c54a2015-10-13 14:34:03 -07001728 if (DBG) {
1729 Log.d(LOG_TAG, "invalidateEffectiveUserRestrictions userId=" + userId);
1730 }
1731 mCachedEffectiveUserRestrictions.remove(userId);
1732 }
1733
Bookatzf56f2582019-09-04 16:06:41 -07001734 private Bundle getEffectiveUserRestrictions(@UserIdInt int userId) {
Makoto Onuki068c54a2015-10-13 14:34:03 -07001735 synchronized (mRestrictionsLock) {
1736 Bundle restrictions = mCachedEffectiveUserRestrictions.get(userId);
1737 if (restrictions == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001738 restrictions = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001739 mCachedEffectiveUserRestrictions.put(userId, restrictions);
1740 }
1741 return restrictions;
Amith Yamasani8cd28b52014-06-08 17:54:27 -07001742 }
1743 }
1744
Makoto Onuki068c54a2015-10-13 14:34:03 -07001745 /** @return a specific user restriction that's in effect currently. */
1746 @Override
Bookatzf56f2582019-09-04 16:06:41 -07001747 public boolean hasUserRestriction(String restrictionKey, @UserIdInt int userId) {
Roshan Pius7969c802019-10-21 19:58:57 -07001748 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "hasUserRestriction");
Patrick Baumann2f2fd712019-07-31 15:18:53 -07001749 return mLocalService.hasUserRestriction(restrictionKey, userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001750 }
1751
Makoto Onukiacc50462018-02-14 14:13:49 -08001752 /** @return if any user has the given restriction. */
1753 @Override
1754 public boolean hasUserRestrictionOnAnyUser(String restrictionKey) {
1755 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1756 return false;
1757 }
1758 final List<UserInfo> users = getUsers(/* excludeDying= */ true);
1759 for (int i = 0; i < users.size(); i++) {
1760 final int userId = users.get(i).id;
1761 Bundle restrictions = getEffectiveUserRestrictions(userId);
1762 if (restrictions != null && restrictions.getBoolean(restrictionKey)) {
1763 return true;
1764 }
1765 }
1766 return false;
1767 }
1768
Christopher Tate65fb2e42019-10-11 17:00:23 -07001769 @Override
1770 public boolean isSettingRestrictedForUser(String setting, @UserIdInt int userId,
1771 String value, int callingUid) {
1772 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
1773 throw new SecurityException("Non-system caller");
1774 }
1775 return UserRestrictionsUtils.isSettingRestrictedForUser(mContext, setting, userId,
1776 value, callingUid);
1777 }
1778
1779 @Override
1780 public void addUserRestrictionsListener(final IUserRestrictionsListener listener) {
1781 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
1782 throw new SecurityException("Non-system caller");
1783 }
1784
1785 // NOTE: unregistering not supported; only client is the settings provider,
1786 // which installs a single static permanent listener. If that listener goes
1787 // bad it implies the whole system process is going to crash.
1788 mLocalService.addUserRestrictionsListener(
1789 (int userId, Bundle newRestrict, Bundle prevRestrict) -> {
1790 try {
1791 listener.onUserRestrictionsChanged(userId, newRestrict, prevRestrict);
1792 } catch (RemoteException re) {
1793 Slog.e("IUserRestrictionsListener",
1794 "Unable to invoke listener: " + re.getMessage());
1795 }
1796 });
1797 }
1798
Makoto Onuki068c54a2015-10-13 14:34:03 -07001799 /**
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001800 * @hide
1801 *
1802 * Returns who set a user restriction on a user.
1803 * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
1804 * @param restrictionKey the string key representing the restriction
1805 * @param userId the id of the user for whom to retrieve the restrictions.
1806 * @return The source of user restriction. Any combination of
1807 * {@link UserManager#RESTRICTION_NOT_SET},
1808 * {@link UserManager#RESTRICTION_SOURCE_SYSTEM},
1809 * {@link UserManager#RESTRICTION_SOURCE_DEVICE_OWNER}
1810 * and {@link UserManager#RESTRICTION_SOURCE_PROFILE_OWNER}
1811 */
1812 @Override
Bookatzf56f2582019-09-04 16:06:41 -07001813 public int getUserRestrictionSource(String restrictionKey, @UserIdInt int userId) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001814 List<EnforcingUser> enforcingUsers = getUserRestrictionSources(restrictionKey, userId);
1815 // Get "bitwise or" of restriction sources for all enforcing users.
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001816 int result = UserManager.RESTRICTION_NOT_SET;
Pavel Grafov6a40f092016-10-25 15:46:51 +01001817 for (int i = enforcingUsers.size() - 1; i >= 0; i--) {
1818 result |= enforcingUsers.get(i).getUserRestrictionSource();
1819 }
1820 return result;
1821 }
1822
1823 @Override
1824 public List<EnforcingUser> getUserRestrictionSources(
1825 String restrictionKey, @UserIdInt int userId) {
1826 checkManageUsersPermission("getUserRestrictionSource");
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001827
1828 // Shortcut for the most common case
1829 if (!hasUserRestriction(restrictionKey, userId)) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001830 return Collections.emptyList();
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001831 }
1832
Pavel Grafov6a40f092016-10-25 15:46:51 +01001833 final List<EnforcingUser> result = new ArrayList<>();
1834
1835 // Check if it is base restriction.
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001836 if (hasBaseUserRestriction(restrictionKey, userId)) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001837 result.add(new EnforcingUser(
1838 UserHandle.USER_NULL, UserManager.RESTRICTION_SOURCE_SYSTEM));
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001839 }
1840
Pavel Grafov6a40f092016-10-25 15:46:51 +01001841 synchronized (mRestrictionsLock) {
1842 // Check if it is set by profile owner.
1843 Bundle profileOwnerRestrictions = mDevicePolicyLocalUserRestrictions.get(userId);
1844 if (UserRestrictionsUtils.contains(profileOwnerRestrictions, restrictionKey)) {
1845 result.add(getEnforcingUserLocked(userId));
1846 }
1847
1848 // Iterate over all users who enforce global restrictions.
1849 for (int i = mDevicePolicyGlobalUserRestrictions.size() - 1; i >= 0; i--) {
1850 Bundle globalRestrictions = mDevicePolicyGlobalUserRestrictions.valueAt(i);
1851 int profileUserId = mDevicePolicyGlobalUserRestrictions.keyAt(i);
1852 if (UserRestrictionsUtils.contains(globalRestrictions, restrictionKey)) {
1853 result.add(getEnforcingUserLocked(profileUserId));
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001854 }
1855 }
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001856 }
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001857 return result;
1858 }
1859
Andreas Gampea36dc622018-02-05 17:19:22 -08001860 @GuardedBy("mRestrictionsLock")
Pavel Grafov6a40f092016-10-25 15:46:51 +01001861 private EnforcingUser getEnforcingUserLocked(@UserIdInt int userId) {
1862 int source = mDeviceOwnerUserId == userId ? UserManager.RESTRICTION_SOURCE_DEVICE_OWNER
1863 : UserManager.RESTRICTION_SOURCE_PROFILE_OWNER;
1864 return new EnforcingUser(userId, source);
1865 }
1866
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001867 /**
Makoto Onuki068c54a2015-10-13 14:34:03 -07001868 * @return UserRestrictions that are in effect currently. This always returns a new
1869 * {@link Bundle}.
1870 */
Amith Yamasani8cd28b52014-06-08 17:54:27 -07001871 @Override
Bookatzf56f2582019-09-04 16:06:41 -07001872 public Bundle getUserRestrictions(@UserIdInt int userId) {
Roshan Pius7969c802019-10-21 19:58:57 -07001873 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "getUserRestrictions");
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001874 return UserRestrictionsUtils.clone(getEffectiveUserRestrictions(userId));
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001875 }
1876
1877 @Override
Bookatzf56f2582019-09-04 16:06:41 -07001878 public boolean hasBaseUserRestriction(String restrictionKey, @UserIdInt int userId) {
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +00001879 checkManageUsersPermission("hasBaseUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001880 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1881 return false;
1882 }
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +00001883 synchronized (mRestrictionsLock) {
1884 Bundle bundle = mBaseUserRestrictions.get(userId);
1885 return (bundle != null && bundle.getBoolean(restrictionKey, false));
1886 }
1887 }
1888
1889 @Override
Bookatzf56f2582019-09-04 16:06:41 -07001890 public void setUserRestriction(String key, boolean value, @UserIdInt int userId) {
Fyodor Kupolovd4b26042015-07-27 14:30:59 -07001891 checkManageUsersPermission("setUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001892 if (!UserRestrictionsUtils.isValidRestriction(key)) {
1893 return;
1894 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001895 synchronized (mRestrictionsLock) {
1896 // Note we can't modify Bundles stored in mBaseUserRestrictions directly, so create
1897 // a copy.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001898 final Bundle newRestrictions = UserRestrictionsUtils.clone(
1899 mBaseUserRestrictions.get(userId));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001900 newRestrictions.putBoolean(key, value);
1901
Fyodor Kupolov82402752015-10-28 14:54:51 -07001902 updateUserRestrictionsInternalLR(newRestrictions, userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001903 }
1904 }
1905
Makoto Onuki068c54a2015-10-13 14:34:03 -07001906 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001907 * Optionally updating user restrictions, calculate the effective user restrictions and also
1908 * propagate to other services and system settings.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001909 *
Pavel Grafov6a40f092016-10-25 15:46:51 +01001910 * @param newBaseRestrictions User restrictions to set.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001911 * If null, will not update user restrictions and only does the propagation.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001912 * @param userId target user ID.
1913 */
1914 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001915 private void updateUserRestrictionsInternalLR(
Bookatzf56f2582019-09-04 16:06:41 -07001916 @Nullable Bundle newBaseRestrictions, @UserIdInt int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001917 final Bundle prevAppliedRestrictions = UserRestrictionsUtils.nonNull(
1918 mAppliedUserRestrictions.get(userId));
1919
1920 // Update base restrictions.
Pavel Grafov6a40f092016-10-25 15:46:51 +01001921 if (newBaseRestrictions != null) {
1922 // If newBaseRestrictions == the current one, it's probably a bug.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001923 final Bundle prevBaseRestrictions = mBaseUserRestrictions.get(userId);
1924
Pavel Grafov6a40f092016-10-25 15:46:51 +01001925 Preconditions.checkState(prevBaseRestrictions != newBaseRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001926 Preconditions.checkState(mCachedEffectiveUserRestrictions.get(userId)
Pavel Grafov6a40f092016-10-25 15:46:51 +01001927 != newBaseRestrictions);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001928
Pavel Grafov6a40f092016-10-25 15:46:51 +01001929 if (updateRestrictionsIfNeededLR(userId, newBaseRestrictions, mBaseUserRestrictions)) {
Amith Yamasani12747872015-12-07 14:19:49 -08001930 scheduleWriteUser(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001931 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001932 }
1933
Fyodor Kupolov82402752015-10-28 14:54:51 -07001934 final Bundle effective = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001935
Makoto Onuki759a7632015-10-28 16:43:10 -07001936 mCachedEffectiveUserRestrictions.put(userId, effective);
1937
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001938 // Apply the new restrictions.
Makoto Onuki4f160732015-10-27 17:15:38 -07001939 if (DBG) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001940 debug("Applying user restrictions: userId=" + userId
1941 + " new=" + effective + " prev=" + prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001942 }
1943
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001944 if (mAppOpsService != null) { // We skip it until system-ready.
Fyodor Kupolovec30ca32016-06-16 15:09:29 -07001945 mHandler.post(new Runnable() {
1946 @Override
1947 public void run() {
1948 try {
1949 mAppOpsService.setUserRestrictions(effective, mUserRestriconToken, userId);
1950 } catch (RemoteException e) {
1951 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
1952 }
1953 }
1954 });
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001955 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001956
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001957 propagateUserRestrictionsLR(userId, effective, prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001958
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001959 mAppliedUserRestrictions.put(userId, new Bundle(effective));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001960 }
1961
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001962 private void propagateUserRestrictionsLR(final int userId,
Makoto Onukid45a4a22015-11-02 17:17:38 -08001963 Bundle newRestrictions, Bundle prevRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001964 // Note this method doesn't touch any state, meaning it doesn't require mRestrictionsLock
1965 // actually, but we still need some kind of synchronization otherwise we might end up
1966 // calling listeners out-of-order, thus "LR".
1967
1968 if (UserRestrictionsUtils.areEqual(newRestrictions, prevRestrictions)) {
1969 return;
1970 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08001971
1972 final Bundle newRestrictionsFinal = new Bundle(newRestrictions);
1973 final Bundle prevRestrictionsFinal = new Bundle(prevRestrictions);
1974
1975 mHandler.post(new Runnable() {
1976 @Override
1977 public void run() {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07001978 UserRestrictionsUtils.applyUserRestrictions(
1979 mContext, userId, newRestrictionsFinal, prevRestrictionsFinal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001980
Makoto Onukid45a4a22015-11-02 17:17:38 -08001981 final UserRestrictionsListener[] listeners;
1982 synchronized (mUserRestrictionsListeners) {
1983 listeners = new UserRestrictionsListener[mUserRestrictionsListeners.size()];
1984 mUserRestrictionsListeners.toArray(listeners);
1985 }
1986 for (int i = 0; i < listeners.length; i++) {
1987 listeners[i].onUserRestrictionsChanged(userId,
1988 newRestrictionsFinal, prevRestrictionsFinal);
1989 }
Makoto Onukie72f81b2017-03-16 14:08:19 -07001990
1991 final Intent broadcast = new Intent(UserManager.ACTION_USER_RESTRICTIONS_CHANGED)
1992 .setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
1993 mContext.sendBroadcastAsUser(broadcast, UserHandle.of(userId));
Makoto Onukid45a4a22015-11-02 17:17:38 -08001994 }
1995 });
1996 }
1997
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001998 // Package private for the inner class.
Andreas Gampe2e8c7672018-07-20 13:01:08 -07001999 @GuardedBy("mRestrictionsLock")
Bookatzf56f2582019-09-04 16:06:41 -07002000 void applyUserRestrictionsLR(@UserIdInt int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002001 updateUserRestrictionsInternalLR(null, userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002002 }
2003
2004 @GuardedBy("mRestrictionsLock")
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002005 // Package private for the inner class.
2006 void applyUserRestrictionsForAllUsersLR() {
2007 if (DBG) {
2008 debug("applyUserRestrictionsForAllUsersLR");
2009 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07002010 // First, invalidate all cached values.
Makoto Onuki4f160732015-10-27 17:15:38 -07002011 mCachedEffectiveUserRestrictions.clear();
2012
Sudheer Shankadc589ac2016-11-10 15:30:17 -08002013 // We don't want to call into ActivityManagerService while taking a lock, so we'll call
Makoto Onuki068c54a2015-10-13 14:34:03 -07002014 // it on a handler.
2015 final Runnable r = new Runnable() {
2016 @Override
2017 public void run() {
2018 // Then get the list of running users.
2019 final int[] runningUsers;
2020 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08002021 runningUsers = ActivityManager.getService().getRunningUserIds();
Makoto Onuki068c54a2015-10-13 14:34:03 -07002022 } catch (RemoteException e) {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08002023 Log.w(LOG_TAG, "Unable to access ActivityManagerService");
Makoto Onuki068c54a2015-10-13 14:34:03 -07002024 return;
2025 }
2026 // Then re-calculate the effective restrictions and apply, only for running users.
2027 // It's okay if a new user has started after the getRunningUserIds() call,
2028 // because we'll do the same thing (re-calculate the restrictions and apply)
2029 // when we start a user.
Makoto Onuki068c54a2015-10-13 14:34:03 -07002030 synchronized (mRestrictionsLock) {
2031 for (int i = 0; i < runningUsers.length; i++) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002032 applyUserRestrictionsLR(runningUsers[i]);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002033 }
2034 }
2035 }
2036 };
2037 mHandler.post(r);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07002038 }
2039
Amith Yamasani258848d2012-08-10 17:06:33 -07002040 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -07002041 * Check if we've hit the limit of how many users can be created.
2042 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002043 private boolean isUserLimitReached() {
2044 int count;
2045 synchronized (mUsersLock) {
2046 count = getAliveUsersExcludingGuestsCountLU();
2047 }
2048 return count >= UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07002049 }
2050
Bookatz029832a2019-10-04 16:50:22 -07002051 /**
2052 * Returns whether more users of the given type can be added (based on how many users of that
2053 * type already exist).
2054 *
2055 * <p>For checking whether more profiles can be added to a particular parent use
2056 * {@link #canAddMoreProfilesToUser}.
2057 */
2058 private boolean canAddMoreUsersOfType(UserTypeDetails userTypeDetails) {
2059 final int max = userTypeDetails.getMaxAllowed();
2060 if (max == UserTypeDetails.UNLIMITED_NUMBER_OF_USERS) {
2061 return true; // Indicates that there is no max.
2062 }
2063 return getNumberOfUsersOfType(userTypeDetails.getName()) < max;
2064 }
2065
2066 /**
2067 * Gets the number of users of the given user type.
2068 * Does not include users that are about to die.
2069 */
2070 private int getNumberOfUsersOfType(String userType) {
2071 int count = 0;
2072 synchronized (mUsersLock) {
2073 final int size = mUsers.size();
2074 for (int i = 0; i < size; i++) {
2075 final UserInfo user = mUsers.valueAt(i).info;
2076 if (user.userType.equals(userType)
2077 && !user.guestToRemove
2078 && !mRemovingUserIds.get(user.id)
2079 && !user.preCreated) {
2080 count++;
2081 }
2082 }
2083 }
2084 return count;
2085 }
2086
Nicolas Prevot12678a92015-05-13 12:15:03 -07002087 @Override
Bookatzf56f2582019-09-04 16:06:41 -07002088 public boolean canAddMoreManagedProfiles(@UserIdInt int userId, boolean allowedToRemoveOne) {
Bookatz029832a2019-10-04 16:50:22 -07002089 return canAddMoreProfilesToUser(UserManager.USER_TYPE_PROFILE_MANAGED, userId,
2090 allowedToRemoveOne);
2091 }
2092
2093 /** Returns whether more profiles of the given type can be added to the given parent userId. */
2094 @Override
2095 public boolean canAddMoreProfilesToUser(String userType, @UserIdInt int userId,
2096 boolean allowedToRemoveOne) {
2097 checkManageUsersPermission("check if more profiles can be added.");
2098 final UserTypeDetails type = mUserTypes.get(userType);
2099 if (type == null) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07002100 return false;
2101 }
Bookatz029832a2019-10-04 16:50:22 -07002102 // Managed profiles have their own specific rules.
2103 final boolean isManagedProfile = type.isManagedProfile();
2104 if (isManagedProfile) {
2105 if (ActivityManager.isLowRamDeviceStatic()) {
2106 return false;
2107 }
2108 if (!mContext.getPackageManager().hasSystemFeature(
2109 PackageManager.FEATURE_MANAGED_USERS)) {
2110 return false;
2111 }
Fyodor Kupolovb6157992015-06-05 15:32:28 -07002112 }
Bookatz029832a2019-10-04 16:50:22 -07002113 synchronized (mUsersLock) {
2114 // Check if the parent exists and its type is even allowed to have a profile.
Fyodor Kupolov82402752015-10-28 14:54:51 -07002115 UserInfo userInfo = getUserInfoLU(userId);
yuanhao47f9f7c2017-01-18 09:54:45 +08002116 if (userInfo == null || !userInfo.canHaveProfile()) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07002117 return false;
2118 }
Bookatz029832a2019-10-04 16:50:22 -07002119
2120 // Limit the number of profiles that can be created
2121 final int maxUsersOfType = getMaxUsersOfTypePerParent(type);
2122 if (maxUsersOfType != UserTypeDetails.UNLIMITED_NUMBER_OF_USERS) {
2123 final int userTypeCount = getProfileIds(userId, userType, false).length;
2124 final int profilesRemovedCount = userTypeCount > 0 && allowedToRemoveOne ? 1 : 0;
2125 if (userTypeCount - profilesRemovedCount >= maxUsersOfType) {
2126 return false;
2127 }
2128 // Allow creating a managed profile in the special case where there is only one user
2129 if (isManagedProfile) {
2130 int usersCountAfterRemoving = getAliveUsersExcludingGuestsCountLU()
2131 - profilesRemovedCount;
2132 return usersCountAfterRemoving == 1
2133 || usersCountAfterRemoving < UserManager.getMaxSupportedUsers();
2134 }
2135 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07002136 }
Bookatz029832a2019-10-04 16:50:22 -07002137 return true;
Nicolas Prevot12678a92015-05-13 12:15:03 -07002138 }
2139
Andreas Gampe2e8c7672018-07-20 13:01:08 -07002140 @GuardedBy("mUsersLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07002141 private int getAliveUsersExcludingGuestsCountLU() {
Amith Yamasanif584f012014-05-19 17:57:25 -07002142 int aliveUserCount = 0;
2143 final int totalUserCount = mUsers.size();
2144 // Skip over users being removed
2145 for (int i = 0; i < totalUserCount; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002146 UserInfo user = mUsers.valueAt(i).info;
Felipe Lemec1ca4412019-09-11 09:23:26 -07002147 if (!mRemovingUserIds.get(user.id) && !user.isGuest() && !user.preCreated) {
Amith Yamasanif584f012014-05-19 17:57:25 -07002148 aliveUserCount++;
2149 }
2150 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07002151 return aliveUserCount;
Amith Yamasanifaea76f2012-09-11 10:59:48 -07002152 }
2153
2154 /**
Amith Yamasani195263742012-08-21 15:40:12 -07002155 * Enforces that only the system UID or root's UID or apps that have the
Xiaohui Chenb3b92582015-12-07 11:22:13 -08002156 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} and
2157 * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL INTERACT_ACROSS_USERS_FULL}
2158 * permissions can make certain calls to the UserManager.
2159 *
2160 * @param message used as message if SecurityException is thrown
2161 * @throws SecurityException if the caller does not have enough privilege.
2162 */
2163 private static final void checkManageUserAndAcrossUsersFullPermission(String message) {
2164 final int uid = Binder.getCallingUid();
jovanakf24ad492018-05-18 12:15:59 -07002165
2166 if (uid == Process.SYSTEM_UID || uid == 0) {
2167 // System UID or root's UID are granted privilege.
2168 return;
Xiaohui Chenb3b92582015-12-07 11:22:13 -08002169 }
jovanakf24ad492018-05-18 12:15:59 -07002170
2171 if (hasPermissionGranted(Manifest.permission.MANAGE_USERS, uid)
2172 && hasPermissionGranted(Manifest.permission.INTERACT_ACROSS_USERS_FULL, uid)) {
2173 // Apps with both permissions are granted privilege.
2174 return;
2175 }
2176
2177 throw new SecurityException(
2178 "You need MANAGE_USERS and INTERACT_ACROSS_USERS_FULL permission to: " + message);
2179 }
2180
2181 private static boolean hasPermissionGranted(String permission, int uid) {
2182 return ActivityManager.checkComponentPermission(
2183 permission, uid, /* owningUid = */-1, /* exported = */ true) ==
2184 PackageManager.PERMISSION_GRANTED;
Xiaohui Chenb3b92582015-12-07 11:22:13 -08002185 }
2186
2187 /**
2188 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -07002189 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -07002190 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -07002191 *
2192 * @param message used as message if SecurityException is thrown
2193 * @throws SecurityException if the caller is not system or root
Tony Mak4dc008c2016-03-16 10:46:49 +00002194 * @see #hasManageUsersPermission()
Amith Yamasani258848d2012-08-10 17:06:33 -07002195 */
Amith Yamasanibe465322014-04-24 13:45:17 -07002196 private static final void checkManageUsersPermission(String message) {
Tony Mak4dc008c2016-03-16 10:46:49 +00002197 if (!hasManageUsersPermission()) {
Amith Yamasanibe465322014-04-24 13:45:17 -07002198 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
2199 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -04002200 }
2201
Esteban Talavera5b9f1672015-12-11 15:22:34 +00002202 /**
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002203 * Enforces that only the system UID or root's UID or apps that have the
2204 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or
2205 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS}
2206 * can make certain calls to the UserManager.
2207 *
2208 * @param message used as message if SecurityException is thrown
2209 * @throws SecurityException if the caller is not system or root
2210 * @see #hasManageOrCreateUsersPermission()
2211 */
2212 private static final void checkManageOrCreateUsersPermission(String message) {
2213 if (!hasManageOrCreateUsersPermission()) {
2214 throw new SecurityException(
2215 "You either need MANAGE_USERS or CREATE_USERS permission to: " + message);
2216 }
2217 }
2218
2219 /**
2220 * Similar to {@link #checkManageOrCreateUsersPermission(String)} but when the caller is tries
2221 * to create user/profiles other than what is allowed for
2222 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS} permission, then it will only
2223 * allow callers with {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} permission.
2224 */
2225 private static final void checkManageOrCreateUsersPermission(int creationFlags) {
2226 if ((creationFlags & ~ALLOWED_FLAGS_FOR_CREATE_USERS_PERMISSION) == 0) {
2227 if (!hasManageOrCreateUsersPermission()) {
2228 throw new SecurityException("You either need MANAGE_USERS or CREATE_USERS "
2229 + "permission to create an user with flags: " + creationFlags);
2230 }
2231 } else if (!hasManageUsersPermission()) {
2232 throw new SecurityException("You need MANAGE_USERS permission to create an user "
2233 + " with flags: " + creationFlags);
2234 }
2235 }
2236
2237 /**
Tony Mak4dc008c2016-03-16 10:46:49 +00002238 * @return whether the calling UID is system UID or root's UID or the calling app has the
2239 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}.
2240 */
2241 private static final boolean hasManageUsersPermission() {
2242 final int callingUid = Binder.getCallingUid();
2243 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
2244 || callingUid == Process.ROOT_UID
jovanakf24ad492018-05-18 12:15:59 -07002245 || hasPermissionGranted(android.Manifest.permission.MANAGE_USERS, callingUid);
Tony Mak4dc008c2016-03-16 10:46:49 +00002246 }
2247
2248 /**
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002249 * @return whether the calling UID is system UID or root's UID or the calling app has the
Bookatzcde3d922019-03-08 14:30:00 -08002250 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or the provided permission.
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002251 */
Bookatzcde3d922019-03-08 14:30:00 -08002252 private static final boolean hasManageUsersOrPermission(String alternativePermission) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002253 final int callingUid = Binder.getCallingUid();
2254 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
2255 || callingUid == Process.ROOT_UID
jovanakf24ad492018-05-18 12:15:59 -07002256 || hasPermissionGranted(android.Manifest.permission.MANAGE_USERS, callingUid)
Bookatzcde3d922019-03-08 14:30:00 -08002257 || hasPermissionGranted(alternativePermission, callingUid);
2258 }
2259
2260 /**
2261 * @return whether the calling UID is system UID or root's UID or the calling app has the
2262 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or
2263 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS}.
2264 */
2265 private static final boolean hasManageOrCreateUsersPermission() {
2266 return hasManageUsersOrPermission(android.Manifest.permission.CREATE_USERS);
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002267 }
2268
2269 /**
Esteban Talavera5b9f1672015-12-11 15:22:34 +00002270 * Enforces that only the system UID or root's UID (on any user) can make certain calls to the
2271 * UserManager.
2272 *
2273 * @param message used as message if SecurityException is thrown
2274 * @throws SecurityException if the caller is not system or root
2275 */
2276 private static void checkSystemOrRoot(String message) {
2277 final int uid = Binder.getCallingUid();
2278 if (!UserHandle.isSameApp(uid, Process.SYSTEM_UID) && uid != Process.ROOT_UID) {
2279 throw new SecurityException("Only system may: " + message);
2280 }
2281 }
2282
Fyodor Kupolov82402752015-10-28 14:54:51 -07002283 private void writeBitmapLP(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002284 try {
2285 File dir = new File(mUsersDir, Integer.toString(info.id));
2286 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +01002287 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002288 if (!dir.exists()) {
2289 dir.mkdir();
2290 FileUtils.setPermissions(
2291 dir.getPath(),
2292 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
2293 -1, -1);
2294 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07002295 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +01002296 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01002297 && tmp.renameTo(file) && SELinux.restorecon(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -07002298 info.iconPath = file.getAbsolutePath();
2299 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07002300 try {
2301 os.close();
2302 } catch (IOException ioe) {
2303 // What the ... !
2304 }
Adrian Roos1bdff912015-02-17 15:51:35 +01002305 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002306 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002307 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002308 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002309 }
2310
Amith Yamasani0b285492011-04-14 17:35:23 -07002311 /**
2312 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
2313 * cache it elsewhere.
2314 * @return the array of user ids.
2315 */
Dianne Hackborn1676c852012-09-10 14:52:30 -07002316 public int[] getUserIds() {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002317 synchronized (mUsersLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07002318 return mUserIds;
2319 }
Amith Yamasani0b285492011-04-14 17:35:23 -07002320 }
2321
Andreas Gampe2e8c7672018-07-20 13:01:08 -07002322 @GuardedBy({"mRestrictionsLock", "mPackagesLock"})
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002323 private void readUserListLP() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002324 if (!mUserListFile.exists()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002325 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002326 return;
2327 }
2328 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07002329 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002330 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07002331 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002332 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002333 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002334 int type;
2335 while ((type = parser.next()) != XmlPullParser.START_TAG
2336 && type != XmlPullParser.END_DOCUMENT) {
Amith Yamasani12747872015-12-07 14:19:49 -08002337 // Skip
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002338 }
2339
2340 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07002341 Slog.e(LOG_TAG, "Unable to read user list");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002342 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002343 return;
2344 }
2345
Amith Yamasani2a003292012-08-14 18:25:45 -07002346 mNextSerialNumber = -1;
2347 if (parser.getName().equals(TAG_USERS)) {
2348 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
2349 if (lastSerialNumber != null) {
2350 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
2351 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07002352 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
2353 if (versionNumber != null) {
2354 mUserVersion = Integer.parseInt(versionNumber);
2355 }
Amith Yamasani2a003292012-08-14 18:25:45 -07002356 }
2357
Pavel Grafov6a40f092016-10-25 15:46:51 +01002358 // Pre-O global user restriction were stored as a single bundle (as opposed to per-user
2359 // currently), take care of it in case of upgrade.
2360 Bundle oldDevicePolicyGlobalUserRestrictions = null;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002361
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002362 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05302363 if (type == XmlPullParser.START_TAG) {
2364 final String name = parser.getName();
2365 if (name.equals(TAG_USER)) {
2366 String id = parser.getAttributeValue(null, ATTR_ID);
Amith Yamasani6f34b412012-10-22 18:19:27 -07002367
Amith Yamasani12747872015-12-07 14:19:49 -08002368 UserData userData = readUserLP(Integer.parseInt(id));
2369
2370 if (userData != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002371 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002372 mUsers.put(userData.info.id, userData);
2373 if (mNextSerialNumber < 0
2374 || mNextSerialNumber <= userData.info.id) {
2375 mNextSerialNumber = userData.info.id + 1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002376 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05302377 }
Amith Yamasani2a003292012-08-14 18:25:45 -07002378 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05302379 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -08002380 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2381 && type != XmlPullParser.END_TAG) {
2382 if (type == XmlPullParser.START_TAG) {
2383 if (parser.getName().equals(TAG_RESTRICTIONS)) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002384 synchronized (mGuestRestrictions) {
Fyodor Kupoloveafee022017-03-15 17:09:04 -07002385 UserRestrictionsUtils
2386 .readRestrictions(parser, mGuestRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002387 }
Amith Yamasanida0b1682014-11-21 12:58:17 -08002388 }
2389 break;
2390 }
2391 }
Pavel Grafov6a40f092016-10-25 15:46:51 +01002392 } else if (name.equals(TAG_DEVICE_OWNER_USER_ID)
2393 // Legacy name, should only be encountered when upgrading from pre-O.
2394 || name.equals(TAG_GLOBAL_RESTRICTION_OWNER_ID)) {
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01002395 String ownerUserId = parser.getAttributeValue(null, ATTR_ID);
2396 if (ownerUserId != null) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01002397 mDeviceOwnerUserId = Integer.parseInt(ownerUserId);
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01002398 }
Pavel Grafov6a40f092016-10-25 15:46:51 +01002399 } else if (name.equals(TAG_DEVICE_POLICY_RESTRICTIONS)) {
2400 // Should only happen when upgrading from pre-O (version < 7).
2401 oldDevicePolicyGlobalUserRestrictions =
2402 UserRestrictionsUtils.readRestrictions(parser);
Amith Yamasani258848d2012-08-10 17:06:33 -07002403 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002404 }
2405 }
Pavel Grafov6a40f092016-10-25 15:46:51 +01002406
Fyodor Kupolov82402752015-10-28 14:54:51 -07002407 updateUserIds();
Pavel Grafov6a40f092016-10-25 15:46:51 +01002408 upgradeIfNecessaryLP(oldDevicePolicyGlobalUserRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002409 } catch (IOException | XmlPullParserException e) {
2410 fallbackToSingleUserLP();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08002411 } finally {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002412 IoUtils.closeQuietly(fis);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002413 }
2414 }
2415
Amith Yamasani6f34b412012-10-22 18:19:27 -07002416 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -08002417 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Pavel Grafov6a40f092016-10-25 15:46:51 +01002418 * @param oldGlobalUserRestrictions Pre-O global device policy restrictions.
Amith Yamasani6f34b412012-10-22 18:19:27 -07002419 */
Andreas Gampe2e8c7672018-07-20 13:01:08 -07002420 @GuardedBy({"mRestrictionsLock", "mPackagesLock"})
Pavel Grafov6a40f092016-10-25 15:46:51 +01002421 private void upgradeIfNecessaryLP(Bundle oldGlobalUserRestrictions) {
Bookatz029832a2019-10-04 16:50:22 -07002422 upgradeIfNecessaryLP(oldGlobalUserRestrictions, mUserVersion);
2423 }
2424
2425 /**
2426 * Version of {@link #upgradeIfNecessaryLP(Bundle)} that takes in the userVersion for testing
2427 * purposes. For non-tests, use {@link #upgradeIfNecessaryLP(Bundle)}.
2428 */
2429 @GuardedBy({"mRestrictionsLock", "mPackagesLock"})
2430 @VisibleForTesting
2431 void upgradeIfNecessaryLP(Bundle oldGlobalUserRestrictions, int userVersion) {
Bookatz75f0a072019-08-05 14:12:16 -07002432 Set<Integer> userIdsToWrite = new ArraySet<>();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002433 final int originalVersion = mUserVersion;
Amith Yamasani6f34b412012-10-22 18:19:27 -07002434 if (userVersion < 1) {
2435 // Assign a proper name for the owner, if not initialized correctly before
Amith Yamasani12747872015-12-07 14:19:49 -08002436 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
2437 if ("Primary".equals(userData.info.name)) {
2438 userData.info.name =
2439 mContext.getResources().getString(com.android.internal.R.string.owner_name);
Bookatz75f0a072019-08-05 14:12:16 -07002440 userIdsToWrite.add(userData.info.id);
Amith Yamasani6f34b412012-10-22 18:19:27 -07002441 }
2442 userVersion = 1;
2443 }
2444
Amith Yamasanibc9625052012-11-15 14:39:18 -08002445 if (userVersion < 2) {
2446 // Owner should be marked as initialized
Amith Yamasani12747872015-12-07 14:19:49 -08002447 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
2448 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
2449 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
Bookatz75f0a072019-08-05 14:12:16 -07002450 userIdsToWrite.add(userData.info.id);
Amith Yamasanibc9625052012-11-15 14:39:18 -08002451 }
2452 userVersion = 2;
2453 }
2454
Amith Yamasani350962c2013-08-06 11:18:53 -07002455
Amith Yamasani5e486f52013-08-07 11:06:44 -07002456 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -07002457 userVersion = 4;
2458 }
2459
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07002460 if (userVersion < 5) {
2461 initDefaultGuestRestrictions();
2462 userVersion = 5;
2463 }
2464
Fyodor Kupolov1c363152015-09-02 13:27:21 -07002465 if (userVersion < 6) {
2466 final boolean splitSystemUser = UserManager.isSplitSystemUser();
Fyodor Kupolov82402752015-10-28 14:54:51 -07002467 synchronized (mUsersLock) {
2468 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002469 UserData userData = mUsers.valueAt(i);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002470 // In non-split mode, only user 0 can have restricted profiles
Amith Yamasani12747872015-12-07 14:19:49 -08002471 if (!splitSystemUser && userData.info.isRestricted()
2472 && (userData.info.restrictedProfileParentId
2473 == UserInfo.NO_PROFILE_GROUP_ID)) {
2474 userData.info.restrictedProfileParentId = UserHandle.USER_SYSTEM;
Bookatz75f0a072019-08-05 14:12:16 -07002475 userIdsToWrite.add(userData.info.id);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002476 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07002477 }
2478 }
2479 userVersion = 6;
2480 }
2481
Pavel Grafov6a40f092016-10-25 15:46:51 +01002482 if (userVersion < 7) {
2483 // Previously only one user could enforce global restrictions, now it is per-user.
2484 synchronized (mRestrictionsLock) {
2485 if (!UserRestrictionsUtils.isEmpty(oldGlobalUserRestrictions)
2486 && mDeviceOwnerUserId != UserHandle.USER_NULL) {
2487 mDevicePolicyGlobalUserRestrictions.put(
2488 mDeviceOwnerUserId, oldGlobalUserRestrictions);
2489 }
2490 // ENSURE_VERIFY_APPS is now enforced globally even if put by profile owner, so move
2491 // it from local to global bundle for all users who set it.
2492 UserRestrictionsUtils.moveRestriction(UserManager.ENSURE_VERIFY_APPS,
2493 mDevicePolicyLocalUserRestrictions, mDevicePolicyGlobalUserRestrictions
2494 );
2495 }
2496 userVersion = 7;
2497 }
2498
Bookatz75f0a072019-08-05 14:12:16 -07002499 if (userVersion < 8) {
2500 // Added FLAG_FULL and FLAG_SYSTEM flags.
2501 synchronized (mUsersLock) {
2502 UserData userData = mUsers.get(UserHandle.USER_SYSTEM);
2503 userData.info.flags |= UserInfo.FLAG_SYSTEM;
2504 if (!UserManager.isHeadlessSystemUserMode()) {
2505 userData.info.flags |= UserInfo.FLAG_FULL;
2506 }
2507 userIdsToWrite.add(userData.info.id);
2508
2509 // Mark FULL all non-profile users except USER_SYSTEM.
2510 // Start index at 1 since USER_SYSTEM is the smallest userId and we're skipping it.
2511 for (int i = 1; i < mUsers.size(); i++) {
2512 userData = mUsers.valueAt(i);
2513 if ((userData.info.flags & UserInfo.FLAG_MANAGED_PROFILE) == 0) {
2514 userData.info.flags |= UserInfo.FLAG_FULL;
2515 userIdsToWrite.add(userData.info.id);
2516 }
2517 }
2518 }
2519 userVersion = 8;
2520 }
2521
Bookatz029832a2019-10-04 16:50:22 -07002522 if (userVersion < 9) {
2523 // Convert from UserInfo flags to UserTypes. Apply FLAG_PROFILE to FLAG_MANAGED_PROFILE.
2524 synchronized (mUsersLock) {
2525 for (int i = 0; i < mUsers.size(); i++) {
2526 UserData userData = mUsers.valueAt(i);
2527 final int flags = userData.info.flags;
2528 if ((flags & UserInfo.FLAG_SYSTEM) != 0) {
2529 if ((flags & UserInfo.FLAG_FULL) != 0) {
2530 userData.info.userType = UserManager.USER_TYPE_FULL_SYSTEM;
2531 } else {
2532 userData.info.userType = UserManager.USER_TYPE_SYSTEM_HEADLESS;
2533 }
2534 } else {
2535 try {
2536 userData.info.userType = UserInfo.getDefaultUserType(flags);
2537 } catch (IllegalArgumentException e) {
2538 // TODO(b/142482943): What should we do here? Delete user? Crashloop?
2539 throw new IllegalStateException("Cannot upgrade user with flags "
2540 + Integer.toHexString(flags) + " because it doesn't correspond "
2541 + "to a valid user type.", e);
2542 }
2543 }
2544 // OEMs are responsible for their own custom upgrade logic here.
2545
2546 final UserTypeDetails userTypeDetails = mUserTypes.get(userData.info.userType);
2547 if (userTypeDetails == null) {
2548 throw new IllegalStateException(
2549 "Cannot upgrade user with flags " + Integer.toHexString(flags)
2550 + " because " + userData.info.userType + " isn't defined"
2551 + " on this device!");
2552 }
2553 userData.info.flags |= userTypeDetails.getDefaultUserInfoFlags();
2554 userIdsToWrite.add(userData.info.id);
2555 }
2556 }
2557 userVersion = 9;
2558 }
2559
Amith Yamasani6f34b412012-10-22 18:19:27 -07002560 if (userVersion < USER_VERSION) {
2561 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
2562 + USER_VERSION);
2563 } else {
2564 mUserVersion = userVersion;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002565
2566 if (originalVersion < mUserVersion) {
Bookatz75f0a072019-08-05 14:12:16 -07002567 for (int userId : userIdsToWrite) {
2568 UserData userData = getUserDataNoChecks(userId);
2569 if (userData != null) {
2570 writeUserLP(userData);
2571 }
2572 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002573 writeUserListLP();
2574 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07002575 }
2576 }
2577
Andreas Gampe2e8c7672018-07-20 13:01:08 -07002578 @GuardedBy({"mPackagesLock", "mRestrictionsLock"})
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002579 private void fallbackToSingleUserLP() {
Ying Zheng215116f2019-09-11 12:50:09 -07002580 int flags = UserInfo.FLAG_SYSTEM | UserInfo.FLAG_INITIALIZED | UserInfo.FLAG_ADMIN
2581 | UserInfo.FLAG_PRIMARY;
Xiaohui Chen70f6c382015-04-28 14:21:43 -07002582 // Create the system user
Bookatz029832a2019-10-04 16:50:22 -07002583 String systemUserType = UserManager.isHeadlessSystemUserMode() ?
2584 UserManager.USER_TYPE_SYSTEM_HEADLESS : UserManager.USER_TYPE_FULL_SYSTEM;
2585 flags |= mUserTypes.get(systemUserType).getDefaultUserInfoFlags();
2586 UserInfo system = new UserInfo(UserHandle.USER_SYSTEM, null, null, flags, systemUserType);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002587 UserData userData = putUserInfo(system);
Amith Yamasani634cf312012-10-04 17:34:21 -07002588 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -04002589 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -08002590
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05002591 Bundle restrictions = new Bundle();
Mahaver Chopra3d9805d2016-07-07 16:25:05 +01002592 try {
2593 final String[] defaultFirstUserRestrictions = mContext.getResources().getStringArray(
2594 com.android.internal.R.array.config_defaultFirstUserRestrictions);
2595 for (String userRestriction : defaultFirstUserRestrictions) {
2596 if (UserRestrictionsUtils.isValidRestriction(userRestriction)) {
2597 restrictions.putBoolean(userRestriction, true);
2598 }
2599 }
2600 } catch (Resources.NotFoundException e) {
2601 Log.e(LOG_TAG, "Couldn't find resource: config_defaultFirstUserRestrictions", e);
2602 }
2603
Pavel Grafov6a40f092016-10-25 15:46:51 +01002604 if (!restrictions.isEmpty()) {
2605 synchronized (mRestrictionsLock) {
2606 mBaseUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions);
2607 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07002608 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08002609
Fyodor Kupolov82402752015-10-28 14:54:51 -07002610 updateUserIds();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07002611 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002612
Amith Yamasani12747872015-12-07 14:19:49 -08002613 writeUserLP(userData);
Jeff Sharkeycd575992016-03-29 14:12:49 -06002614 writeUserListLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002615 }
2616
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07002617 private String getOwnerName() {
2618 return mContext.getResources().getString(com.android.internal.R.string.owner_name);
2619 }
2620
Bookatz75f0a072019-08-05 14:12:16 -07002621 private void scheduleWriteUser(UserData userData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002622 if (DBG) {
2623 debug("scheduleWriteUser");
2624 }
Makoto Onuki9e935a32015-11-06 14:24:24 -08002625 // No need to wrap it within a lock -- worst case, we'll just post the same message
2626 // twice.
Bookatz75f0a072019-08-05 14:12:16 -07002627 if (!mHandler.hasMessages(WRITE_USER_MSG, userData)) {
2628 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, userData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002629 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
2630 }
2631 }
2632
Amith Yamasani12747872015-12-07 14:19:49 -08002633 private void writeUserLP(UserData userData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002634 if (DBG) {
Amith Yamasani12747872015-12-07 14:19:49 -08002635 debug("writeUserLP " + userData);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002636 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002637 FileOutputStream fos = null;
Amith Yamasani12747872015-12-07 14:19:49 -08002638 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userData.info.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002639 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07002640 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002641 final BufferedOutputStream bos = new BufferedOutputStream(fos);
Kenny Guy02c89902016-11-15 19:36:38 +00002642 writeUserLP(userData, bos);
Amith Yamasani2a003292012-08-14 18:25:45 -07002643 userFile.finishWrite(fos);
2644 } catch (Exception ioe) {
Jeff Sharkeycd575992016-03-29 14:12:49 -06002645 Slog.e(LOG_TAG, "Error writing user info " + userData.info.id, ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -07002646 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002647 }
2648 }
2649
2650 /*
Kenny Guy02c89902016-11-15 19:36:38 +00002651 * Writes the user file in this format:
2652 *
2653 * <user flags="20039023" id="0">
2654 * <name>Primary</name>
2655 * </user>
2656 */
2657 @VisibleForTesting
2658 void writeUserLP(UserData userData, OutputStream os)
2659 throws IOException, XmlPullParserException {
2660 // XmlSerializer serializer = XmlUtils.serializerInstance();
2661 final XmlSerializer serializer = new FastXmlSerializer();
2662 serializer.setOutput(os, StandardCharsets.UTF_8.name());
2663 serializer.startDocument(null, true);
2664 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2665
2666 final UserInfo userInfo = userData.info;
2667 serializer.startTag(null, TAG_USER);
2668 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
2669 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
2670 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Bookatz029832a2019-10-04 16:50:22 -07002671 serializer.attribute(null, ATTR_TYPE, userInfo.userType);
Kenny Guy02c89902016-11-15 19:36:38 +00002672 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
2673 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
2674 Long.toString(userInfo.lastLoggedInTime));
2675 if (userInfo.lastLoggedInFingerprint != null) {
2676 serializer.attribute(null, ATTR_LAST_LOGGED_IN_FINGERPRINT,
2677 userInfo.lastLoggedInFingerprint);
2678 }
2679 if (userInfo.iconPath != null) {
2680 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
2681 }
2682 if (userInfo.partial) {
2683 serializer.attribute(null, ATTR_PARTIAL, "true");
2684 }
Felipe Lemec1ca4412019-09-11 09:23:26 -07002685 if (userInfo.preCreated) {
2686 serializer.attribute(null, ATTR_PRE_CREATED, "true");
2687 }
Kenny Guy02c89902016-11-15 19:36:38 +00002688 if (userInfo.guestToRemove) {
2689 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
2690 }
2691 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
2692 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
2693 Integer.toString(userInfo.profileGroupId));
2694 }
2695 serializer.attribute(null, ATTR_PROFILE_BADGE,
2696 Integer.toString(userInfo.profileBadge));
2697 if (userInfo.restrictedProfileParentId != UserInfo.NO_PROFILE_GROUP_ID) {
2698 serializer.attribute(null, ATTR_RESTRICTED_PROFILE_PARENT_ID,
2699 Integer.toString(userInfo.restrictedProfileParentId));
2700 }
2701 // Write seed data
2702 if (userData.persistSeedData) {
2703 if (userData.seedAccountName != null) {
2704 serializer.attribute(null, ATTR_SEED_ACCOUNT_NAME, userData.seedAccountName);
2705 }
2706 if (userData.seedAccountType != null) {
2707 serializer.attribute(null, ATTR_SEED_ACCOUNT_TYPE, userData.seedAccountType);
2708 }
2709 }
2710 if (userInfo.name != null) {
2711 serializer.startTag(null, TAG_NAME);
2712 serializer.text(userInfo.name);
2713 serializer.endTag(null, TAG_NAME);
2714 }
2715 synchronized (mRestrictionsLock) {
2716 UserRestrictionsUtils.writeRestrictions(serializer,
2717 mBaseUserRestrictions.get(userInfo.id), TAG_RESTRICTIONS);
2718 UserRestrictionsUtils.writeRestrictions(serializer,
2719 mDevicePolicyLocalUserRestrictions.get(userInfo.id),
2720 TAG_DEVICE_POLICY_RESTRICTIONS);
Pavel Grafov6a40f092016-10-25 15:46:51 +01002721 UserRestrictionsUtils.writeRestrictions(serializer,
2722 mDevicePolicyGlobalUserRestrictions.get(userInfo.id),
2723 TAG_DEVICE_POLICY_GLOBAL_RESTRICTIONS);
Kenny Guy02c89902016-11-15 19:36:38 +00002724 }
2725
2726 if (userData.account != null) {
2727 serializer.startTag(null, TAG_ACCOUNT);
2728 serializer.text(userData.account);
2729 serializer.endTag(null, TAG_ACCOUNT);
2730 }
2731
2732 if (userData.persistSeedData && userData.seedAccountOptions != null) {
2733 serializer.startTag(null, TAG_SEED_ACCOUNT_OPTIONS);
2734 userData.seedAccountOptions.saveToXml(serializer);
2735 serializer.endTag(null, TAG_SEED_ACCOUNT_OPTIONS);
2736 }
2737
arangelov9b632d72018-12-07 23:21:22 +00002738 if (userData.getLastRequestQuietModeEnabledMillis() != 0L) {
2739 serializer.startTag(/* namespace */ null, TAG_LAST_REQUEST_QUIET_MODE_ENABLED_CALL);
2740 serializer.text(String.valueOf(userData.getLastRequestQuietModeEnabledMillis()));
2741 serializer.endTag(/* namespace */ null, TAG_LAST_REQUEST_QUIET_MODE_ENABLED_CALL);
2742 }
2743
Kenny Guy02c89902016-11-15 19:36:38 +00002744 serializer.endTag(null, TAG_USER);
2745
2746 serializer.endDocument();
2747 }
2748
2749 /*
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002750 * Writes the user list file in this format:
2751 *
Amith Yamasani2a003292012-08-14 18:25:45 -07002752 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002753 * <user id="0"></user>
2754 * <user id="2"></user>
2755 * </users>
2756 */
Andreas Gampe2e8c7672018-07-20 13:01:08 -07002757 @GuardedBy({"mRestrictionsLock", "mPackagesLock"})
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002758 private void writeUserListLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002759 if (DBG) {
2760 debug("writeUserList");
2761 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002762 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07002763 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002764 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07002765 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002766 final BufferedOutputStream bos = new BufferedOutputStream(fos);
2767
2768 // XmlSerializer serializer = XmlUtils.serializerInstance();
2769 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002770 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002771 serializer.startDocument(null, true);
2772 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2773
2774 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -07002775 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -07002776 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002777
Adam Lesinskieddeb492014-09-08 17:50:03 -07002778 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002779 synchronized (mGuestRestrictions) {
2780 UserRestrictionsUtils
2781 .writeRestrictions(serializer, mGuestRestrictions, TAG_RESTRICTIONS);
2782 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05302783 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Pavel Grafov6a40f092016-10-25 15:46:51 +01002784 serializer.startTag(null, TAG_DEVICE_OWNER_USER_ID);
2785 serializer.attribute(null, ATTR_ID, Integer.toString(mDeviceOwnerUserId));
2786 serializer.endTag(null, TAG_DEVICE_OWNER_USER_ID);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002787 int[] userIdsToWrite;
2788 synchronized (mUsersLock) {
2789 userIdsToWrite = new int[mUsers.size()];
2790 for (int i = 0; i < userIdsToWrite.length; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002791 UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002792 userIdsToWrite[i] = user.id;
2793 }
2794 }
2795 for (int id : userIdsToWrite) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002796 serializer.startTag(null, TAG_USER);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002797 serializer.attribute(null, ATTR_ID, Integer.toString(id));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002798 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002799 }
2800
2801 serializer.endTag(null, TAG_USERS);
2802
2803 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07002804 userListFile.finishWrite(fos);
2805 } catch (Exception e) {
2806 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -07002807 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002808 }
2809 }
2810
Amith Yamasani12747872015-12-07 14:19:49 -08002811 private UserData readUserLP(int id) {
Kenny Guy02c89902016-11-15 19:36:38 +00002812 FileInputStream fis = null;
2813 try {
2814 AtomicFile userFile =
2815 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
2816 fis = userFile.openRead();
2817 return readUserLP(id, fis);
2818 } catch (IOException ioe) {
2819 Slog.e(LOG_TAG, "Error reading user list");
2820 } catch (XmlPullParserException pe) {
2821 Slog.e(LOG_TAG, "Error reading user list");
2822 } finally {
2823 IoUtils.closeQuietly(fis);
2824 }
2825 return null;
2826 }
2827
2828 @VisibleForTesting
2829 UserData readUserLP(int id, InputStream is) throws IOException,
2830 XmlPullParserException {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002831 int flags = 0;
Bookatz029832a2019-10-04 16:50:22 -07002832 String userType = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07002833 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002834 String name = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -08002835 String account = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002836 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -07002837 long creationTime = 0L;
2838 long lastLoggedInTime = 0L;
arangelov9b632d72018-12-07 23:21:22 +00002839 long lastRequestQuietModeEnabledTimestamp = 0L;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002840 String lastLoggedInFingerprint = null;
Kenny Guy2a764942014-04-02 13:29:20 +01002841 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Kenny Guy02c89902016-11-15 19:36:38 +00002842 int profileBadge = 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002843 int restrictedProfileParentId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002844 boolean partial = false;
Felipe Lemec1ca4412019-09-11 09:23:26 -07002845 boolean preCreated = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -07002846 boolean guestToRemove = false;
Amith Yamasani12747872015-12-07 14:19:49 -08002847 boolean persistSeedData = false;
2848 String seedAccountName = null;
2849 String seedAccountType = null;
2850 PersistableBundle seedAccountOptions = null;
Pavel Grafov6a40f092016-10-25 15:46:51 +01002851 Bundle baseRestrictions = null;
2852 Bundle localRestrictions = null;
2853 Bundle globalRestrictions = null;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002854
Kenny Guy02c89902016-11-15 19:36:38 +00002855 XmlPullParser parser = Xml.newPullParser();
2856 parser.setInput(is, StandardCharsets.UTF_8.name());
2857 int type;
2858 while ((type = parser.next()) != XmlPullParser.START_TAG
2859 && type != XmlPullParser.END_DOCUMENT) {
2860 // Skip
2861 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002862
Kenny Guy02c89902016-11-15 19:36:38 +00002863 if (type != XmlPullParser.START_TAG) {
2864 Slog.e(LOG_TAG, "Unable to read user " + id);
2865 return null;
2866 }
2867
2868 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
2869 int storedId = readIntAttribute(parser, ATTR_ID, -1);
2870 if (storedId != id) {
2871 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002872 return null;
2873 }
Kenny Guy02c89902016-11-15 19:36:38 +00002874 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
2875 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Bookatz029832a2019-10-04 16:50:22 -07002876 userType = parser.getAttributeValue(null, ATTR_TYPE);
2877 userType = userType != null ? userType.intern() : null;
Kenny Guy02c89902016-11-15 19:36:38 +00002878 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
2879 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
2880 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
2881 lastLoggedInFingerprint = parser.getAttributeValue(null,
2882 ATTR_LAST_LOGGED_IN_FINGERPRINT);
2883 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
2884 UserInfo.NO_PROFILE_GROUP_ID);
2885 profileBadge = readIntAttribute(parser, ATTR_PROFILE_BADGE, 0);
2886 restrictedProfileParentId = readIntAttribute(parser,
2887 ATTR_RESTRICTED_PROFILE_PARENT_ID, UserInfo.NO_PROFILE_GROUP_ID);
2888 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
2889 if ("true".equals(valueString)) {
2890 partial = true;
2891 }
Felipe Lemec1ca4412019-09-11 09:23:26 -07002892 valueString = parser.getAttributeValue(null, ATTR_PRE_CREATED);
2893 if ("true".equals(valueString)) {
2894 preCreated = true;
2895 }
Kenny Guy02c89902016-11-15 19:36:38 +00002896 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
2897 if ("true".equals(valueString)) {
2898 guestToRemove = true;
2899 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002900
Kenny Guy02c89902016-11-15 19:36:38 +00002901 seedAccountName = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_NAME);
2902 seedAccountType = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_TYPE);
2903 if (seedAccountName != null || seedAccountType != null) {
2904 persistSeedData = true;
2905 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002906
Kenny Guy02c89902016-11-15 19:36:38 +00002907 int outerDepth = parser.getDepth();
2908 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2909 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2910 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2911 continue;
2912 }
2913 String tag = parser.getName();
2914 if (TAG_NAME.equals(tag)) {
2915 type = parser.next();
2916 if (type == XmlPullParser.TEXT) {
2917 name = parser.getText();
2918 }
2919 } else if (TAG_RESTRICTIONS.equals(tag)) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01002920 baseRestrictions = UserRestrictionsUtils.readRestrictions(parser);
Kenny Guy02c89902016-11-15 19:36:38 +00002921 } else if (TAG_DEVICE_POLICY_RESTRICTIONS.equals(tag)) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01002922 localRestrictions = UserRestrictionsUtils.readRestrictions(parser);
2923 } else if (TAG_DEVICE_POLICY_GLOBAL_RESTRICTIONS.equals(tag)) {
2924 globalRestrictions = UserRestrictionsUtils.readRestrictions(parser);
Kenny Guy02c89902016-11-15 19:36:38 +00002925 } else if (TAG_ACCOUNT.equals(tag)) {
2926 type = parser.next();
2927 if (type == XmlPullParser.TEXT) {
2928 account = parser.getText();
2929 }
2930 } else if (TAG_SEED_ACCOUNT_OPTIONS.equals(tag)) {
2931 seedAccountOptions = PersistableBundle.restoreFromXml(parser);
Amith Yamasani12747872015-12-07 14:19:49 -08002932 persistSeedData = true;
arangelov9b632d72018-12-07 23:21:22 +00002933 } else if (TAG_LAST_REQUEST_QUIET_MODE_ENABLED_CALL.equals(tag)) {
2934 type = parser.next();
2935 if (type == XmlPullParser.TEXT) {
2936 lastRequestQuietModeEnabledTimestamp = Long.parseLong(parser.getText());
2937 }
Amith Yamasani12747872015-12-07 14:19:49 -08002938 }
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08002939 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002940 }
Kenny Guy02c89902016-11-15 19:36:38 +00002941
2942 // Create the UserInfo object that gets passed around
Bookatz029832a2019-10-04 16:50:22 -07002943 UserInfo userInfo = new UserInfo(id, name, iconPath, flags, userType);
Kenny Guy02c89902016-11-15 19:36:38 +00002944 userInfo.serialNumber = serialNumber;
2945 userInfo.creationTime = creationTime;
2946 userInfo.lastLoggedInTime = lastLoggedInTime;
2947 userInfo.lastLoggedInFingerprint = lastLoggedInFingerprint;
2948 userInfo.partial = partial;
Felipe Lemec1ca4412019-09-11 09:23:26 -07002949 userInfo.preCreated = preCreated;
Kenny Guy02c89902016-11-15 19:36:38 +00002950 userInfo.guestToRemove = guestToRemove;
2951 userInfo.profileGroupId = profileGroupId;
2952 userInfo.profileBadge = profileBadge;
2953 userInfo.restrictedProfileParentId = restrictedProfileParentId;
2954
2955 // Create the UserData object that's internal to this class
2956 UserData userData = new UserData();
2957 userData.info = userInfo;
2958 userData.account = account;
2959 userData.seedAccountName = seedAccountName;
2960 userData.seedAccountType = seedAccountType;
2961 userData.persistSeedData = persistSeedData;
2962 userData.seedAccountOptions = seedAccountOptions;
arangelov9b632d72018-12-07 23:21:22 +00002963 userData.setLastRequestQuietModeEnabledMillis(lastRequestQuietModeEnabledTimestamp);
Kenny Guy02c89902016-11-15 19:36:38 +00002964
2965 synchronized (mRestrictionsLock) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01002966 if (baseRestrictions != null) {
2967 mBaseUserRestrictions.put(id, baseRestrictions);
2968 }
2969 if (localRestrictions != null) {
2970 mDevicePolicyLocalUserRestrictions.put(id, localRestrictions);
2971 }
2972 if (globalRestrictions != null) {
2973 mDevicePolicyGlobalUserRestrictions.put(id, globalRestrictions);
2974 }
Kenny Guy02c89902016-11-15 19:36:38 +00002975 }
2976 return userData;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002977 }
2978
Amith Yamasani920ace02012-09-20 22:15:37 -07002979 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
2980 String valueString = parser.getAttributeValue(null, attr);
2981 if (valueString == null) return defaultValue;
2982 try {
2983 return Integer.parseInt(valueString);
2984 } catch (NumberFormatException nfe) {
2985 return defaultValue;
2986 }
2987 }
2988
2989 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
2990 String valueString = parser.getAttributeValue(null, attr);
2991 if (valueString == null) return defaultValue;
2992 try {
2993 return Long.parseLong(valueString);
2994 } catch (NumberFormatException nfe) {
2995 return defaultValue;
2996 }
2997 }
2998
Amith Yamasanib82add22013-07-09 11:24:44 -07002999 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07003000 * Removes the app restrictions file for a specific package and user id, if it exists.
3001 */
Bookatzf56f2582019-09-04 16:06:41 -07003002 private static void cleanAppRestrictionsForPackageLAr(String pkg, @UserIdInt int userId) {
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003003 File dir = Environment.getUserSystemDirectory(userId);
3004 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
3005 if (resFile.exists()) {
3006 resFile.delete();
Amith Yamasani1a7472e2013-07-02 11:17:30 -07003007 }
3008 }
3009
Bookatz029832a2019-10-04 16:50:22 -07003010 /**
3011 * Creates a profile user. Used for actual profiles, like
3012 * {@link UserManager#USER_TYPE_PROFILE_MANAGED}, as well as for
3013 * {@link UserManager#USER_TYPE_FULL_RESTRICTED}.
3014 */
Kenny Guya52dc3e2014-02-11 15:33:14 +00003015 @Override
Bookatz029832a2019-10-04 16:50:22 -07003016 public UserInfo createProfileForUser(String name, @NonNull String userType,
3017 @UserInfoFlag int flags, @UserIdInt int userId, @Nullable String[] disallowedPackages) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07003018 checkManageOrCreateUsersPermission(flags);
Bookatz029832a2019-10-04 16:50:22 -07003019 return createUserInternal(name, userType, flags, userId, disallowedPackages);
3020 }
3021
3022 /** @see #createProfileForUser */
3023 @Override
3024 public UserInfo createProfileForUserEvenWhenDisallowed(String name, @NonNull String userType,
3025 @UserInfoFlag int flags, @UserIdInt int userId, @Nullable String[] disallowedPackages) {
3026 checkManageOrCreateUsersPermission(flags);
3027 return createUserInternalUnchecked(name, userType, flags, userId,
3028 /* preCreate= */ false, disallowedPackages);
Kenny Guya52dc3e2014-02-11 15:33:14 +00003029 }
3030
Amith Yamasani258848d2012-08-10 17:06:33 -07003031 @Override
Bookatz029832a2019-10-04 16:50:22 -07003032 public UserInfo createUser(String name, @NonNull String userType, @UserInfoFlag int flags) {
Tony Mak6dc428f2016-10-10 15:48:27 +01003033 checkManageOrCreateUsersPermission(flags);
Bookatz029832a2019-10-04 16:50:22 -07003034 return createUserInternal(name, userType, flags, UserHandle.USER_NULL,
3035 /* disallowedPackages= */ null);
Tony Mak6dc428f2016-10-10 15:48:27 +01003036 }
3037
3038 @Override
Bookatz029832a2019-10-04 16:50:22 -07003039 public UserInfo preCreateUser(String userType) {
3040 final UserTypeDetails userTypeDetails = mUserTypes.get(userType);
3041 final int flags = userTypeDetails != null ? userTypeDetails.getDefaultUserInfoFlags() : 0;
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00003042
Felipe Lemec1ca4412019-09-11 09:23:26 -07003043 checkManageOrCreateUsersPermission(flags);
3044
Bookatz029832a2019-10-04 16:50:22 -07003045 Preconditions.checkArgument(isUserTypeEligibleForPreCreation(userTypeDetails),
3046 "cannot pre-create user of type " + userType);
3047 Slog.i(LOG_TAG, "Pre-creating user of type " + userType);
Felipe Lemec1ca4412019-09-11 09:23:26 -07003048
Bookatz029832a2019-10-04 16:50:22 -07003049 return createUserInternalUnchecked(/* name= */ null, userType, flags,
Felipe Lemec1ca4412019-09-11 09:23:26 -07003050 /* parentId= */ UserHandle.USER_NULL, /* preCreate= */ true,
3051 /* disallowedPackages= */ null);
3052 }
3053
Bookatz029832a2019-10-04 16:50:22 -07003054 private UserInfo createUserInternal(@Nullable String name, @NonNull String userType,
3055 @UserInfoFlag int flags, @UserIdInt int parentId,
3056 @Nullable String[] disallowedPackages) {
3057 String restriction = (UserManager.isUserTypeManagedProfile(userType))
Esteban Talavera6c9116a2016-11-24 16:12:44 +00003058 ? UserManager.DISALLOW_ADD_MANAGED_PROFILE
3059 : UserManager.DISALLOW_ADD_USER;
3060 if (hasUserRestriction(restriction, UserHandle.getCallingUserId())) {
3061 Log.w(LOG_TAG, "Cannot add user. " + restriction + " is enabled.");
Julia Reynolds75175022014-06-26 16:35:00 -04003062 return null;
3063 }
Bookatz029832a2019-10-04 16:50:22 -07003064 return createUserInternalUnchecked(name, userType, flags, parentId,
3065 /* preCreate= */ false, disallowedPackages);
Tony Mak6dc428f2016-10-10 15:48:27 +01003066 }
3067
Bookatz029832a2019-10-04 16:50:22 -07003068 private UserInfo createUserInternalUnchecked(@Nullable String name,
3069 @NonNull String userType, @UserInfoFlag int flags, @UserIdInt int parentId,
3070 boolean preCreate, @Nullable String[] disallowedPackages) {
Felipe Lemec1ca4412019-09-11 09:23:26 -07003071 final TimingsTraceAndSlog t = new TimingsTraceAndSlog();
3072 t.traceBegin("createUser-" + flags);
3073 try {
Bookatz029832a2019-10-04 16:50:22 -07003074 return createUserInternalUncheckedNoTracing(name, userType, flags, parentId,
3075 preCreate, disallowedPackages, t);
Felipe Lemec1ca4412019-09-11 09:23:26 -07003076 } finally {
3077 t.traceEnd();
3078 }
jovanakdd7e4752019-09-04 12:35:45 -07003079 }
3080
Felipe Lemec1ca4412019-09-11 09:23:26 -07003081 private UserInfo createUserInternalUncheckedNoTracing(@Nullable String name,
Bookatz029832a2019-10-04 16:50:22 -07003082 @NonNull String userType, @UserInfoFlag int flags, @UserIdInt int parentId,
3083 boolean preCreate, @Nullable String[] disallowedPackages,
3084 @NonNull TimingsTraceAndSlog t) {
3085
3086 final UserTypeDetails userTypeDetails = mUserTypes.get(userType);
3087 if (userTypeDetails == null) {
3088 Slog.e(LOG_TAG, "Cannot create user of invalid user type: " + userType);
3089 return null;
3090 }
3091 userType = userType.intern(); // Now that we know it's valid, we can intern it.
3092 flags |= userTypeDetails.getDefaultUserInfoFlags();
3093 if (!checkUserTypeConsistency(flags)) {
3094 Slog.e(LOG_TAG, "Cannot add user. Flags (" + Integer.toHexString(flags)
3095 + ") and userTypeDetails (" + userType + ") are inconsistent.");
3096 return null;
3097 }
3098 if ((flags & UserInfo.FLAG_SYSTEM) != 0) {
3099 Slog.e(LOG_TAG, "Cannot add user. Flags (" + Integer.toHexString(flags)
3100 + ") indicated SYSTEM user, which cannot be created.");
3101 return null;
3102 }
3103 synchronized (mUsersLock) {
3104 if (mForceEphemeralUsers) {
3105 flags |= UserInfo.FLAG_EPHEMERAL;
3106 }
3107 }
Felipe Lemec1ca4412019-09-11 09:23:26 -07003108
Bookatz8ae87ea2019-11-26 12:00:19 -08003109 // Try to use a pre-created user (if available).
3110 if (!preCreate && parentId < 0 && isUserTypeEligibleForPreCreation(userTypeDetails)) {
3111 final UserInfo preCreatedUser = convertPreCreatedUserIfPossible(userType, flags, name);
3112 if (preCreatedUser != null) {
3113 return preCreatedUser;
Felipe Lemec1ca4412019-09-11 09:23:26 -07003114 }
3115 }
3116
Suprabh Shuklac5e057c2016-08-08 16:22:44 -07003117 DeviceStorageMonitorInternal dsm = LocalServices
3118 .getService(DeviceStorageMonitorInternal.class);
3119 if (dsm.isMemoryLow()) {
3120 Log.w(LOG_TAG, "Cannot add user. Not enough space on disk.");
3121 return null;
3122 }
jovanakdd7e4752019-09-04 12:35:45 -07003123
Bookatz029832a2019-10-04 16:50:22 -07003124 final boolean isProfile = userTypeDetails.isProfile();
3125 final boolean isGuest = UserManager.isUserTypeGuest(userType);
3126 final boolean isRestricted = UserManager.isUserTypeRestricted(userType);
3127 final boolean isDemo = UserManager.isUserTypeDemo(userType);
3128
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07003129 final long ident = Binder.clearCallingIdentity();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003130 UserInfo userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08003131 UserData userData;
Amith Yamasanibb054c92015-07-09 14:16:27 -07003132 final int userId;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07003133 try {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003134 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08003135 UserData parent = null;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003136 if (parentId != UserHandle.USER_NULL) {
3137 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08003138 parent = getUserDataLU(parentId);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00003139 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003140 if (parent == null) return null;
3141 }
Bookatz029832a2019-10-04 16:50:22 -07003142 if (!preCreate && !canAddMoreUsersOfType(userTypeDetails)) {
3143 Log.e(LOG_TAG, "Cannot add more users of type " + userType
3144 + ". Maximum number of that type already exists.");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003145 return null;
3146 }
Bookatz029832a2019-10-04 16:50:22 -07003147 // TODO(b/142482943): Perhaps let the following code apply to restricted users too.
3148 if (isProfile && !canAddMoreProfilesToUser(userType, parentId, false)) {
3149 Log.e(LOG_TAG, "Cannot add more profiles of type " + userType
3150 + " for user " + parentId);
3151 return null;
3152 }
3153 if (!isGuest && !isProfile && !isDemo && isUserLimitReached()) {
3154 // If we're not adding a guest/demo user or a profile and the 'user limit' has
3155 // been reached, cannot add a user.
jovanaka6763a32018-12-03 17:23:20 -08003156 Log.e(LOG_TAG, "Cannot add user. Maximum user limit is reached.");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003157 return null;
3158 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003159 // In legacy mode, restricted profile's parent can only be the owner user
3160 if (isRestricted && !UserManager.isSplitSystemUser()
3161 && (parentId != UserHandle.USER_SYSTEM)) {
3162 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
3163 return null;
3164 }
3165 if (isRestricted && UserManager.isSplitSystemUser()) {
3166 if (parent == null) {
3167 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be "
3168 + "specified");
Nicolas Prevot12678a92015-05-13 12:15:03 -07003169 return null;
3170 }
Amith Yamasani12747872015-12-07 14:19:49 -08003171 if (!parent.info.canHaveProfile()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003172 Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be "
3173 + "created for the specified parent user id " + parentId);
Amith Yamasani95ab7842014-08-11 17:09:26 -07003174 return null;
3175 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003176 }
Ying Zheng215116f2019-09-11 12:50:09 -07003177
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01003178 userId = getNextAvailableId();
3179 Environment.getUserSystemDirectory(userId).mkdirs();
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01003180
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003181 synchronized (mUsersLock) {
Bookatz029832a2019-10-04 16:50:22 -07003182 // Inherit ephemeral flag from parent.
3183 if (parent != null && parent.info.isEphemeral()) {
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01003184 flags |= UserInfo.FLAG_EPHEMERAL;
3185 }
3186
Bookatz029832a2019-10-04 16:50:22 -07003187 userInfo = new UserInfo(userId, name, null, flags, userType);
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01003188 userInfo.serialNumber = mNextSerialNumber++;
Felipe Lemec1ca4412019-09-11 09:23:26 -07003189 userInfo.creationTime = getCreationTime();
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01003190 userInfo.partial = true;
Felipe Lemec1ca4412019-09-11 09:23:26 -07003191 userInfo.preCreated = preCreate;
Fyodor Kupolov83c24242016-03-31 13:30:42 -07003192 userInfo.lastLoggedInFingerprint = Build.FINGERPRINT;
Bookatz029832a2019-10-04 16:50:22 -07003193 if (userTypeDetails.hasBadge() && parentId != UserHandle.USER_NULL) {
3194 userInfo.profileBadge = getFreeProfileBadgeLU(parentId, userType);
Kenny Guy02c89902016-11-15 19:36:38 +00003195 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01003196 userData = new UserData();
3197 userData.info = userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08003198 mUsers.put(userId, userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003199 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06003200 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003201 writeUserListLP();
3202 if (parent != null) {
Bookatz029832a2019-10-04 16:50:22 -07003203 if (isProfile) {
Amith Yamasani12747872015-12-07 14:19:49 -08003204 if (parent.info.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
3205 parent.info.profileGroupId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003206 writeUserLP(parent);
Kenny Guya52dc3e2014-02-11 15:33:14 +00003207 }
Amith Yamasani12747872015-12-07 14:19:49 -08003208 userInfo.profileGroupId = parent.info.profileGroupId;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003209 } else if (isRestricted) {
Amith Yamasani12747872015-12-07 14:19:49 -08003210 if (parent.info.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) {
3211 parent.info.restrictedProfileParentId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003212 writeUserLP(parent);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07003213 }
Amith Yamasani12747872015-12-07 14:19:49 -08003214 userInfo.restrictedProfileParentId = parent.info.restrictedProfileParentId;
Makoto Onuki068c54a2015-10-13 14:34:03 -07003215 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07003216 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07003217 }
jovanakdd7e4752019-09-04 12:35:45 -07003218
3219 t.traceBegin("createUserKey");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003220 final StorageManager storage = mContext.getSystemService(StorageManager.class);
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01003221 storage.createUserKey(userId, userInfo.serialNumber, userInfo.isEphemeral());
jovanakdd7e4752019-09-04 12:35:45 -07003222 t.traceEnd();
3223
3224 t.traceBegin("prepareUserData");
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -08003225 mUserDataPreparer.prepareUserData(userId, userInfo.serialNumber,
Jeff Sharkey47f71082016-02-01 17:03:54 -07003226 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
jovanakdd7e4752019-09-04 12:35:45 -07003227 t.traceEnd();
3228
Bookatza8c2d2a2019-11-13 10:10:18 -08003229 final Set<String> installablePackages =
3230 mSystemPackageInstaller.getInstallablePackagesForUserType(userType);
jovanakdd7e4752019-09-04 12:35:45 -07003231 t.traceBegin("PM.createNewUser");
Bookatz04d7ae52019-08-05 14:07:12 -07003232 mPm.createNewUser(userId, installablePackages, disallowedPackages);
jovanakdd7e4752019-09-04 12:35:45 -07003233 t.traceEnd();
3234
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003235 userInfo.partial = false;
3236 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08003237 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003238 }
3239 updateUserIds();
3240 Bundle restrictions = new Bundle();
Bookatz029832a2019-10-04 16:50:22 -07003241 // TODO(b/142482943): Generalize this using UserTypeDetails default restrictions.
Fyodor Kupolove04462c2015-11-30 15:02:53 -08003242 if (isGuest) {
3243 synchronized (mGuestRestrictions) {
3244 restrictions.putAll(mGuestRestrictions);
3245 }
3246 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003247 synchronized (mRestrictionsLock) {
3248 mBaseUserRestrictions.append(userId, restrictions);
3249 }
jovanakdd7e4752019-09-04 12:35:45 -07003250
3251 t.traceBegin("PM.onNewUserCreated");
Fyodor Kupolov5fd967d2016-07-12 14:46:19 -07003252 mPm.onNewUserCreated(userId);
jovanakdd7e4752019-09-04 12:35:45 -07003253
Felipe Lemec1ca4412019-09-11 09:23:26 -07003254 if (preCreate) {
3255 // Must start user (which will be stopped right away, through
3256 // UserController.finishUserUnlockedCompleted) so services can properly
3257 // intialize it.
Felipe Lemec6e015d2019-10-21 12:51:08 -07003258 // TODO(b/143092698): in the long-term, it might be better to add a onCreateUser()
3259 // callback on SystemService instead.
Felipe Lemec1ca4412019-09-11 09:23:26 -07003260 Slog.i(LOG_TAG, "starting pre-created user " + userInfo.toFullString());
3261 final IActivityManager am = ActivityManager.getService();
3262 try {
3263 am.startUserInBackground(userId);
3264 } catch (RemoteException e) {
3265 Slog.w(LOG_TAG, "could not start pre-created user " + userId, e);
3266 }
3267 } else {
3268 dispatchUserAddedIntent(userInfo);
3269 }
3270
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07003271 } finally {
3272 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07003273 }
Felipe Lemec1ca4412019-09-11 09:23:26 -07003274
Felipe Lemec6e015d2019-10-21 12:51:08 -07003275 // TODO(b/143092698): it's possible to reach "max users overflow" when the user is created
Felipe Lemec1ca4412019-09-11 09:23:26 -07003276 // "from scratch" (i.e., not from a pre-created user) and reaches the maximum number of
3277 // users without counting the pre-created one. Then when the pre-created is converted, the
3278 // "effective" number of max users is exceeds. Example:
3279 // Max: 3 Current: 2 full (u0 and u10) + 1 pre-created (u11)
3280 // Step 1: create(/* flags doesn't match u11 */): u12 is created, "effective max" is now 3
3281 // (u0, u10, u12) but "real" max is 4 (u0, u10, u11, u12)
3282 // Step 2: create(/* flags match u11 */): u11 is converted, now "effective max" is also 4
3283 // (u0, u10, u11, u12)
3284 // One way to avoid this issue is by removing a pre-created user from the pool when the
3285 // "real" max exceeds the max here.
3286
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003287 return userInfo;
3288 }
3289
Bookatz8ae87ea2019-11-26 12:00:19 -08003290 /**
3291 * Finds and converts a previously pre-created user into a regular user, if possible.
3292 *
3293 * @return the converted user, or {@code null} if no pre-created user could be converted.
3294 */
3295 private @Nullable UserInfo convertPreCreatedUserIfPossible(String userType,
3296 @UserInfoFlag int flags, String name) {
3297 final UserData preCreatedUserData;
3298 synchronized (mUsersLock) {
3299 preCreatedUserData = getPreCreatedUserLU(userType);
3300 }
3301 if (preCreatedUserData == null) {
3302 return null;
3303 }
3304 final UserInfo preCreatedUser = preCreatedUserData.info;
3305 final int newFlags = preCreatedUser.flags | flags;
3306 if (!checkUserTypeConsistency(newFlags)) {
3307 Slog.wtf(LOG_TAG, "Cannot reuse pre-created user " + preCreatedUser.id
3308 + " of type " + userType + " because flags are inconsistent. "
3309 + "Flags (" + Integer.toHexString(flags) + "); preCreatedUserFlags ( "
3310 + Integer.toHexString(preCreatedUser.flags) + ").");
3311 return null;
3312 }
3313 Log.i(LOG_TAG, "Reusing pre-created user " + preCreatedUser.id + " of type "
3314 + userType + " and bestowing on it flags " + UserInfo.flagsToString(flags));
3315 preCreatedUser.name = name;
3316 preCreatedUser.flags = newFlags;
3317 preCreatedUser.preCreated = false;
3318 preCreatedUser.creationTime = getCreationTime();
3319
3320 dispatchUserAddedIntent(preCreatedUser);
3321 synchronized (mPackagesLock) {
3322 writeUserLP(preCreatedUserData);
3323 writeUserListLP();
3324 }
3325 return preCreatedUser;
3326 }
3327
Bookatz029832a2019-10-04 16:50:22 -07003328 /** Checks that the flags do not contain mutually exclusive types/properties. */
3329 static boolean checkUserTypeConsistency(@UserInfoFlag int flags) {
3330 // Mask to check that flags don't refer to multiple user types.
3331 final int userTypeFlagMask = UserInfo.FLAG_GUEST | UserInfo.FLAG_DEMO
3332 | UserInfo.FLAG_RESTRICTED | UserInfo.FLAG_PROFILE;
3333 return isAtMostOneFlag(flags & userTypeFlagMask)
3334 && isAtMostOneFlag(flags & (UserInfo.FLAG_PROFILE | UserInfo.FLAG_FULL))
3335 && isAtMostOneFlag(flags & (UserInfo.FLAG_PROFILE | UserInfo.FLAG_SYSTEM));
3336 }
3337
3338 /** Returns whether the given flags contains at most one 1. */
3339 private static boolean isAtMostOneFlag(int flags) {
3340 return (flags & (flags - 1)) == 0;
3341 // If !=0, this means that flags is not a power of 2, and therefore is multiple types.
3342 }
3343
Bookatz04d7ae52019-08-05 14:07:12 -07003344 /** Install/uninstall system packages for all users based on their user-type, as applicable. */
3345 boolean installWhitelistedSystemPackages(boolean isFirstBoot, boolean isUpgrade) {
3346 return mSystemPackageInstaller.installWhitelistedSystemPackages(isFirstBoot, isUpgrade);
3347 }
3348
Felipe Lemec1ca4412019-09-11 09:23:26 -07003349 private long getCreationTime() {
3350 final long now = System.currentTimeMillis();
3351 return (now > EPOCH_PLUS_30_YEARS) ? now : 0;
3352 }
3353
3354 private void dispatchUserAddedIntent(@NonNull UserInfo userInfo) {
3355 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
3356 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userInfo.id);
3357 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
3358 android.Manifest.permission.MANAGE_USERS);
3359 MetricsLogger.count(mContext, userInfo.isGuest() ? TRON_GUEST_CREATED
3360 : (userInfo.isDemo() ? TRON_DEMO_CREATED : TRON_USER_CREATED), 1);
3361 }
3362
Felipe Lemec1ca4412019-09-11 09:23:26 -07003363 /**
Bookatz029832a2019-10-04 16:50:22 -07003364 * Gets a pre-created user for the given user type.
Felipe Lemec1ca4412019-09-11 09:23:26 -07003365 *
3366 * <p>Should be used only during user creation, so the pre-created user can be used (instead of
3367 * creating and initializing a new user from scratch).
3368 */
Felipe Lemec6e015d2019-10-21 12:51:08 -07003369 // TODO(b/143092698): add unit test
Felipe Lemec1ca4412019-09-11 09:23:26 -07003370 @GuardedBy("mUsersLock")
Bookatz029832a2019-10-04 16:50:22 -07003371 private @Nullable UserData getPreCreatedUserLU(String userType) {
3372 if (DBG) Slog.d(LOG_TAG, "getPreCreatedUser(): userType= " + userType);
Felipe Lemec1ca4412019-09-11 09:23:26 -07003373 final int userSize = mUsers.size();
3374 for (int i = 0; i < userSize; i++) {
3375 final UserData user = mUsers.valueAt(i);
3376 if (DBG) Slog.d(LOG_TAG, i + ":" + user.info.toFullString());
Bookatz029832a2019-10-04 16:50:22 -07003377 if (user.info.preCreated && user.info.userType.equals(userType)) {
Felipe Lemec1ca4412019-09-11 09:23:26 -07003378 if (!user.info.isInitialized()) {
Bookatz029832a2019-10-04 16:50:22 -07003379 Slog.w(LOG_TAG, "found pre-created user of type " + userType
Felipe Lemec1ca4412019-09-11 09:23:26 -07003380 + ", but it's not initialized yet: " + user.info.toFullString());
3381 continue;
3382 }
3383 return user;
3384 }
3385 }
3386 return null;
3387 }
3388
Bookatz029832a2019-10-04 16:50:22 -07003389 /**
3390 * Returns whether a user with the given userTypeDetails is eligible to be
3391 * {@link UserInfo#preCreated}.
3392 */
3393 private static boolean isUserTypeEligibleForPreCreation(UserTypeDetails userTypeDetails) {
3394 if (userTypeDetails == null) {
3395 return false;
3396 }
3397 return !userTypeDetails.isProfile()
3398 && !userTypeDetails.getName().equals(UserManager.USER_TYPE_FULL_RESTRICTED);
3399 }
3400
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003401 @VisibleForTesting
3402 UserData putUserInfo(UserInfo userInfo) {
3403 final UserData userData = new UserData();
3404 userData.info = userInfo;
3405 synchronized (mUsers) {
3406 mUsers.put(userInfo.id, userData);
3407 }
3408 return userData;
3409 }
3410
3411 @VisibleForTesting
Bookatzf56f2582019-09-04 16:06:41 -07003412 void removeUserInfo(@UserIdInt int userId) {
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003413 synchronized (mUsers) {
3414 mUsers.remove(userId);
3415 }
3416 }
3417
Amith Yamasani0b285492011-04-14 17:35:23 -07003418 /**
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003419 * @hide
3420 */
Amith Yamasani12747872015-12-07 14:19:49 -08003421 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003422 public UserInfo createRestrictedProfile(String name, int parentUserId) {
Sudheer Shanka53d41472016-06-16 09:11:08 -07003423 checkManageOrCreateUsersPermission("setupRestrictedProfile");
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07003424 final UserInfo user = createProfileForUser(
Bookatz029832a2019-10-04 16:50:22 -07003425 name, UserManager.USER_TYPE_FULL_RESTRICTED, 0, parentUserId, null);
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003426 if (user == null) {
3427 return null;
3428 }
Fyodor Kupolov9e912ba2016-02-09 18:29:43 -08003429 long identity = Binder.clearCallingIdentity();
3430 try {
3431 setUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, true, user.id);
3432 // Change the setting before applying the DISALLOW_SHARE_LOCATION restriction, otherwise
3433 // the putIntForUser() will fail.
3434 android.provider.Settings.Secure.putIntForUser(mContext.getContentResolver(),
3435 android.provider.Settings.Secure.LOCATION_MODE,
3436 android.provider.Settings.Secure.LOCATION_MODE_OFF, user.id);
3437 setUserRestriction(UserManager.DISALLOW_SHARE_LOCATION, true, user.id);
3438 } finally {
3439 Binder.restoreCallingIdentity(identity);
3440 }
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003441 return user;
3442 }
3443
3444 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07003445 * Find the current guest user. If the Guest user is partial,
3446 * then do not include it in the results as it is about to die.
Adam Lesinskieddeb492014-09-08 17:50:03 -07003447 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07003448 private UserInfo findCurrentGuestUser() {
3449 synchronized (mUsersLock) {
3450 final int size = mUsers.size();
3451 for (int i = 0; i < size; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003452 final UserInfo user = mUsers.valueAt(i).info;
Felipe Lemee35f5b02019-10-14 15:37:44 -07003453 if (user.isGuest() && !user.guestToRemove && !user.preCreated
3454 && !mRemovingUserIds.get(user.id)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003455 return user;
3456 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07003457 }
3458 }
3459 return null;
3460 }
3461
3462 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07003463 * Mark this guest user for deletion to allow us to create another guest
3464 * and switch to that user before actually removing this guest.
Bookatzf56f2582019-09-04 16:06:41 -07003465 * @param userId the userid of the current guest
Amith Yamasani1df14732014-08-29 21:37:27 -07003466 * @return whether the user could be marked for deletion
3467 */
Amith Yamasani12747872015-12-07 14:19:49 -08003468 @Override
Bookatzf56f2582019-09-04 16:06:41 -07003469 public boolean markGuestForDeletion(@UserIdInt int userId) {
Amith Yamasani1df14732014-08-29 21:37:27 -07003470 checkManageUsersPermission("Only the system can remove users");
3471 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
3472 UserManager.DISALLOW_REMOVE_USER, false)) {
3473 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
3474 return false;
3475 }
3476
3477 long ident = Binder.clearCallingIdentity();
3478 try {
Amith Yamasani12747872015-12-07 14:19:49 -08003479 final UserData userData;
Amith Yamasani1df14732014-08-29 21:37:27 -07003480 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003481 synchronized (mUsersLock) {
Bookatzf56f2582019-09-04 16:06:41 -07003482 userData = mUsers.get(userId);
3483 if (userId == 0 || userData == null || mRemovingUserIds.get(userId)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003484 return false;
3485 }
Amith Yamasani1df14732014-08-29 21:37:27 -07003486 }
Amith Yamasani12747872015-12-07 14:19:49 -08003487 if (!userData.info.isGuest()) {
Amith Yamasani1df14732014-08-29 21:37:27 -07003488 return false;
3489 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07003490 // We set this to a guest user that is to be removed. This is a temporary state
3491 // where we are allowed to add new Guest users, even if this one is still not
3492 // removed. This user will still show up in getUserInfo() calls.
3493 // If we don't get around to removing this Guest user, it will be purged on next
3494 // startup.
Amith Yamasani12747872015-12-07 14:19:49 -08003495 userData.info.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07003496 // Mark it as disabled, so that it isn't returned any more when
3497 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08003498 userData.info.flags |= UserInfo.FLAG_DISABLED;
3499 writeUserLP(userData);
Amith Yamasani1df14732014-08-29 21:37:27 -07003500 }
3501 } finally {
3502 Binder.restoreCallingIdentity(ident);
3503 }
3504 return true;
3505 }
3506
3507 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07003508 * Removes a user and all data directories created for that user. This method should be called
3509 * after the user's processes have been terminated.
Bookatzf56f2582019-09-04 16:06:41 -07003510 * @param userId the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07003511 */
Amith Yamasani12747872015-12-07 14:19:49 -08003512 @Override
Bookatzf56f2582019-09-04 16:06:41 -07003513 public boolean removeUser(@UserIdInt int userId) {
3514 Slog.i(LOG_TAG, "removeUser u" + userId);
Sudheer Shankaf5cea032016-06-08 17:13:24 -07003515 checkManageOrCreateUsersPermission("Only the system can remove users");
Esteban Talavera6c9116a2016-11-24 16:12:44 +00003516
3517 final boolean isManagedProfile;
3518 synchronized (mUsersLock) {
Bookatzf56f2582019-09-04 16:06:41 -07003519 UserInfo userInfo = getUserInfoLU(userId);
Esteban Talavera6c9116a2016-11-24 16:12:44 +00003520 isManagedProfile = userInfo != null && userInfo.isManagedProfile();
3521 }
3522 String restriction = isManagedProfile
3523 ? UserManager.DISALLOW_REMOVE_MANAGED_PROFILE : UserManager.DISALLOW_REMOVE_USER;
3524 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(restriction, false)) {
3525 Log.w(LOG_TAG, "Cannot remove user. " + restriction + " is enabled.");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04003526 return false;
3527 }
Bookatzf56f2582019-09-04 16:06:41 -07003528 return removeUserUnchecked(userId);
Nicolas Prevotdf1b87d2016-10-25 13:57:08 +01003529 }
Julia Reynolds4ac5f852014-06-23 17:38:51 -04003530
Bookatz029832a2019-10-04 16:50:22 -07003531 @Override
3532 public boolean removeUserEvenWhenDisallowed(@UserIdInt int userId) {
3533 checkManageOrCreateUsersPermission("Only the system can remove users");
3534 return removeUserUnchecked(userId);
3535 }
3536
Bookatzf56f2582019-09-04 16:06:41 -07003537 private boolean removeUserUnchecked(@UserIdInt int userId) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01003538 long ident = Binder.clearCallingIdentity();
3539 try {
Amith Yamasani12747872015-12-07 14:19:49 -08003540 final UserData userData;
Fyodor Kupolov0df68cd2015-10-01 13:54:22 -07003541 int currentUser = ActivityManager.getCurrentUser();
Bookatzf56f2582019-09-04 16:06:41 -07003542 if (currentUser == userId) {
jovanaka6763a32018-12-03 17:23:20 -08003543 Log.w(LOG_TAG, "Current user cannot be removed.");
Fyodor Kupolov0df68cd2015-10-01 13:54:22 -07003544 return false;
3545 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01003546 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003547 synchronized (mUsersLock) {
Bookatzf56f2582019-09-04 16:06:41 -07003548 userData = mUsers.get(userId);
3549 if (userId == UserHandle.USER_SYSTEM) {
jovanaka6763a32018-12-03 17:23:20 -08003550 Log.e(LOG_TAG, "System user cannot be removed.");
3551 return false;
3552 }
3553
3554 if (userData == null) {
3555 Log.e(LOG_TAG, String.format(
Bookatzf56f2582019-09-04 16:06:41 -07003556 "Cannot remove user %d, invalid user id provided.", userId));
jovanaka6763a32018-12-03 17:23:20 -08003557 return false;
3558 }
3559
Bookatzf56f2582019-09-04 16:06:41 -07003560 if (mRemovingUserIds.get(userId)) {
jovanaka6763a32018-12-03 17:23:20 -08003561 Log.e(LOG_TAG, String.format(
Bookatzf56f2582019-09-04 16:06:41 -07003562 "User %d is already scheduled for removal.", userId));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003563 return false;
3564 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08003565
Bookatzf56f2582019-09-04 16:06:41 -07003566 addRemovingUserIdLocked(userId);
Fyodor Kupolov82402752015-10-28 14:54:51 -07003567 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08003568
Kenny Guyee58b4f2014-05-23 15:19:53 +01003569 // Set this to a partially created user, so that the user will be purged
3570 // on next startup, in case the runtime stops now before stopping and
3571 // removing the user completely.
Amith Yamasani12747872015-12-07 14:19:49 -08003572 userData.info.partial = true;
Kenny Guyee58b4f2014-05-23 15:19:53 +01003573 // Mark it as disabled, so that it isn't returned any more when
3574 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08003575 userData.info.flags |= UserInfo.FLAG_DISABLED;
3576 writeUserLP(userData);
Kenny Guyee58b4f2014-05-23 15:19:53 +01003577 }
Fyodor Kupolov6c96f7f2017-06-28 18:22:59 -07003578 try {
Bookatzf56f2582019-09-04 16:06:41 -07003579 mAppOpsService.removeUser(userId);
Fyodor Kupolov6c96f7f2017-06-28 18:22:59 -07003580 } catch (RemoteException e) {
jovanaka6763a32018-12-03 17:23:20 -08003581 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user.", e);
Fyodor Kupolov6c96f7f2017-06-28 18:22:59 -07003582 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01003583
Bookatz029832a2019-10-04 16:50:22 -07003584 // TODO(b/142482943): Send some sort of broadcast for profiles even if non-managed?
Amith Yamasani12747872015-12-07 14:19:49 -08003585 if (userData.info.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
3586 && userData.info.isManagedProfile()) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01003587 // Send broadcast to notify system that the user removed was a
3588 // managed user.
Amith Yamasani12747872015-12-07 14:19:49 -08003589 sendProfileRemovedBroadcast(userData.info.profileGroupId, userData.info.id);
Kenny Guyee58b4f2014-05-23 15:19:53 +01003590 }
3591
Bookatzf56f2582019-09-04 16:06:41 -07003592 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userId);
Kenny Guyee58b4f2014-05-23 15:19:53 +01003593 int res;
3594 try {
Bookatzf56f2582019-09-04 16:06:41 -07003595 res = ActivityManager.getService().stopUser(userId, /* force= */ true,
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07003596 new IStopUserCallback.Stub() {
Kenny Guyee58b4f2014-05-23 15:19:53 +01003597 @Override
Bookatzf56f2582019-09-04 16:06:41 -07003598 public void userStopped(int userIdParam) {
3599 finishRemoveUser(userIdParam);
Kenny Guyee58b4f2014-05-23 15:19:53 +01003600 }
3601 @Override
Bookatzf56f2582019-09-04 16:06:41 -07003602 public void userStopAborted(int userIdParam) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01003603 }
3604 });
3605 } catch (RemoteException e) {
jovanaka6763a32018-12-03 17:23:20 -08003606 Log.w(LOG_TAG, "Failed to stop user during removal.", e);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003607 return false;
3608 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01003609 return res == ActivityManager.USER_OP_SUCCESS;
3610 } finally {
3611 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003612 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003613 }
3614
Andreas Gampea36dc622018-02-05 17:19:22 -08003615 @GuardedBy("mUsersLock")
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003616 @VisibleForTesting
Bookatzf56f2582019-09-04 16:06:41 -07003617 void addRemovingUserIdLocked(@UserIdInt int userId) {
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003618 // We remember deleted user IDs to prevent them from being
3619 // reused during the current boot; they can still be reused
3620 // after a reboot or recycling of userIds.
3621 mRemovingUserIds.put(userId, true);
3622 mRecentlyRemovedIds.add(userId);
3623 // Keep LRU queue of recently removed IDs for recycling
3624 if (mRecentlyRemovedIds.size() > MAX_RECENTLY_REMOVED_IDS_SIZE) {
3625 mRecentlyRemovedIds.removeFirst();
3626 }
3627 }
3628
Bookatzf56f2582019-09-04 16:06:41 -07003629 void finishRemoveUser(final @UserIdInt int userId) {
3630 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userId);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07003631 // Let other services shutdown any activity and clean up their state before completely
3632 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07003633 long ident = Binder.clearCallingIdentity();
3634 try {
3635 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
Bookatzf56f2582019-09-04 16:06:41 -07003636 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07003637 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
3638 android.Manifest.permission.MANAGE_USERS,
3639
3640 new BroadcastReceiver() {
3641 @Override
3642 public void onReceive(Context context, Intent intent) {
3643 if (DBG) {
3644 Slog.i(LOG_TAG,
3645 "USER_REMOVED broadcast sent, cleaning up user data "
Bookatzf56f2582019-09-04 16:06:41 -07003646 + userId);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07003647 }
3648 new Thread() {
Amith Yamasani12747872015-12-07 14:19:49 -08003649 @Override
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07003650 public void run() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003651 // Clean up any ActivityTaskManager state
3652 LocalServices.getService(ActivityTaskManagerInternal.class)
Bookatzf56f2582019-09-04 16:06:41 -07003653 .onUserStopped(userId);
3654 removeUserState(userId);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07003655 }
3656 }.start();
3657 }
3658 },
3659
3660 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07003661 } finally {
3662 Binder.restoreCallingIdentity(ident);
3663 }
Amith Yamasani2a003292012-08-14 18:25:45 -07003664 }
3665
Bookatzf56f2582019-09-04 16:06:41 -07003666 private void removeUserState(final @UserIdInt int userId) {
Paul Crowley91293792016-03-25 15:23:07 -07003667 try {
Bookatzf56f2582019-09-04 16:06:41 -07003668 mContext.getSystemService(StorageManager.class).destroyUserKey(userId);
Paul Crowley91293792016-03-25 15:23:07 -07003669 } catch (IllegalStateException e) {
3670 // This may be simply because the user was partially created.
Bookatzf56f2582019-09-04 16:06:41 -07003671 Slog.i(LOG_TAG, "Destroying key for user " + userId + " failed, continuing anyway", e);
Paul Crowley91293792016-03-25 15:23:07 -07003672 }
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06003673
Amith Yamasanid04aaa32016-06-13 12:09:36 -07003674 // Cleanup gatekeeper secure user id
3675 try {
3676 final IGateKeeperService gk = GateKeeper.getService();
3677 if (gk != null) {
Bookatzf56f2582019-09-04 16:06:41 -07003678 gk.clearSecureUserId(userId);
Amith Yamasanid04aaa32016-06-13 12:09:36 -07003679 }
3680 } catch (Exception ex) {
3681 Slog.w(LOG_TAG, "unable to clear GK secure user id");
3682 }
3683
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003684 // Cleanup package manager settings
Bookatzf56f2582019-09-04 16:06:41 -07003685 mPm.cleanUpUser(this, userId);
Amith Yamasanid04aaa32016-06-13 12:09:36 -07003686
3687 // Clean up all data before removing metadata
Bookatzf56f2582019-09-04 16:06:41 -07003688 mUserDataPreparer.destroyUserData(userId,
Amith Yamasanid04aaa32016-06-13 12:09:36 -07003689 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
3690
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003691 // Remove this user from the list
Fyodor Kupolov82402752015-10-28 14:54:51 -07003692 synchronized (mUsersLock) {
Bookatzf56f2582019-09-04 16:06:41 -07003693 mUsers.remove(userId);
3694 mIsUserManaged.delete(userId);
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003695 }
3696 synchronized (mUserStates) {
Bookatzf56f2582019-09-04 16:06:41 -07003697 mUserStates.delete(userId);
Makoto Onukie7927da2015-11-25 10:05:17 -08003698 }
3699 synchronized (mRestrictionsLock) {
Bookatzf56f2582019-09-04 16:06:41 -07003700 mBaseUserRestrictions.remove(userId);
3701 mAppliedUserRestrictions.remove(userId);
3702 mCachedEffectiveUserRestrictions.remove(userId);
3703 mDevicePolicyLocalUserRestrictions.remove(userId);
3704 if (mDevicePolicyGlobalUserRestrictions.get(userId) != null) {
3705 mDevicePolicyGlobalUserRestrictions.remove(userId);
Pavel Grafov6a40f092016-10-25 15:46:51 +01003706 applyUserRestrictionsForAllUsersLR();
3707 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07003708 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003709 // Update the user list
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003710 synchronized (mPackagesLock) {
3711 writeUserListLP();
3712 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06003713 // Remove user file
Bookatzf56f2582019-09-04 16:06:41 -07003714 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userId + XML_SUFFIX));
Jeff Sharkeycd575992016-03-29 14:12:49 -06003715 userFile.delete();
Fyodor Kupolov82402752015-10-28 14:54:51 -07003716 updateUserIds();
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003717 if (RELEASE_DELETED_USER_ID) {
3718 synchronized (mUsers) {
Bookatzf56f2582019-09-04 16:06:41 -07003719 mRemovingUserIds.delete(userId);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003720 }
3721 }
Amith Yamasani61f57372012-08-31 12:12:28 -07003722 }
3723
Kenny Guyf8d3a232014-05-15 16:09:52 +01003724 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01003725 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01003726 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
3727 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01003728 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
Jeff Sharkeyaf6ec292015-12-17 11:19:00 -07003729 managedProfileIntent.putExtra(Intent.EXTRA_USER_HANDLE, removedUserId);
Kenny Guyf8d3a232014-05-15 16:09:52 +01003730 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01003731 }
3732
Amith Yamasani2a003292012-08-14 18:25:45 -07003733 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07003734 public Bundle getApplicationRestrictions(String packageName) {
3735 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
3736 }
3737
3738 @Override
Bookatzf56f2582019-09-04 16:06:41 -07003739 public Bundle getApplicationRestrictionsForUser(String packageName, @UserIdInt int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003740 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07003741 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07003742 checkSystemOrRoot("get application restrictions for other user/app " + packageName);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003743 }
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003744 synchronized (mAppRestrictionsLock) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003745 // Read the restrictions from XML
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003746 return readApplicationRestrictionsLAr(packageName, userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003747 }
3748 }
3749
3750 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07003751 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Bookatzf56f2582019-09-04 16:06:41 -07003752 @UserIdInt int userId) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00003753 checkSystemOrRoot("set application restrictions");
Fyodor Kupolov0d88d542016-04-19 11:37:22 -07003754 if (restrictions != null) {
3755 restrictions.setDefusable(true);
3756 }
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003757 synchronized (mAppRestrictionsLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01003758 if (restrictions == null || restrictions.isEmpty()) {
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003759 cleanAppRestrictionsForPackageLAr(packageName, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01003760 } else {
3761 // Write the restrictions to XML
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003762 writeApplicationRestrictionsLAr(packageName, restrictions, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01003763 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003764 }
Robin Lee66e5d962014-04-09 16:44:21 +01003765
Fyodor Kupolovd2846122016-02-11 18:06:34 -08003766 // Notify package of changes via an intent - only sent to explicitly registered receivers.
3767 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
3768 changeIntent.setPackage(packageName);
3769 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3770 mContext.sendBroadcastAsUser(changeIntent, UserHandle.of(userId));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003771 }
3772
3773 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07003774 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003775 try {
3776 return mContext.getPackageManager().getApplicationInfo(packageName,
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07003777 PackageManager.MATCH_ANY_USER).uid;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003778 } catch (NameNotFoundException nnfe) {
3779 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07003780 } finally {
3781 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003782 }
3783 }
3784
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003785 @GuardedBy("mAppRestrictionsLock")
Bookatzf56f2582019-09-04 16:06:41 -07003786 private static Bundle readApplicationRestrictionsLAr(String packageName,
3787 @UserIdInt int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003788 AtomicFile restrictionsFile =
3789 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
3790 packageToRestrictionsFileName(packageName)));
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003791 return readApplicationRestrictionsLAr(restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003792 }
3793
3794 @VisibleForTesting
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003795 @GuardedBy("mAppRestrictionsLock")
3796 static Bundle readApplicationRestrictionsLAr(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07003797 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003798 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07003799 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07003800 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07003801 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003802
3803 FileInputStream fis = null;
3804 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003805 fis = restrictionsFile.openRead();
3806 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01003807 parser.setInput(fis, StandardCharsets.UTF_8.name());
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003808 XmlUtils.nextElement(parser);
3809 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003810 Slog.e(LOG_TAG, "Unable to read restrictions file "
3811 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07003812 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003813 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003814 while (parser.next() != XmlPullParser.END_DOCUMENT) {
3815 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003816 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003817 } catch (IOException|XmlPullParserException e) {
3818 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003819 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003820 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003821 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07003822 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003823 }
3824
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003825 private static void readEntry(Bundle restrictions, ArrayList<String> values,
3826 XmlPullParser parser) throws XmlPullParserException, IOException {
3827 int type = parser.getEventType();
3828 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
3829 String key = parser.getAttributeValue(null, ATTR_KEY);
3830 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
3831 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
3832 if (multiple != null) {
3833 values.clear();
3834 int count = Integer.parseInt(multiple);
3835 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
3836 if (type == XmlPullParser.START_TAG
3837 && parser.getName().equals(TAG_VALUE)) {
3838 values.add(parser.nextText().trim());
3839 count--;
3840 }
3841 }
3842 String [] valueStrings = new String[values.size()];
3843 values.toArray(valueStrings);
3844 restrictions.putStringArray(key, valueStrings);
3845 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
3846 restrictions.putBundle(key, readBundleEntry(parser, values));
3847 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
3848 final int outerDepth = parser.getDepth();
3849 ArrayList<Bundle> bundleList = new ArrayList<>();
3850 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
3851 Bundle childBundle = readBundleEntry(parser, values);
3852 bundleList.add(childBundle);
3853 }
3854 restrictions.putParcelableArray(key,
3855 bundleList.toArray(new Bundle[bundleList.size()]));
3856 } else {
3857 String value = parser.nextText().trim();
3858 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
3859 restrictions.putBoolean(key, Boolean.parseBoolean(value));
3860 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
3861 restrictions.putInt(key, Integer.parseInt(value));
3862 } else {
3863 restrictions.putString(key, value);
3864 }
3865 }
3866 }
3867 }
3868
3869 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
3870 throws IOException, XmlPullParserException {
3871 Bundle childBundle = new Bundle();
3872 final int outerDepth = parser.getDepth();
3873 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
3874 readEntry(childBundle, values, parser);
3875 }
3876 return childBundle;
3877 }
3878
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003879 @GuardedBy("mAppRestrictionsLock")
3880 private static void writeApplicationRestrictionsLAr(String packageName,
Bookatzf56f2582019-09-04 16:06:41 -07003881 Bundle restrictions, @UserIdInt int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003882 AtomicFile restrictionsFile = new AtomicFile(
3883 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07003884 packageToRestrictionsFileName(packageName)));
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003885 writeApplicationRestrictionsLAr(restrictions, restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003886 }
3887
3888 @VisibleForTesting
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003889 @GuardedBy("mAppRestrictionsLock")
3890 static void writeApplicationRestrictionsLAr(Bundle restrictions, AtomicFile restrictionsFile) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003891 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003892 try {
3893 fos = restrictionsFile.startWrite();
3894 final BufferedOutputStream bos = new BufferedOutputStream(fos);
3895
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003896 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01003897 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003898 serializer.startDocument(null, true);
3899 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
3900
3901 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003902 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003903 serializer.endTag(null, TAG_RESTRICTIONS);
3904
3905 serializer.endDocument();
3906 restrictionsFile.finishWrite(fos);
3907 } catch (Exception e) {
3908 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003909 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
3910 }
3911 }
3912
3913 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
3914 throws IOException {
3915 for (String key : restrictions.keySet()) {
3916 Object value = restrictions.get(key);
3917 serializer.startTag(null, TAG_ENTRY);
3918 serializer.attribute(null, ATTR_KEY, key);
3919
3920 if (value instanceof Boolean) {
3921 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
3922 serializer.text(value.toString());
3923 } else if (value instanceof Integer) {
3924 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
3925 serializer.text(value.toString());
3926 } else if (value == null || value instanceof String) {
3927 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
3928 serializer.text(value != null ? (String) value : "");
3929 } else if (value instanceof Bundle) {
3930 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
3931 writeBundle((Bundle) value, serializer);
3932 } else if (value instanceof Parcelable[]) {
3933 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
3934 Parcelable[] array = (Parcelable[]) value;
3935 for (Parcelable parcelable : array) {
3936 if (!(parcelable instanceof Bundle)) {
3937 throw new IllegalArgumentException("bundle-array can only hold Bundles");
3938 }
3939 serializer.startTag(null, TAG_ENTRY);
3940 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
3941 writeBundle((Bundle) parcelable, serializer);
3942 serializer.endTag(null, TAG_ENTRY);
3943 }
3944 } else {
3945 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
3946 String[] values = (String[]) value;
3947 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
3948 for (String choice : values) {
3949 serializer.startTag(null, TAG_VALUE);
3950 serializer.text(choice != null ? choice : "");
3951 serializer.endTag(null, TAG_VALUE);
3952 }
3953 }
3954 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003955 }
3956 }
3957
3958 @Override
Bookatzf56f2582019-09-04 16:06:41 -07003959 public int getUserSerialNumber(@UserIdInt int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003960 synchronized (mUsersLock) {
Bookatzf56f2582019-09-04 16:06:41 -07003961 final UserInfo userInfo = getUserInfoLU(userId);
Pavel Grafov9c295d42019-03-26 19:42:08 +00003962 return userInfo != null ? userInfo.serialNumber : -1;
Amith Yamasani2a003292012-08-14 18:25:45 -07003963 }
3964 }
3965
3966 @Override
Bookatzf56f2582019-09-04 16:06:41 -07003967 public boolean isUserNameSet(@UserIdInt int userId) {
Fyodor Kupolov605b12a2017-05-10 15:58:09 -07003968 synchronized (mUsersLock) {
Bookatzf56f2582019-09-04 16:06:41 -07003969 final UserInfo userInfo = getUserInfoLU(userId);
Fyodor Kupolov605b12a2017-05-10 15:58:09 -07003970 return userInfo != null && userInfo.name != null;
3971 }
3972 }
3973
3974 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07003975 public int getUserHandle(int userSerialNumber) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003976 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07003977 for (int userId : mUserIds) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003978 UserInfo info = getUserInfoLU(userId);
Kenny Guy945f8832015-02-10 15:17:26 +00003979 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07003980 }
3981 // Not found
3982 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07003983 }
3984 }
3985
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003986 @Override
Bookatzf56f2582019-09-04 16:06:41 -07003987 public long getUserCreationTime(@UserIdInt int userId) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003988 int callingUserId = UserHandle.getCallingUserId();
3989 UserInfo userInfo = null;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003990 synchronized (mUsersLock) {
Bookatzf56f2582019-09-04 16:06:41 -07003991 if (callingUserId == userId) {
3992 userInfo = getUserInfoLU(userId);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003993 } else {
Bookatzf56f2582019-09-04 16:06:41 -07003994 UserInfo parent = getProfileParentLU(userId);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003995 if (parent != null && parent.id == callingUserId) {
Bookatzf56f2582019-09-04 16:06:41 -07003996 userInfo = getUserInfoLU(userId);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003997 }
3998 }
3999 }
4000 if (userInfo == null) {
Bookatzf56f2582019-09-04 16:06:41 -07004001 throw new SecurityException("userId can only be the calling user or a managed "
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07004002 + "profile associated with this user");
4003 }
4004 return userInfo.creationTime;
4005 }
4006
Amith Yamasani0b285492011-04-14 17:35:23 -07004007 /**
4008 * Caches the list of user ids in an array, adjusting the array size when necessary.
4009 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07004010 private void updateUserIds() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07004011 int num = 0;
Fyodor Kupolov82402752015-10-28 14:54:51 -07004012 synchronized (mUsersLock) {
4013 final int userSize = mUsers.size();
4014 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08004015 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07004016 num++;
4017 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07004018 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07004019 final int[] newUsers = new int[num];
4020 int n = 0;
4021 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08004022 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07004023 newUsers[n++] = mUsers.keyAt(i);
4024 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07004025 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07004026 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07004027 }
4028 }
4029
4030 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07004031 * Called right before a user is started. This gives us a chance to prepare
4032 * app storage and apply any user restrictions.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08004033 */
Bookatzf56f2582019-09-04 16:06:41 -07004034 public void onBeforeStartUser(@UserIdInt int userId) {
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07004035 UserInfo userInfo = getUserInfo(userId);
4036 if (userInfo == null) {
4037 return;
4038 }
Felipe Leme3aad1be2019-05-31 11:43:12 -07004039 TimingsTraceAndSlog t = new TimingsTraceAndSlog();
4040 t.traceBegin("onBeforeStartUser-" + userId);
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07004041 final int userSerial = userInfo.serialNumber;
4042 // Migrate only if build fingerprints mismatch
4043 boolean migrateAppsData = !Build.FINGERPRINT.equals(userInfo.lastLoggedInFingerprint);
Felipe Leme3aad1be2019-05-31 11:43:12 -07004044 t.traceBegin("prepareUserData");
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -08004045 mUserDataPreparer.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_DE);
Felipe Leme3aad1be2019-05-31 11:43:12 -07004046 t.traceEnd();
4047 t.traceBegin("reconcileAppsData");
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07004048 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_DE, migrateAppsData);
Felipe Leme3aad1be2019-05-31 11:43:12 -07004049 t.traceEnd();
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07004050
4051 if (userId != UserHandle.USER_SYSTEM) {
Felipe Leme3aad1be2019-05-31 11:43:12 -07004052 t.traceBegin("applyUserRestrictions");
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07004053 synchronized (mRestrictionsLock) {
4054 applyUserRestrictionsLR(userId);
4055 }
Felipe Leme3aad1be2019-05-31 11:43:12 -07004056 t.traceEnd();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08004057 }
Felipe Leme3aad1be2019-05-31 11:43:12 -07004058 t.traceEnd(); // onBeforeStartUser
Makoto Onuki1a2cd742015-11-16 13:51:27 -08004059 }
4060
4061 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07004062 * Called right before a user is unlocked. This gives us a chance to prepare
4063 * app storage.
4064 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06004065 public void onBeforeUnlockUser(@UserIdInt int userId) {
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07004066 UserInfo userInfo = getUserInfo(userId);
4067 if (userInfo == null) {
4068 return;
4069 }
4070 final int userSerial = userInfo.serialNumber;
4071 // Migrate only if build fingerprints mismatch
4072 boolean migrateAppsData = !Build.FINGERPRINT.equals(userInfo.lastLoggedInFingerprint);
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -08004073 mUserDataPreparer.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_CE);
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07004074 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_CE, migrateAppsData);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07004075 }
4076
4077 /**
Fyodor Kupolov50979d12017-01-27 17:36:32 -08004078 * Examine all users present on given mounted volume, and destroy data
4079 * belonging to users that are no longer valid, or whose user ID has been
4080 * recycled.
4081 */
4082 void reconcileUsers(String volumeUuid) {
4083 mUserDataPreparer.reconcileUsers(volumeUuid, getUsers(true /* excludeDying */));
4084 }
4085
4086 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07004087 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasanieb437d42016-04-29 09:31:25 -07004088 * This is called with ActivityManagerService lock held.
Amith Yamasani920ace02012-09-20 22:15:37 -07004089 * @param userId the user that was just foregrounded
4090 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06004091 public void onUserLoggedIn(@UserIdInt int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -08004092 UserData userData = getUserDataNoChecks(userId);
4093 if (userData == null || userData.info.partial) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08004094 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
4095 return;
4096 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06004097
4098 final long now = System.currentTimeMillis();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08004099 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani12747872015-12-07 14:19:49 -08004100 userData.info.lastLoggedInTime = now;
Amith Yamasani920ace02012-09-20 22:15:37 -07004101 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06004102 userData.info.lastLoggedInFingerprint = Build.FINGERPRINT;
4103 scheduleWriteUser(userData);
Amith Yamasani920ace02012-09-20 22:15:37 -07004104 }
4105
4106 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07004107 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani0b285492011-04-14 17:35:23 -07004108 */
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07004109 @VisibleForTesting
4110 int getNextAvailableId() {
4111 int nextId;
Fyodor Kupolov82402752015-10-28 14:54:51 -07004112 synchronized (mUsersLock) {
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07004113 nextId = scanNextAvailableIdLocked();
4114 if (nextId >= 0) {
4115 return nextId;
4116 }
4117 // All ids up to MAX_USER_ID were used. Remove all mRemovingUserIds,
4118 // except most recently removed
4119 if (mRemovingUserIds.size() > 0) {
4120 Slog.i(LOG_TAG, "All available IDs are used. Recycling LRU ids.");
4121 mRemovingUserIds.clear();
4122 for (Integer recentlyRemovedId : mRecentlyRemovedIds) {
4123 mRemovingUserIds.put(recentlyRemovedId, true);
Amith Yamasani195263742012-08-21 15:40:12 -07004124 }
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07004125 nextId = scanNextAvailableIdLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07004126 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07004127 }
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07004128 if (nextId < 0) {
4129 throw new IllegalStateException("No user id available!");
4130 }
4131 return nextId;
4132 }
4133
Andreas Gampea36dc622018-02-05 17:19:22 -08004134 @GuardedBy("mUsersLock")
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07004135 private int scanNextAvailableIdLocked() {
4136 for (int i = MIN_USER_ID; i < MAX_USER_ID; i++) {
4137 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
4138 return i;
4139 }
4140 }
4141 return -1;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07004142 }
Amith Yamasani920ace02012-09-20 22:15:37 -07004143
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07004144 private static String packageToRestrictionsFileName(String packageName) {
Amith Yamasanifc95e702013-09-26 13:20:17 -07004145 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
4146 }
4147
Amith Yamasani920ace02012-09-20 22:15:37 -07004148 @Override
Bookatzf56f2582019-09-04 16:06:41 -07004149 public void setSeedAccountData(@UserIdInt int userId, String accountName, String accountType,
Amith Yamasani12747872015-12-07 14:19:49 -08004150 PersistableBundle accountOptions, boolean persist) {
4151 checkManageUsersPermission("Require MANAGE_USERS permission to set user seed data");
4152 synchronized (mPackagesLock) {
4153 final UserData userData;
4154 synchronized (mUsersLock) {
4155 userData = getUserDataLU(userId);
4156 if (userData == null) {
4157 Slog.e(LOG_TAG, "No such user for settings seed data u=" + userId);
4158 return;
4159 }
4160 userData.seedAccountName = accountName;
4161 userData.seedAccountType = accountType;
4162 userData.seedAccountOptions = accountOptions;
4163 userData.persistSeedData = persist;
4164 }
4165 if (persist) {
4166 writeUserLP(userData);
4167 }
4168 }
4169 }
4170
4171 @Override
4172 public String getSeedAccountName() throws RemoteException {
4173 checkManageUsersPermission("Cannot get seed account information");
4174 synchronized (mUsersLock) {
4175 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
4176 return userData.seedAccountName;
4177 }
4178 }
4179
4180 @Override
4181 public String getSeedAccountType() throws RemoteException {
4182 checkManageUsersPermission("Cannot get seed account information");
4183 synchronized (mUsersLock) {
4184 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
4185 return userData.seedAccountType;
4186 }
4187 }
4188
4189 @Override
4190 public PersistableBundle getSeedAccountOptions() throws RemoteException {
4191 checkManageUsersPermission("Cannot get seed account information");
4192 synchronized (mUsersLock) {
4193 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
4194 return userData.seedAccountOptions;
4195 }
4196 }
4197
4198 @Override
4199 public void clearSeedAccountData() throws RemoteException {
4200 checkManageUsersPermission("Cannot clear seed account information");
4201 synchronized (mPackagesLock) {
4202 UserData userData;
4203 synchronized (mUsersLock) {
4204 userData = getUserDataLU(UserHandle.getCallingUserId());
4205 if (userData == null) return;
4206 userData.clearSeedAccountData();
4207 }
4208 writeUserLP(userData);
4209 }
4210 }
4211
4212 @Override
4213 public boolean someUserHasSeedAccount(String accountName, String accountType)
4214 throws RemoteException {
4215 checkManageUsersPermission("Cannot check seed account information");
4216 synchronized (mUsersLock) {
4217 final int userSize = mUsers.size();
4218 for (int i = 0; i < userSize; i++) {
4219 final UserData data = mUsers.valueAt(i);
4220 if (data.info.isInitialized()) continue;
4221 if (data.seedAccountName == null || !data.seedAccountName.equals(accountName)) {
4222 continue;
4223 }
4224 if (data.seedAccountType == null || !data.seedAccountType.equals(accountType)) {
4225 continue;
4226 }
4227 return true;
4228 }
4229 }
4230 return false;
4231 }
4232
4233 @Override
Todd Kennedy60459ab2015-10-30 11:32:16 -07004234 public void onShellCommand(FileDescriptor in, FileDescriptor out,
Dianne Hackborn354736e2016-08-22 17:00:05 -07004235 FileDescriptor err, String[] args, ShellCallback callback,
4236 ResultReceiver resultReceiver) {
4237 (new Shell()).exec(this, in, out, err, args, callback, resultReceiver);
Todd Kennedy60459ab2015-10-30 11:32:16 -07004238 }
4239
4240 int onShellCommand(Shell shell, String cmd) {
4241 if (cmd == null) {
4242 return shell.handleDefaultCommands(cmd);
4243 }
4244
4245 final PrintWriter pw = shell.getOutPrintWriter();
4246 try {
4247 switch(cmd) {
4248 case "list":
Felipe Lemec1ca4412019-09-11 09:23:26 -07004249 return runList(pw, shell);
Hui Yu8ba65972018-04-16 18:45:48 -07004250 default:
4251 return shell.handleDefaultCommands(cmd);
Todd Kennedy60459ab2015-10-30 11:32:16 -07004252 }
4253 } catch (RemoteException e) {
4254 pw.println("Remote exception: " + e);
4255 }
4256 return -1;
4257 }
4258
Felipe Lemec1ca4412019-09-11 09:23:26 -07004259 private int runList(PrintWriter pw, Shell shell) throws RemoteException {
4260 boolean all = false;
4261 boolean verbose = false;
4262 String opt;
4263 while ((opt = shell.getNextOption()) != null) {
4264 switch (opt) {
4265 case "-v":
4266 verbose = true;
4267 break;
4268 case "--all":
4269 all = true;
4270 break;
4271 default:
4272 pw.println("Invalid option: " + opt);
4273 return -1;
4274 }
4275 }
Sudheer Shankadc589ac2016-11-10 15:30:17 -08004276 final IActivityManager am = ActivityManager.getService();
Felipe Lemec1ca4412019-09-11 09:23:26 -07004277 final List<UserInfo> users = getUsers(/* excludePartial= */ !all,
4278 /* excludingDying=*/ false, /* excludePreCreated= */ !all);
Todd Kennedy60459ab2015-10-30 11:32:16 -07004279 if (users == null) {
4280 pw.println("Error: couldn't get users");
4281 return 1;
4282 } else {
Felipe Lemec1ca4412019-09-11 09:23:26 -07004283 final int size = users.size();
4284 int currentUser = UserHandle.USER_NULL;
4285 if (verbose) {
4286 pw.printf("%d users:\n\n", size);
4287 currentUser = am.getCurrentUser().id;
4288 } else {
4289 // NOTE: the standard "list users" command is used by integration tests and
4290 // hence should not be changed. If you need to add more info, use the
4291 // verbose option.
4292 pw.println("Users:");
4293 }
4294 for (int i = 0; i < size; i++) {
4295 final UserInfo user = users.get(i);
4296 final boolean running = am.isUserRunning(user.id, 0);
4297 final boolean current = user.id == currentUser;
4298 if (verbose) {
4299 pw.printf("%d: id=%d, name=%s, flags=%s%s%s%s%s\n", i, user.id, user.name,
4300 UserInfo.flagsToString(user.flags),
4301 running ? " (running)" : "",
4302 user.partial ? " (partial)" : "",
4303 user.preCreated ? " (pre-created)" : "",
4304 current ? " (current)" : "");
4305 } else {
4306 // NOTE: the standard "list users" command is used by integration tests and
4307 // hence should not be changed. If you need to add more info, use the
4308 // verbose option.
4309 pw.printf("\t%s%s\n", user, running ? " running" : "");
4310 }
Todd Kennedy60459ab2015-10-30 11:32:16 -07004311 }
4312 return 0;
4313 }
4314 }
4315
4316 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -07004317 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06004318 if (!DumpUtils.checkDumpPermission(mContext, LOG_TAG, pw)) return;
Amith Yamasani920ace02012-09-20 22:15:37 -07004319
4320 long now = System.currentTimeMillis();
Makoto Onuki73dded22017-12-20 13:14:48 +09004321 final long nowRealtime = SystemClock.elapsedRealtime();
Felipe Lemed7b88382019-06-12 17:40:53 -07004322
Felipe Leme5b8dc762019-10-04 16:23:16 -07004323 final ActivityManagerInternal amInternal = LocalServices
4324 .getService(ActivityManagerInternal.class);
4325 pw.print("Current user: ");
4326 if (amInternal != null) {
4327 pw.println(amInternal.getCurrentUserId());
4328 } else {
4329 pw.println("N/A");
4330 }
Felipe Lemed7b88382019-06-12 17:40:53 -07004331
Amith Yamasani920ace02012-09-20 22:15:37 -07004332 StringBuilder sb = new StringBuilder();
4333 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07004334 synchronized (mUsersLock) {
4335 pw.println("Users:");
4336 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08004337 UserData userData = mUsers.valueAt(i);
4338 if (userData == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07004339 continue;
4340 }
Amith Yamasani12747872015-12-07 14:19:49 -08004341 UserInfo userInfo = userData.info;
4342 final int userId = userInfo.id;
4343 pw.print(" "); pw.print(userInfo);
4344 pw.print(" serialNo="); pw.print(userInfo.serialNumber);
Felipe Lemed7b88382019-06-12 17:40:53 -07004345 pw.print(" isPrimary="); pw.print(userInfo.isPrimary());
Makoto Onukie7927da2015-11-25 10:05:17 -08004346 if (mRemovingUserIds.get(userId)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07004347 pw.print(" <removing> ");
4348 }
Amith Yamasani12747872015-12-07 14:19:49 -08004349 if (userInfo.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07004350 pw.print(" <partial>");
4351 }
Felipe Lemec1ca4412019-09-11 09:23:26 -07004352 if (userInfo.preCreated) {
4353 pw.print(" <pre-created>");
4354 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07004355 pw.println();
Bookatz029832a2019-10-04 16:50:22 -07004356 pw.print(" Type: "); pw.println(userInfo.userType);
Felipe Lemee5434c32019-08-13 09:28:33 -07004357 pw.print(" Flags: "); pw.print(userInfo.flags); pw.print(" (");
4358 pw.print(UserInfo.flagsToString(userInfo.flags)); pw.println(")");
Makoto Onuki88aef752017-03-29 16:52:03 -07004359 pw.print(" State: ");
4360 final int state;
4361 synchronized (mUserStates) {
4362 state = mUserStates.get(userId, -1);
4363 }
4364 pw.println(UserState.stateToString(state));
Fyodor Kupolov82402752015-10-28 14:54:51 -07004365 pw.print(" Created: ");
Makoto Onuki73dded22017-12-20 13:14:48 +09004366 dumpTimeAgo(pw, sb, now, userInfo.creationTime);
4367
Fyodor Kupolov82402752015-10-28 14:54:51 -07004368 pw.print(" Last logged in: ");
Makoto Onuki73dded22017-12-20 13:14:48 +09004369 dumpTimeAgo(pw, sb, now, userInfo.lastLoggedInTime);
4370
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06004371 pw.print(" Last logged in fingerprint: ");
4372 pw.println(userInfo.lastLoggedInFingerprint);
Makoto Onuki73dded22017-12-20 13:14:48 +09004373
4374 pw.print(" Start time: ");
4375 dumpTimeAgo(pw, sb, nowRealtime, userData.startRealtime);
4376
4377 pw.print(" Unlock time: ");
4378 dumpTimeAgo(pw, sb, nowRealtime, userData.unlockRealtime);
4379
Makoto Onukie7927da2015-11-25 10:05:17 -08004380 pw.print(" Has profile owner: ");
4381 pw.println(mIsUserManaged.get(userId));
Fyodor Kupolov82402752015-10-28 14:54:51 -07004382 pw.println(" Restrictions:");
4383 synchronized (mRestrictionsLock) {
4384 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08004385 pw, " ", mBaseUserRestrictions.get(userInfo.id));
Pavel Grafov6a40f092016-10-25 15:46:51 +01004386 pw.println(" Device policy global restrictions:");
4387 UserRestrictionsUtils.dumpRestrictions(
4388 pw, " ", mDevicePolicyGlobalUserRestrictions.get(userInfo.id));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08004389 pw.println(" Device policy local restrictions:");
4390 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08004391 pw, " ", mDevicePolicyLocalUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07004392 pw.println(" Effective restrictions:");
4393 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08004394 pw, " ", mCachedEffectiveUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07004395 }
Amith Yamasani12747872015-12-07 14:19:49 -08004396
4397 if (userData.account != null) {
4398 pw.print(" Account name: " + userData.account);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08004399 pw.println();
4400 }
Amith Yamasani12747872015-12-07 14:19:49 -08004401
4402 if (userData.seedAccountName != null) {
4403 pw.print(" Seed account name: " + userData.seedAccountName);
4404 pw.println();
4405 if (userData.seedAccountType != null) {
4406 pw.print(" account type: " + userData.seedAccountType);
4407 pw.println();
4408 }
4409 if (userData.seedAccountOptions != null) {
4410 pw.print(" account options exist");
4411 pw.println();
4412 }
4413 }
Amith Yamasani920ace02012-09-20 22:15:37 -07004414 }
Amith Yamasani920ace02012-09-20 22:15:37 -07004415 }
Amith Yamasani12747872015-12-07 14:19:49 -08004416 pw.println();
Pavel Grafov6a40f092016-10-25 15:46:51 +01004417 pw.println(" Device owner id:" + mDeviceOwnerUserId);
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01004418 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08004419 pw.println(" Guest restrictions:");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08004420 synchronized (mGuestRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08004421 UserRestrictionsUtils.dumpRestrictions(pw, " ", mGuestRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08004422 }
Makoto Onukie7927da2015-11-25 10:05:17 -08004423 synchronized (mUsersLock) {
4424 pw.println();
4425 pw.println(" Device managed: " + mIsDeviceManaged);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07004426 if (mRemovingUserIds.size() > 0) {
4427 pw.println();
4428 pw.println(" Recently removed userIds: " + mRecentlyRemovedIds);
4429 }
Makoto Onukie7927da2015-11-25 10:05:17 -08004430 }
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00004431 synchronized (mUserStates) {
4432 pw.println(" Started users state: " + mUserStates);
4433 }
Felipe Lemed7b88382019-06-12 17:40:53 -07004434 } // synchronized (mPackagesLock)
4435
4436 // Dump some capabilities
4437 pw.println();
Felipe Lemec1ca4412019-09-11 09:23:26 -07004438 pw.print(" Max users: " + UserManager.getMaxSupportedUsers());
4439 pw.println(" (limit reached: " + isUserLimitReached() + ")");
Felipe Lemed7b88382019-06-12 17:40:53 -07004440 pw.println(" Supports switchable users: " + UserManager.supportsMultipleUsers());
Bookatz029832a2019-10-04 16:50:22 -07004441 pw.println(" All guests ephemeral: " + Resources.getSystem().getBoolean(
4442 com.android.internal.R.bool.config_guestUserEphemeral));
Felipe Lemed7b88382019-06-12 17:40:53 -07004443 pw.println(" Is split-system user: " + UserManager.isSplitSystemUser());
Felipe Lemee5434c32019-08-13 09:28:33 -07004444 pw.println(" Is headless-system mode: " + UserManager.isHeadlessSystemUserMode());
4445 pw.println(" User version: " + mUserVersion);
Bookatz04d7ae52019-08-05 14:07:12 -07004446
Bookatz029832a2019-10-04 16:50:22 -07004447 // Dump UserTypes
4448 pw.println();
4449 pw.println(" User types (" + mUserTypes.size() + " types):");
4450 for (int i = 0; i < mUserTypes.size(); i++) {
4451 pw.println(" " + mUserTypes.keyAt(i) + ": ");
4452 mUserTypes.valueAt(i).dump(pw);
4453 }
4454
Bookatz04d7ae52019-08-05 14:07:12 -07004455 // Dump package whitelist
4456 pw.println();
4457 mSystemPackageInstaller.dump(pw);
Amith Yamasani920ace02012-09-20 22:15:37 -07004458 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08004459
Makoto Onuki73dded22017-12-20 13:14:48 +09004460 private static void dumpTimeAgo(PrintWriter pw, StringBuilder sb, long nowTime, long time) {
4461 if (time == 0) {
4462 pw.println("<unknown>");
4463 } else {
4464 sb.setLength(0);
4465 TimeUtils.formatDuration(nowTime - time, sb);
4466 sb.append(" ago");
4467 pw.println(sb);
4468 }
4469 }
4470
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08004471 final class MainHandler extends Handler {
4472
4473 @Override
4474 public void handleMessage(Message msg) {
4475 switch (msg.what) {
4476 case WRITE_USER_MSG:
4477 removeMessages(WRITE_USER_MSG, msg.obj);
4478 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08004479 int userId = ((UserData) msg.obj).info.id;
4480 UserData userData = getUserDataNoChecks(userId);
4481 if (userData != null) {
4482 writeUserLP(userData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08004483 }
4484 }
4485 }
4486 }
4487 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07004488
4489 /**
4490 * @param userId
4491 * @return whether the user has been initialized yet
4492 */
Bookatzf56f2582019-09-04 16:06:41 -07004493 boolean isUserInitialized(@UserIdInt int userId) {
Todd Kennedy0eb97382017-10-03 16:57:22 -07004494 return mLocalService.isUserInitialized(userId);
Amith Yamasanibb054c92015-07-09 14:16:27 -07004495 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07004496
4497 private class LocalService extends UserManagerInternal {
Makoto Onuki068c54a2015-10-13 14:34:03 -07004498 @Override
Bookatzf56f2582019-09-04 16:06:41 -07004499 public void setDevicePolicyUserRestrictions(@UserIdInt int userId,
4500 @Nullable Bundle restrictions, boolean isDeviceOwner, int cameraRestrictionScope) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01004501 UserManagerService.this.setDevicePolicyUserRestrictionsInner(userId, restrictions,
4502 isDeviceOwner, cameraRestrictionScope);
Makoto Onuki068c54a2015-10-13 14:34:03 -07004503 }
4504
4505 @Override
Bookatzf56f2582019-09-04 16:06:41 -07004506 public Bundle getBaseUserRestrictions(@UserIdInt int userId) {
Makoto Onuki068c54a2015-10-13 14:34:03 -07004507 synchronized (mRestrictionsLock) {
4508 return mBaseUserRestrictions.get(userId);
4509 }
4510 }
4511
4512 @Override
4513 public void setBaseUserRestrictionsByDpmsForMigration(
Bookatzf56f2582019-09-04 16:06:41 -07004514 @UserIdInt int userId, Bundle baseRestrictions) {
Makoto Onuki068c54a2015-10-13 14:34:03 -07004515 synchronized (mRestrictionsLock) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01004516 if (updateRestrictionsIfNeededLR(
4517 userId, new Bundle(baseRestrictions), mBaseUserRestrictions)) {
4518 invalidateEffectiveUserRestrictionsLR(userId);
4519 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07004520 }
4521
Amith Yamasani12747872015-12-07 14:19:49 -08004522 final UserData userData = getUserDataNoChecks(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07004523 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08004524 if (userData != null) {
4525 writeUserLP(userData);
Makoto Onuki068c54a2015-10-13 14:34:03 -07004526 } else {
4527 Slog.w(LOG_TAG, "UserInfo not found for " + userId);
4528 }
4529 }
4530 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08004531
4532 @Override
Bookatzf56f2582019-09-04 16:06:41 -07004533 public boolean getUserRestriction(@UserIdInt int userId, String key) {
Makoto Onukid45a4a22015-11-02 17:17:38 -08004534 return getUserRestrictions(userId).getBoolean(key);
4535 }
4536
4537 @Override
4538 public void addUserRestrictionsListener(UserRestrictionsListener listener) {
4539 synchronized (mUserRestrictionsListeners) {
4540 mUserRestrictionsListeners.add(listener);
4541 }
4542 }
4543
4544 @Override
4545 public void removeUserRestrictionsListener(UserRestrictionsListener listener) {
4546 synchronized (mUserRestrictionsListeners) {
4547 mUserRestrictionsListeners.remove(listener);
4548 }
4549 }
Makoto Onukie7927da2015-11-25 10:05:17 -08004550
4551 @Override
4552 public void setDeviceManaged(boolean isManaged) {
4553 synchronized (mUsersLock) {
4554 mIsDeviceManaged = isManaged;
4555 }
4556 }
4557
4558 @Override
Rubin Xu0f1e56d2019-08-23 13:34:25 +01004559 public boolean isDeviceManaged() {
4560 synchronized (mUsersLock) {
4561 return mIsDeviceManaged;
4562 }
4563 }
4564
4565 @Override
Bookatzf56f2582019-09-04 16:06:41 -07004566 public void setUserManaged(@UserIdInt int userId, boolean isManaged) {
Makoto Onukie7927da2015-11-25 10:05:17 -08004567 synchronized (mUsersLock) {
4568 mIsUserManaged.put(userId, isManaged);
4569 }
4570 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01004571
4572 @Override
Rubin Xu0f1e56d2019-08-23 13:34:25 +01004573 public boolean isUserManaged(@UserIdInt int userId) {
4574 synchronized (mUsersLock) {
4575 return mIsUserManaged.get(userId);
4576 }
4577 }
4578
4579 @Override
Bookatzf56f2582019-09-04 16:06:41 -07004580 public void setUserIcon(@UserIdInt int userId, Bitmap bitmap) {
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01004581 long ident = Binder.clearCallingIdentity();
4582 try {
4583 synchronized (mPackagesLock) {
4584 UserData userData = getUserDataNoChecks(userId);
4585 if (userData == null || userData.info.partial) {
4586 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
4587 return;
4588 }
4589 writeBitmapLP(userData.info, bitmap);
4590 writeUserLP(userData);
4591 }
4592 sendUserInfoChangedBroadcast(userId);
4593 } finally {
4594 Binder.restoreCallingIdentity(ident);
4595 }
4596 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01004597
4598 @Override
4599 public void setForceEphemeralUsers(boolean forceEphemeralUsers) {
4600 synchronized (mUsersLock) {
4601 mForceEphemeralUsers = forceEphemeralUsers;
4602 }
4603 }
4604
4605 @Override
4606 public void removeAllUsers() {
4607 if (UserHandle.USER_SYSTEM == ActivityManager.getCurrentUser()) {
4608 // Remove the non-system users straight away.
4609 removeNonSystemUsers();
4610 } else {
4611 // Switch to the system user first and then remove the other users.
4612 BroadcastReceiver userSwitchedReceiver = new BroadcastReceiver() {
4613 @Override
4614 public void onReceive(Context context, Intent intent) {
4615 int userId =
4616 intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
4617 if (userId != UserHandle.USER_SYSTEM) {
4618 return;
4619 }
4620 mContext.unregisterReceiver(this);
4621 removeNonSystemUsers();
4622 }
4623 };
4624 IntentFilter userSwitchedFilter = new IntentFilter();
4625 userSwitchedFilter.addAction(Intent.ACTION_USER_SWITCHED);
4626 mContext.registerReceiver(
4627 userSwitchedReceiver, userSwitchedFilter, null, mHandler);
4628
4629 // Switch to the system user.
4630 ActivityManager am =
4631 (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
4632 am.switchUser(UserHandle.USER_SYSTEM);
4633 }
4634 }
phweisse9c44062016-02-10 12:57:38 +01004635
4636 @Override
Bookatzf56f2582019-09-04 16:06:41 -07004637 public void onEphemeralUserStop(@UserIdInt int userId) {
Lenka Trochtova1ddda472016-02-12 10:42:12 +01004638 synchronized (mUsersLock) {
4639 UserInfo userInfo = getUserInfoLU(userId);
4640 if (userInfo != null && userInfo.isEphemeral()) {
4641 // Do not allow switching back to the ephemeral user again as the user is going
4642 // to be deleted.
4643 userInfo.flags |= UserInfo.FLAG_DISABLED;
4644 if (userInfo.isGuest()) {
4645 // Indicate that the guest will be deleted after it stops.
4646 userInfo.guestToRemove = true;
4647 }
4648 }
4649 }
4650 }
4651
4652 @Override
Bookatz029832a2019-10-04 16:50:22 -07004653 public UserInfo createUserEvenWhenDisallowed(String name, @NonNull String userType,
4654 @UserInfoFlag int flags, String[] disallowedPackages) {
4655 UserInfo user = createUserInternalUnchecked(name, userType, flags,
4656 UserHandle.USER_NULL, /* preCreated= */ false, disallowedPackages);
phweisse9c44062016-02-10 12:57:38 +01004657 // Keep this in sync with UserManager.createUser
Christine Franks97a54802017-08-09 10:06:43 -07004658 if (user != null && !user.isAdmin() && !user.isDemo()) {
phweisse9c44062016-02-10 12:57:38 +01004659 setUserRestriction(UserManager.DISALLOW_SMS, true, user.id);
4660 setUserRestriction(UserManager.DISALLOW_OUTGOING_CALLS, true, user.id);
4661 }
4662 return user;
4663 }
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07004664
4665 @Override
Bookatzf56f2582019-09-04 16:06:41 -07004666 public boolean removeUserEvenWhenDisallowed(@UserIdInt int userId) {
Nicolas Prevotdf1b87d2016-10-25 13:57:08 +01004667 return removeUserUnchecked(userId);
4668 }
4669
4670 @Override
Bookatzf56f2582019-09-04 16:06:41 -07004671 public boolean isUserRunning(@UserIdInt int userId) {
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00004672 synchronized (mUserStates) {
4673 return mUserStates.get(userId, -1) >= 0;
4674 }
4675 }
4676
4677 @Override
Bookatzf56f2582019-09-04 16:06:41 -07004678 public void setUserState(@UserIdInt int userId, int userState) {
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00004679 synchronized (mUserStates) {
4680 mUserStates.put(userId, userState);
4681 }
4682 }
4683
4684 @Override
Bookatzf56f2582019-09-04 16:06:41 -07004685 public void removeUserState(@UserIdInt int userId) {
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00004686 synchronized (mUserStates) {
4687 mUserStates.delete(userId);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07004688 }
4689 }
4690
4691 @Override
Michael Wachenschwanz3f2b6552017-05-15 13:53:09 -07004692 public int[] getUserIds() {
4693 return UserManagerService.this.getUserIds();
4694 }
4695
4696 @Override
Bookatzf56f2582019-09-04 16:06:41 -07004697 public boolean isUserUnlockingOrUnlocked(@UserIdInt int userId) {
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07004698 int state;
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00004699 synchronized (mUserStates) {
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07004700 state = mUserStates.get(userId, -1);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07004701 }
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07004702 // Special case, in the stopping/shutdown state user key can still be unlocked
4703 if (state == UserState.STATE_STOPPING || state == UserState.STATE_SHUTDOWN) {
4704 return StorageManager.isUserKeyUnlocked(userId);
4705 }
4706 return (state == UserState.STATE_RUNNING_UNLOCKING)
4707 || (state == UserState.STATE_RUNNING_UNLOCKED);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07004708 }
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08004709
4710 @Override
Bookatzf56f2582019-09-04 16:06:41 -07004711 public boolean isUserUnlocked(@UserIdInt int userId) {
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07004712 int state;
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08004713 synchronized (mUserStates) {
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07004714 state = mUserStates.get(userId, -1);
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08004715 }
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07004716 // Special case, in the stopping/shutdown state user key can still be unlocked
4717 if (state == UserState.STATE_STOPPING || state == UserState.STATE_SHUTDOWN) {
4718 return StorageManager.isUserKeyUnlocked(userId);
4719 }
4720 return state == UserState.STATE_RUNNING_UNLOCKED;
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08004721 }
Todd Kennedy0eb97382017-10-03 16:57:22 -07004722
4723 @Override
Bookatzf56f2582019-09-04 16:06:41 -07004724 public boolean isUserInitialized(@UserIdInt int userId) {
Todd Kennedy0eb97382017-10-03 16:57:22 -07004725 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
4726 }
4727
4728 @Override
Bookatzf56f2582019-09-04 16:06:41 -07004729 public boolean exists(@UserIdInt int userId) {
Todd Kennedy0eb97382017-10-03 16:57:22 -07004730 return getUserInfoNoChecks(userId) != null;
4731 }
Sunny Goyal145c8f82018-02-15 14:27:09 -08004732
4733 @Override
4734 public boolean isProfileAccessible(int callingUserId, int targetUserId, String debugMsg,
4735 boolean throwSecurityException) {
4736 if (targetUserId == callingUserId) {
4737 return true;
4738 }
4739 synchronized (mUsersLock) {
4740 UserInfo callingUserInfo = getUserInfoLU(callingUserId);
Bookatz029832a2019-10-04 16:50:22 -07004741 if (callingUserInfo == null || callingUserInfo.isProfile()) {
Sunny Goyal145c8f82018-02-15 14:27:09 -08004742 if (throwSecurityException) {
4743 throw new SecurityException(
4744 debugMsg + " for another profile "
4745 + targetUserId + " from " + callingUserId);
4746 }
4747 }
4748
4749 UserInfo targetUserInfo = getUserInfoLU(targetUserId);
4750 if (targetUserInfo == null || !targetUserInfo.isEnabled()) {
4751 // Do not throw any exception here as this could happen due to race conditions
4752 // between the system updating its state and the client getting notified.
4753 if (throwSecurityException) {
4754 Slog.w(LOG_TAG, debugMsg + " for disabled profile "
4755 + targetUserId + " from " + callingUserId);
4756 }
4757 return false;
4758 }
4759
4760 if (targetUserInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID ||
4761 targetUserInfo.profileGroupId != callingUserInfo.profileGroupId) {
4762 if (throwSecurityException) {
4763 throw new SecurityException(
4764 debugMsg + " for unrelated profile " + targetUserId);
4765 }
4766 return false;
4767 }
4768 }
4769 return true;
4770 }
4771
4772 @Override
Bookatzf56f2582019-09-04 16:06:41 -07004773 public int getProfileParentId(@UserIdInt int userId) {
Sunny Goyal145c8f82018-02-15 14:27:09 -08004774 synchronized (mUsersLock) {
4775 UserInfo profileParent = getProfileParentLU(userId);
4776 if (profileParent == null) {
4777 return userId;
4778 }
4779 return profileParent.id;
4780 }
4781 }
yuemingw1d13eae2018-01-30 17:27:54 +00004782
4783 @Override
4784 public boolean isSettingRestrictedForUser(String setting, @UserIdInt int userId,
4785 String value, int callingUid) {
Christopher Tate65fb2e42019-10-11 17:00:23 -07004786 return UserManagerService.this.isSettingRestrictedForUser(setting, userId,
yuemingw1d13eae2018-01-30 17:27:54 +00004787 value, callingUid);
4788 }
Patrick Baumann2f2fd712019-07-31 15:18:53 -07004789
4790 @Override
Bookatzf56f2582019-09-04 16:06:41 -07004791 public boolean hasUserRestriction(String restrictionKey, @UserIdInt int userId) {
Patrick Baumann2f2fd712019-07-31 15:18:53 -07004792 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
4793 return false;
4794 }
4795 Bundle restrictions = getEffectiveUserRestrictions(userId);
4796 return restrictions != null && restrictions.getBoolean(restrictionKey);
4797 }
Felipe Lemee5434c32019-08-13 09:28:33 -07004798
Rubin Xu0f1e56d2019-08-23 13:34:25 +01004799 @Override
Felipe Lemee5434c32019-08-13 09:28:33 -07004800 public @Nullable UserInfo getUserInfo(@UserIdInt int userId) {
4801 UserData userData;
4802 synchronized (mUsersLock) {
4803 userData = mUsers.get(userId);
4804 }
4805 return userData == null ? null : userData.info;
4806 }
Felipe Leme987655d2019-08-26 10:45:24 -07004807
4808 public @NonNull UserInfo[] getUserInfos() {
4809 synchronized (mUsersLock) {
4810 int userSize = mUsers.size();
4811 UserInfo[] allInfos = new UserInfo[userSize];
4812 for (int i = 0; i < userSize; i++) {
4813 allInfos[i] = mUsers.valueAt(i).info;
4814 }
4815 return allInfos;
4816 }
4817 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01004818 }
4819
4820 /* Remove all the users except of the system one. */
4821 private void removeNonSystemUsers() {
4822 ArrayList<UserInfo> usersToRemove = new ArrayList<>();
4823 synchronized (mUsersLock) {
4824 final int userSize = mUsers.size();
4825 for (int i = 0; i < userSize; i++) {
4826 UserInfo ui = mUsers.valueAt(i).info;
4827 if (ui.id != UserHandle.USER_SYSTEM) {
4828 usersToRemove.add(ui);
4829 }
4830 }
4831 }
4832 for (UserInfo ui: usersToRemove) {
4833 removeUser(ui.id);
4834 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07004835 }
Todd Kennedy60459ab2015-10-30 11:32:16 -07004836
4837 private class Shell extends ShellCommand {
4838 @Override
4839 public int onCommand(String cmd) {
4840 return onShellCommand(this, cmd);
4841 }
4842
4843 @Override
4844 public void onHelp() {
4845 final PrintWriter pw = getOutPrintWriter();
4846 pw.println("User manager (user) commands:");
4847 pw.println(" help");
4848 pw.println(" Print this help text.");
4849 pw.println("");
Felipe Lemec1ca4412019-09-11 09:23:26 -07004850 pw.println(" list [-v] [-all]");
Todd Kennedy60459ab2015-10-30 11:32:16 -07004851 pw.println(" Prints all users on the system.");
4852 }
4853 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08004854
4855 private static void debug(String message) {
4856 Log.d(LOG_TAG, message +
4857 (DBG_WITH_STACKTRACE ? " called at\n" + Debug.getCallers(10, " ") : ""));
4858 }
Kenny Guy02c89902016-11-15 19:36:38 +00004859
Bookatz029832a2019-10-04 16:50:22 -07004860 /** @see #getMaxUsersOfTypePerParent(UserTypeDetails) */
Kenny Guy02c89902016-11-15 19:36:38 +00004861 @VisibleForTesting
Bookatz029832a2019-10-04 16:50:22 -07004862 int getMaxUsersOfTypePerParent(String userType) {
4863 final UserTypeDetails type = mUserTypes.get(userType);
4864 if (type == null) {
4865 return 0;
Kenny Guy02c89902016-11-15 19:36:38 +00004866 }
Bookatz029832a2019-10-04 16:50:22 -07004867 return getMaxUsersOfTypePerParent(type);
4868 }
4869
4870 /**
4871 * Returns the maximum number of users allowed for the given userTypeDetails per parent user.
4872 * This is applicable for user types that are {@link UserTypeDetails#isProfile()}.
4873 * If there is no maximum, {@link UserTypeDetails#UNLIMITED_NUMBER_OF_USERS} is returned.
4874 */
4875 private static int getMaxUsersOfTypePerParent(UserTypeDetails userTypeDetails) {
4876 final int defaultMax = userTypeDetails.getMaxAllowedPerParent();
4877 if (!Build.IS_DEBUGGABLE) {
4878 return defaultMax;
4879 } else {
4880 if (userTypeDetails.isManagedProfile()) {
4881 return SystemProperties.getInt("persist.sys.max_profiles", defaultMax);
4882 }
4883 }
4884 return defaultMax;
Kenny Guy02c89902016-11-15 19:36:38 +00004885 }
4886
Andreas Gampe2e8c7672018-07-20 13:01:08 -07004887 @GuardedBy("mUsersLock")
Kenny Guy02c89902016-11-15 19:36:38 +00004888 @VisibleForTesting
Bookatz029832a2019-10-04 16:50:22 -07004889 int getFreeProfileBadgeLU(int parentUserId, String userType) {
4890 Set<Integer> usedBadges = new ArraySet<>();
Kenny Guy02c89902016-11-15 19:36:38 +00004891 final int userSize = mUsers.size();
4892 for (int i = 0; i < userSize; i++) {
4893 UserInfo ui = mUsers.valueAt(i).info;
4894 // Check which badge indexes are already used by this profile group.
Bookatz029832a2019-10-04 16:50:22 -07004895 if (ui.userType.equals(userType)
Kenny Guy02c89902016-11-15 19:36:38 +00004896 && ui.profileGroupId == parentUserId
Bookatz029832a2019-10-04 16:50:22 -07004897 && !mRemovingUserIds.get(ui.id)) {
4898 usedBadges.add(ui.profileBadge);
Kenny Guy02c89902016-11-15 19:36:38 +00004899 }
4900 }
Bookatz029832a2019-10-04 16:50:22 -07004901 int maxUsersOfType = getMaxUsersOfTypePerParent(userType);
4902 if (maxUsersOfType == UserTypeDetails.UNLIMITED_NUMBER_OF_USERS) {
4903 maxUsersOfType = Integer.MAX_VALUE;
4904 }
4905 for (int i = 0; i < maxUsersOfType; i++) {
4906 if (!usedBadges.contains(i)) {
Kenny Guy02c89902016-11-15 19:36:38 +00004907 return i;
4908 }
4909 }
4910 return 0;
4911 }
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07004912
4913 /**
4914 * Checks if the given user has a managed profile associated with it.
4915 * @param userId The parent user
4916 * @return
4917 */
Bookatzf56f2582019-09-04 16:06:41 -07004918 boolean hasManagedProfile(@UserIdInt int userId) {
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07004919 synchronized (mUsersLock) {
4920 UserInfo userInfo = getUserInfoLU(userId);
4921 final int userSize = mUsers.size();
4922 for (int i = 0; i < userSize; i++) {
4923 UserInfo profile = mUsers.valueAt(i).info;
4924 if (userId != profile.id && isProfileOf(userInfo, profile)) {
4925 return true;
4926 }
4927 }
4928 return false;
4929 }
4930 }
Tony Makd390ae92017-12-28 13:23:10 +00004931
4932 /**
4933 * Check if the calling package name matches with the calling UID, throw
4934 * {@link SecurityException} if not.
4935 */
4936 private void verifyCallingPackage(String callingPackage, int callingUid) {
4937 int packageUid = mPm.getPackageUid(callingPackage, 0, UserHandle.getUserId(callingUid));
4938 if (packageUid != callingUid) {
4939 throw new SecurityException("Specified package " + callingPackage
4940 + " does not match the calling uid " + callingUid);
4941 }
4942 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07004943}