blob: 4b047264a11ee6c36aa777aa4ecddabf683fac55 [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 }
Bookatz04d7ae52019-08-05 14:07:12 -0700567 mSystemPackageInstaller = new UserSystemPackageInstaller(this);
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
Tony Makd390ae92017-12-28 13:23:10 +0000902 ensureCanModifyQuietMode(callingPackage, Binder.getCallingUid(), 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>
934 * </ul>
Tony Makd390ae92017-12-28 13:23:10 +0000935 * <p>
936 * If caller wants to start an intent after disabling the quiet mode, it must has
937 * {@link Manifest.permission#MANAGE_USERS}.
Tony Make3d1f652017-12-12 11:00:37 +0000938 */
Tony Makd390ae92017-12-28 13:23:10 +0000939 private void ensureCanModifyQuietMode(String callingPackage, int callingUid,
940 boolean startIntent) {
Tony Make3d1f652017-12-12 11:00:37 +0000941 if (hasManageUsersPermission()) {
Tony Makd390ae92017-12-28 13:23:10 +0000942 return;
Tony Make3d1f652017-12-12 11:00:37 +0000943 }
Tony Makd390ae92017-12-28 13:23:10 +0000944 if (startIntent) {
945 throw new SecurityException("MANAGE_USERS permission is required to start intent "
946 + "after disabling quiet mode.");
947 }
jovanakf24ad492018-05-18 12:15:59 -0700948 final boolean hasModifyQuietModePermission = hasPermissionGranted(
949 Manifest.permission.MODIFY_QUIET_MODE, callingUid);
Tony Make3d1f652017-12-12 11:00:37 +0000950 if (hasModifyQuietModePermission) {
Tony Makd390ae92017-12-28 13:23:10 +0000951 return;
Tony Make3d1f652017-12-12 11:00:37 +0000952 }
953
Tony Makd390ae92017-12-28 13:23:10 +0000954 verifyCallingPackage(callingPackage, callingUid);
Tony Make3d1f652017-12-12 11:00:37 +0000955 final ShortcutServiceInternal shortcutInternal =
956 LocalServices.getService(ShortcutServiceInternal.class);
957 if (shortcutInternal != null) {
958 boolean isForegroundLauncher =
959 shortcutInternal.isForegroundDefaultLauncher(callingPackage, callingUid);
960 if (isForegroundLauncher) {
Tony Makd390ae92017-12-28 13:23:10 +0000961 return;
Tony Make3d1f652017-12-12 11:00:37 +0000962 }
963 }
Tony Makd390ae92017-12-28 13:23:10 +0000964 throw new SecurityException("Can't modify quiet mode, caller is neither foreground "
965 + "default launcher nor has MANAGE_USERS/MODIFY_QUIET_MODE permission");
Tony Make3d1f652017-12-12 11:00:37 +0000966 }
967
Bookatzf56f2582019-09-04 16:06:41 -0700968 private void setQuietModeEnabled(@UserIdInt int userId, boolean enableQuietMode,
arangelov9b632d72018-12-07 23:21:22 +0000969 IntentSender target, @Nullable String callingPackage) {
Tony Makb7e6fd42017-12-05 19:40:28 +0000970 final UserInfo profile, parent;
971 final UserData profileUserData;
972 synchronized (mUsersLock) {
Bookatzf56f2582019-09-04 16:06:41 -0700973 profile = getUserInfoLU(userId);
974 parent = getProfileParentLU(userId);
Tony Makb7e6fd42017-12-05 19:40:28 +0000975
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000976 if (profile == null || !profile.isManagedProfile()) {
Bookatzf56f2582019-09-04 16:06:41 -0700977 throw new IllegalArgumentException("User " + userId + " is not a profile");
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000978 }
Tony Makb7e6fd42017-12-05 19:40:28 +0000979 if (profile.isQuietModeEnabled() == enableQuietMode) {
980 Slog.i(LOG_TAG, "Quiet mode is already " + enableQuietMode);
981 return;
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000982 }
Tony Makb7e6fd42017-12-05 19:40:28 +0000983 profile.flags ^= UserInfo.FLAG_QUIET_MODE;
984 profileUserData = getUserDataLU(profile.id);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000985 }
Tony Makb7e6fd42017-12-05 19:40:28 +0000986 synchronized (mPackagesLock) {
987 writeUserLP(profileUserData);
988 }
989 try {
990 if (enableQuietMode) {
Bookatzf56f2582019-09-04 16:06:41 -0700991 ActivityManager.getService().stopUser(userId, /* force */true, null);
Tony Makb7e6fd42017-12-05 19:40:28 +0000992 LocalServices.getService(ActivityManagerInternal.class)
Bookatzf56f2582019-09-04 16:06:41 -0700993 .killForegroundAppsForUser(userId);
Tony Makb7e6fd42017-12-05 19:40:28 +0000994 } else {
995 IProgressListener callback = target != null
996 ? new DisableQuietModeUserUnlockedCallback(target)
997 : null;
998 ActivityManager.getService().startUserInBackgroundWithListener(
Bookatzf56f2582019-09-04 16:06:41 -0700999 userId, callback);
Rubin Xuf13c9802016-01-21 18:06:00 +00001000 }
Bookatzf56f2582019-09-04 16:06:41 -07001001 logQuietModeEnabled(userId, enableQuietMode, callingPackage);
Tony Makb7e6fd42017-12-05 19:40:28 +00001002 } catch (RemoteException e) {
1003 // Should not happen, same process.
1004 e.rethrowAsRuntimeException();
Rubin Xu0a29ecd2015-11-04 15:11:48 +00001005 }
Tony Makb7e6fd42017-12-05 19:40:28 +00001006 broadcastProfileAvailabilityChanges(profile.getUserHandle(), parent.getUserHandle(),
1007 enableQuietMode);
Rubin Xu0a29ecd2015-11-04 15:11:48 +00001008 }
1009
Bookatzf56f2582019-09-04 16:06:41 -07001010 private void logQuietModeEnabled(@UserIdInt int userId, boolean enableQuietMode,
arangelov9b632d72018-12-07 23:21:22 +00001011 @Nullable String callingPackage) {
1012 UserData userData;
1013 synchronized (mUsersLock) {
Bookatzf56f2582019-09-04 16:06:41 -07001014 userData = getUserDataLU(userId);
arangelov9b632d72018-12-07 23:21:22 +00001015 }
1016 if (userData == null) {
1017 return;
1018 }
1019 final long now = System.currentTimeMillis();
1020 final long period = (userData.getLastRequestQuietModeEnabledMillis() != 0L
1021 ? now - userData.getLastRequestQuietModeEnabledMillis()
1022 : now - userData.info.creationTime);
1023 DevicePolicyEventLogger
1024 .createEvent(DevicePolicyEnums.REQUEST_QUIET_MODE_ENABLED)
1025 .setStrings(callingPackage)
1026 .setBoolean(enableQuietMode)
1027 .setTimePeriod(period)
1028 .write();
1029 userData.setLastRequestQuietModeEnabledMillis(now);
1030 }
1031
Rubin Xu0a29ecd2015-11-04 15:11:48 +00001032 @Override
Bookatzf56f2582019-09-04 16:06:41 -07001033 public boolean isQuietModeEnabled(@UserIdInt int userId) {
Rubin Xu0a29ecd2015-11-04 15:11:48 +00001034 synchronized (mPackagesLock) {
1035 UserInfo info;
1036 synchronized (mUsersLock) {
Bookatzf56f2582019-09-04 16:06:41 -07001037 info = getUserInfoLU(userId);
Rubin Xu0a29ecd2015-11-04 15:11:48 +00001038 }
1039 if (info == null || !info.isManagedProfile()) {
Rubin Xuf13c9802016-01-21 18:06:00 +00001040 return false;
Rubin Xu0a29ecd2015-11-04 15:11:48 +00001041 }
1042 return info.isQuietModeEnabled();
1043 }
1044 }
1045
Tony Makb7e6fd42017-12-05 19:40:28 +00001046 /**
1047 * Show confirm credential screen to unlock user in order to turn off quiet mode.
1048 */
1049 private void showConfirmCredentialToDisableQuietMode(
Bookatzf56f2582019-09-04 16:06:41 -07001050 @UserIdInt int userId, @Nullable IntentSender target) {
Tony Makb7e6fd42017-12-05 19:40:28 +00001051 // otherwise, we show a profile challenge to trigger decryption of the user
1052 final KeyguardManager km = (KeyguardManager) mContext.getSystemService(
1053 Context.KEYGUARD_SERVICE);
Bookatzf56f2582019-09-04 16:06:41 -07001054 // We should use userId not credentialOwnerUserId here, as even if it is unified
Tony Makb7e6fd42017-12-05 19:40:28 +00001055 // lock, confirm screenlock page will know and show personal challenge, and unlock
1056 // work profile when personal challenge is correct
Bookatzf56f2582019-09-04 16:06:41 -07001057 final Intent unlockIntent = km.createConfirmDeviceCredentialIntent(null, null, userId);
Tony Makb7e6fd42017-12-05 19:40:28 +00001058 if (unlockIntent == null) {
1059 return;
Benjamin Franzf02420c2016-04-04 18:52:21 +01001060 }
Tony Makb7e6fd42017-12-05 19:40:28 +00001061 final Intent callBackIntent = new Intent(
1062 ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK);
1063 if (target != null) {
1064 callBackIntent.putExtra(Intent.EXTRA_INTENT, target);
Benjamin Franzf02420c2016-04-04 18:52:21 +01001065 }
Bookatzf56f2582019-09-04 16:06:41 -07001066 callBackIntent.putExtra(Intent.EXTRA_USER_ID, userId);
Tony Makb7e6fd42017-12-05 19:40:28 +00001067 callBackIntent.setPackage(mContext.getPackageName());
1068 callBackIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1069 final PendingIntent pendingIntent = PendingIntent.getBroadcast(
1070 mContext,
1071 0,
1072 callBackIntent,
1073 PendingIntent.FLAG_CANCEL_CURRENT |
1074 PendingIntent.FLAG_ONE_SHOT |
1075 PendingIntent.FLAG_IMMUTABLE);
1076 // After unlocking the challenge, it will disable quiet mode and run the original
1077 // intentSender
1078 unlockIntent.putExtra(Intent.EXTRA_INTENT, pendingIntent.getIntentSender());
1079 unlockIntent.setFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
1080 mContext.startActivity(unlockIntent);
Benjamin Franzf02420c2016-04-04 18:52:21 +01001081 }
1082
1083 @Override
Bookatzf56f2582019-09-04 16:06:41 -07001084 public void setUserEnabled(@UserIdInt int userId) {
Alexandra Gherghinadf35d572014-04-09 13:54:39 +01001085 checkManageUsersPermission("enable user");
1086 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001087 UserInfo info;
1088 synchronized (mUsersLock) {
1089 info = getUserInfoLU(userId);
1090 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +01001091 if (info != null && !info.isEnabled()) {
1092 info.flags ^= UserInfo.FLAG_DISABLED;
Amith Yamasani12747872015-12-07 14:19:49 -08001093 writeUserLP(getUserDataLU(info.id));
Alexandra Gherghinadf35d572014-04-09 13:54:39 +01001094 }
1095 }
1096 }
1097
jovanakf24ad492018-05-18 12:15:59 -07001098 @Override
Bookatzf56f2582019-09-04 16:06:41 -07001099 public void setUserAdmin(@UserIdInt int userId) {
jovanakf24ad492018-05-18 12:15:59 -07001100 checkManageUserAndAcrossUsersFullPermission("set user admin");
1101
1102 synchronized (mPackagesLock) {
1103 UserInfo info;
1104 synchronized (mUsersLock) {
1105 info = getUserInfoLU(userId);
1106 }
1107 if (info == null || info.isAdmin()) {
1108 // Exit if no user found with that id, or the user is already an Admin.
1109 return;
1110 }
1111
1112 info.flags ^= UserInfo.FLAG_ADMIN;
1113 writeUserLP(getUserDataLU(info.id));
1114 }
1115
1116 // Remove non-admin restrictions.
1117 // Keep synchronized with createUserEvenWhenDisallowed.
1118 setUserRestriction(UserManager.DISALLOW_SMS, false, userId);
1119 setUserRestriction(UserManager.DISALLOW_OUTGOING_CALLS, false, userId);
1120 }
1121
Andrew Scull85a63bc2016-10-24 13:47:47 +01001122 /**
1123 * Evicts a user's CE key by stopping and restarting the user.
1124 *
1125 * The key is evicted automatically by the user controller when the user has stopped.
1126 */
1127 @Override
1128 public void evictCredentialEncryptionKey(@UserIdInt int userId) {
1129 checkManageUsersPermission("evict CE key");
1130 final IActivityManager am = ActivityManagerNative.getDefault();
1131 final long identity = Binder.clearCallingIdentity();
1132 try {
1133 am.restartUserInBackground(userId);
1134 } catch (RemoteException re) {
1135 throw re.rethrowAsRuntimeException();
1136 } finally {
1137 Binder.restoreCallingIdentity(identity);
1138 }
1139 }
1140
Bookatz029832a2019-10-04 16:50:22 -07001141 /**
1142 * Returns the user type, e.g. {@link UserManager#USER_TYPE_FULL_GUEST}, of the given userId,
1143 * or null if the user doesn't exist.
1144 */
1145 @Override
1146 public @Nullable String getUserTypeForUser(@UserIdInt int userId) {
1147 // TODO(b/142482943): Decide on the appropriate permission requirements.
1148 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "getUserTypeForUser");
1149 return getUserTypeNoChecks(userId);
1150 }
1151
1152 /**
1153 * Returns the user type of the given userId, or null if the user doesn't exist.
1154 * <p>No permissions checks are made (but userId checks may be made).
1155 */
1156 private @Nullable String getUserTypeNoChecks(@UserIdInt int userId) {
1157 synchronized (mUsersLock) {
1158 final UserInfo userInfo = getUserInfoLU(userId);
1159 return userInfo != null ? userInfo.userType : null;
1160 }
1161 }
1162
1163 /**
1164 * Returns the UserTypeDetails of the given userId's user type, or null if the no such user.
1165 * <p>No permissions checks are made (but userId checks may be made).
1166 */
1167 private @Nullable UserTypeDetails getUserTypeDetailsNoChecks(@UserIdInt int userId) {
1168 final String typeStr = getUserTypeNoChecks(userId);
1169 return typeStr != null ? mUserTypes.get(typeStr) : null;
1170 }
1171
1172 /**
1173 * Returns the UserTypeDetails of the given userInfo's user type (or null for a null userInfo).
1174 */
1175 private @Nullable UserTypeDetails getUserTypeDetails(@Nullable UserInfo userInfo) {
1176 final String typeStr = userInfo != null ? userInfo.userType : null;
1177 return typeStr != null ? mUserTypes.get(typeStr) : null;
1178 }
1179
Alexandra Gherghinadf35d572014-04-09 13:54:39 +01001180 @Override
Bookatzf56f2582019-09-04 16:06:41 -07001181 public UserInfo getUserInfo(@UserIdInt int userId) {
Sudheer Shankaaccaa082016-06-14 16:22:57 -07001182 checkManageOrCreateUsersPermission("query user");
Tony Mak8673b282016-03-21 21:10:59 +00001183 synchronized (mUsersLock) {
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001184 return userWithName(getUserInfoLU(userId));
1185 }
1186 }
1187
1188 /**
1189 * Returns a UserInfo object with the name filled in, for Owner, or the original
1190 * if the name is already set.
1191 */
1192 private UserInfo userWithName(UserInfo orig) {
1193 if (orig != null && orig.name == null && orig.id == UserHandle.USER_SYSTEM) {
1194 UserInfo withName = new UserInfo(orig);
1195 withName.name = getOwnerName();
1196 return withName;
1197 } else {
1198 return orig;
Tony Mak8673b282016-03-21 21:10:59 +00001199 }
1200 }
1201
1202 @Override
Bookatz029832a2019-10-04 16:50:22 -07001203 public boolean hasBadge(@UserIdInt int userId) {
1204 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "hasBadge");
1205 final UserTypeDetails userTypeDetails = getUserTypeDetailsNoChecks(userId);
1206 return userTypeDetails != null && userTypeDetails.hasBadge();
1207 }
1208
1209 @Override
1210 public @StringRes int getUserBadgeLabelResId(@UserIdInt int userId) {
1211 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "getUserBadgeLabelResId");
1212 final UserInfo userInfo = getUserInfoNoChecks(userId);
1213 final UserTypeDetails userTypeDetails = getUserTypeDetails(userInfo);
1214 if (userInfo == null || userTypeDetails == null || !userTypeDetails.hasBadge()) {
1215 Slog.e(LOG_TAG, "Requested badge label for non-badged user " + userId);
1216 return Resources.ID_NULL;
1217 }
1218 final int badgeIndex = userInfo.profileBadge;
1219 return userTypeDetails.getBadgeLabel(badgeIndex);
1220 }
1221
1222 @Override
1223 public @ColorRes int getUserBadgeColorResId(@UserIdInt int userId) {
1224 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "getUserBadgeColorResId");
1225 final UserInfo userInfo = getUserInfoNoChecks(userId);
1226 final UserTypeDetails userTypeDetails = getUserTypeDetails(userInfo);
1227 if (userInfo == null || userTypeDetails == null || !userTypeDetails.hasBadge()) {
1228 Slog.e(LOG_TAG, "Requested badge color for non-badged user " + userId);
1229 return Resources.ID_NULL;
1230 }
1231 final int badgeIndex = userInfo.profileBadge;
1232 return userTypeDetails.getBadgeColor(badgeIndex);
1233 }
1234
1235 @Override
1236 public @DrawableRes int getUserIconBadgeResId(@UserIdInt int userId) {
1237 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "getUserIconBadgeResId");
1238 final UserTypeDetails userTypeDetails = getUserTypeDetailsNoChecks(userId);
1239 if (userTypeDetails == null || !userTypeDetails.hasBadge()) {
1240 Slog.e(LOG_TAG, "Requested icon badge for non-badged user " + userId);
1241 return Resources.ID_NULL;
1242 }
1243 return userTypeDetails.getIconBadge();
1244 }
1245
1246 @Override
1247 public @DrawableRes int getUserBadgeResId(@UserIdInt int userId) {
1248 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "getUserBadgeResId");
1249 final UserTypeDetails userTypeDetails = getUserTypeDetailsNoChecks(userId);
1250 if (userTypeDetails == null || !userTypeDetails.hasBadge()) {
1251 Slog.e(LOG_TAG, "Requested badge for non-badged user " + userId);
1252 return Resources.ID_NULL;
1253 }
1254 return userTypeDetails.getBadgePlain();
1255 }
1256
1257 @Override
1258 public @DrawableRes int getUserBadgeNoBackgroundResId(@UserIdInt int userId) {
1259 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId,
1260 "getUserBadgeNoBackgroundResId");
1261 final UserTypeDetails userTypeDetails = getUserTypeDetailsNoChecks(userId);
1262 if (userTypeDetails == null || !userTypeDetails.hasBadge()) {
1263 Slog.e(LOG_TAG, "Requested badge (no background) for non-badged user " + userId);
1264 return Resources.ID_NULL;
1265 }
1266 return userTypeDetails.getBadgeNoBackground();
1267 }
1268
1269 @Override
1270 public boolean isProfile(@UserIdInt int userId) {
1271 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isProfile");
Kenny Guy02c89902016-11-15 19:36:38 +00001272 synchronized (mUsersLock) {
1273 UserInfo userInfo = getUserInfoLU(userId);
Bookatz029832a2019-10-04 16:50:22 -07001274 return userInfo != null && userInfo.isProfile();
Kenny Guy02c89902016-11-15 19:36:38 +00001275 }
1276 }
1277
1278 @Override
Bookatzf56f2582019-09-04 16:06:41 -07001279 public boolean isManagedProfile(@UserIdInt int userId) {
Jon Miranda2b340a22019-01-25 14:03:49 -08001280 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isManagedProfile");
Fyodor Kupolov82402752015-10-28 14:54:51 -07001281 synchronized (mUsersLock) {
Amith Yamasani1c41dc82016-06-28 16:13:15 -07001282 UserInfo userInfo = getUserInfoLU(userId);
Tony Mak8673b282016-03-21 21:10:59 +00001283 return userInfo != null && userInfo.isManagedProfile();
Amith Yamasani13593602012-03-22 16:16:17 -07001284 }
1285 }
1286
Amith Yamasani71e6c692013-03-24 17:39:28 -07001287 @Override
Bookatzf56f2582019-09-04 16:06:41 -07001288 public boolean isUserUnlockingOrUnlocked(@UserIdInt int userId) {
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08001289 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isUserUnlockingOrUnlocked");
Fyodor Kupolovc413f702016-10-06 17:11:14 -07001290 return mLocalService.isUserUnlockingOrUnlocked(userId);
1291 }
1292
1293 @Override
Bookatzf56f2582019-09-04 16:06:41 -07001294 public boolean isUserUnlocked(@UserIdInt int userId) {
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08001295 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isUserUnlocked");
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07001296 return mLocalService.isUserUnlocked(userId);
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08001297 }
1298
1299 @Override
Bookatzf56f2582019-09-04 16:06:41 -07001300 public boolean isUserRunning(@UserIdInt int userId) {
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08001301 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isUserRunning");
1302 return mLocalService.isUserRunning(userId);
1303 }
1304
Makoto Onuki73dded22017-12-20 13:14:48 +09001305 @Override
Bookatzcde3d922019-03-08 14:30:00 -08001306 public String getUserName() {
1307 if (!hasManageUsersOrPermission(android.Manifest.permission.GET_ACCOUNTS_PRIVILEGED)) {
1308 throw new SecurityException("You need MANAGE_USERS or GET_ACCOUNTS_PRIVILEGED "
1309 + "permissions to: get user name");
1310 }
1311 final int userId = UserHandle.getUserId(Binder.getCallingUid());
1312 synchronized (mUsersLock) {
1313 UserInfo userInfo = userWithName(getUserInfoLU(userId));
1314 return userInfo == null ? "" : userInfo.name;
1315 }
1316 }
1317
1318 @Override
Makoto Onuki73dded22017-12-20 13:14:48 +09001319 public long getUserStartRealtime() {
1320 final int userId = UserHandle.getUserId(Binder.getCallingUid());
1321 synchronized (mUsersLock) {
1322 final UserData user = getUserDataLU(userId);
1323 if (user != null) {
1324 return user.startRealtime;
1325 }
1326 return 0;
1327 }
1328 }
1329
1330 @Override
1331 public long getUserUnlockRealtime() {
1332 synchronized (mUsersLock) {
1333 final UserData user = getUserDataLU(UserHandle.getUserId(Binder.getCallingUid()));
1334 if (user != null) {
1335 return user.unlockRealtime;
1336 }
1337 return 0;
1338 }
1339 }
1340
Bookatzf56f2582019-09-04 16:06:41 -07001341 private void checkManageOrInteractPermIfCallerInOtherProfileGroup(@UserIdInt int userId,
1342 String name) {
Felipe Lemec1ca4412019-09-11 09:23:26 -07001343 final int callingUserId = UserHandle.getCallingUserId();
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08001344 if (callingUserId == userId || isSameProfileGroupNoChecks(callingUserId, userId) ||
1345 hasManageUsersPermission()) {
1346 return;
1347 }
jovanakf24ad492018-05-18 12:15:59 -07001348 if (!hasPermissionGranted(Manifest.permission.INTERACT_ACROSS_USERS,
1349 Binder.getCallingUid())) {
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08001350 throw new SecurityException("You need INTERACT_ACROSS_USERS or MANAGE_USERS permission "
1351 + "to: check " + name);
1352 }
1353 }
1354
1355 @Override
Bookatzf56f2582019-09-04 16:06:41 -07001356 public boolean isDemoUser(@UserIdInt int userId) {
Felipe Lemec1ca4412019-09-11 09:23:26 -07001357 final int callingUserId = UserHandle.getCallingUserId();
Amith Yamasani1c41dc82016-06-28 16:13:15 -07001358 if (callingUserId != userId && !hasManageUsersPermission()) {
1359 throw new SecurityException("You need MANAGE_USERS permission to query if u=" + userId
1360 + " is a demo user");
1361 }
1362 synchronized (mUsersLock) {
1363 UserInfo userInfo = getUserInfoLU(userId);
1364 return userInfo != null && userInfo.isDemo();
1365 }
1366 }
1367
1368 @Override
Felipe Lemec1ca4412019-09-11 09:23:26 -07001369 public boolean isPreCreated(@UserIdInt int userId) {
1370 final int callingUserId = UserHandle.getCallingUserId();
1371 if (callingUserId != userId && !hasManageUsersPermission()) {
1372 throw new SecurityException("You need MANAGE_USERS permission to query if u=" + userId
1373 + " is pre-created");
1374 }
1375 synchronized (mUsersLock) {
1376 UserInfo userInfo = getUserInfoLU(userId);
1377 return userInfo != null && userInfo.preCreated;
1378 }
1379 }
1380
1381 @Override
Amith Yamasani71e6c692013-03-24 17:39:28 -07001382 public boolean isRestricted() {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001383 synchronized (mUsersLock) {
1384 return getUserInfoLU(UserHandle.getCallingUserId()).isRestricted();
Amith Yamasani71e6c692013-03-24 17:39:28 -07001385 }
1386 }
1387
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001388 @Override
Bookatzf56f2582019-09-04 16:06:41 -07001389 public boolean canHaveRestrictedProfile(@UserIdInt int userId) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001390 checkManageUsersPermission("canHaveRestrictedProfile");
Fyodor Kupolov82402752015-10-28 14:54:51 -07001391 synchronized (mUsersLock) {
1392 final UserInfo userInfo = getUserInfoLU(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001393 if (userInfo == null || !userInfo.canHaveProfile()) {
1394 return false;
1395 }
1396 if (!userInfo.isAdmin()) {
1397 return false;
1398 }
Makoto Onukie7927da2015-11-25 10:05:17 -08001399 // restricted profile can be created if there is no DO set and the admin user has no PO;
1400 return !mIsDeviceManaged && !mIsUserManaged.get(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001401 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001402 }
1403
Fyodor Kupolovca177562017-11-09 17:43:01 -08001404 @Override
1405 public boolean hasRestrictedProfiles() {
1406 checkManageUsersPermission("hasRestrictedProfiles");
1407 final int callingUserId = UserHandle.getCallingUserId();
1408 synchronized (mUsersLock) {
1409 final int userSize = mUsers.size();
1410 for (int i = 0; i < userSize; i++) {
1411 UserInfo profile = mUsers.valueAt(i).info;
1412 if (callingUserId != profile.id
1413 && profile.restrictedProfileParentId == callingUserId) {
1414 return true;
1415 }
1416 }
1417 return false;
1418 }
1419 }
1420
Amith Yamasani195263742012-08-21 15:40:12 -07001421 /*
1422 * Should be locked on mUsers before calling this.
1423 */
Andreas Gampe2e8c7672018-07-20 13:01:08 -07001424 @GuardedBy("mUsersLock")
Bookatzf56f2582019-09-04 16:06:41 -07001425 private UserInfo getUserInfoLU(@UserIdInt int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -08001426 final UserData userData = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -07001427 // If it is partial and not in the process of being removed, return as unknown user.
Amith Yamasani12747872015-12-07 14:19:49 -08001428 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001429 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
1430 return null;
1431 }
Amith Yamasani12747872015-12-07 14:19:49 -08001432 return userData != null ? userData.info : null;
1433 }
1434
Andreas Gampe2e8c7672018-07-20 13:01:08 -07001435 @GuardedBy("mUsersLock")
Bookatzf56f2582019-09-04 16:06:41 -07001436 private UserData getUserDataLU(@UserIdInt int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -08001437 final UserData userData = mUsers.get(userId);
1438 // If it is partial and not in the process of being removed, return as unknown user.
1439 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
1440 return null;
1441 }
1442 return userData;
Amith Yamasani195263742012-08-21 15:40:12 -07001443 }
1444
Fyodor Kupolov82402752015-10-28 14:54:51 -07001445 /**
1446 * Obtains {@link #mUsersLock} and return UserInfo from mUsers.
1447 * <p>No permissions checking or any addition checks are made</p>
1448 */
Bookatzf56f2582019-09-04 16:06:41 -07001449 private UserInfo getUserInfoNoChecks(@UserIdInt int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001450 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001451 final UserData userData = mUsers.get(userId);
1452 return userData != null ? userData.info : null;
1453 }
1454 }
1455
1456 /**
1457 * Obtains {@link #mUsersLock} and return UserData from mUsers.
1458 * <p>No permissions checking or any addition checks are made</p>
1459 */
Bookatzf56f2582019-09-04 16:06:41 -07001460 private UserData getUserDataNoChecks(@UserIdInt int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -08001461 synchronized (mUsersLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001462 return mUsers.get(userId);
1463 }
1464 }
1465
Amith Yamasani236b2b52015-08-18 14:32:14 -07001466 /** Called by PackageManagerService */
Bookatzf56f2582019-09-04 16:06:41 -07001467 public boolean exists(@UserIdInt int userId) {
Todd Kennedy0eb97382017-10-03 16:57:22 -07001468 return mLocalService.exists(userId);
Amith Yamasani13593602012-03-22 16:16:17 -07001469 }
1470
Amith Yamasani258848d2012-08-10 17:06:33 -07001471 @Override
Bookatzf56f2582019-09-04 16:06:41 -07001472 public void setUserName(@UserIdInt int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001473 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001474 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -07001475 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001476 UserData userData = getUserDataNoChecks(userId);
1477 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001478 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
1479 return;
1480 }
Amith Yamasani12747872015-12-07 14:19:49 -08001481 if (name != null && !name.equals(userData.info.name)) {
1482 userData.info.name = name;
1483 writeUserLP(userData);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001484 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -07001485 }
1486 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001487 if (changed) {
Bookatzf9368552019-03-14 11:57:09 -07001488 long ident = Binder.clearCallingIdentity();
1489 try {
1490 sendUserInfoChangedBroadcast(userId);
1491 } finally {
1492 Binder.restoreCallingIdentity(ident);
1493 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001494 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001495 }
1496
Amith Yamasani258848d2012-08-10 17:06:33 -07001497 @Override
Bookatzf56f2582019-09-04 16:06:41 -07001498 public void setUserIcon(@UserIdInt int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001499 checkManageUsersPermission("update users");
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01001500 if (hasUserRestriction(UserManager.DISALLOW_SET_USER_ICON, userId)) {
1501 Log.w(LOG_TAG, "Cannot set user icon. DISALLOW_SET_USER_ICON is enabled.");
1502 return;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001503 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01001504 mLocalService.setUserIcon(userId, bitmap);
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001505 }
1506
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01001507
1508
Bookatzf56f2582019-09-04 16:06:41 -07001509 private void sendUserInfoChangedBroadcast(@UserIdInt int userId) {
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001510 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
1511 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
1512 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -07001513 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001514 }
1515
Amith Yamasani258848d2012-08-10 17:06:33 -07001516 @Override
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001517 public ParcelFileDescriptor getUserIcon(int targetUserId) {
Bookatzcde3d922019-03-08 14:30:00 -08001518 if (!hasManageUsersOrPermission(android.Manifest.permission.GET_ACCOUNTS_PRIVILEGED)) {
1519 throw new SecurityException("You need MANAGE_USERS or GET_ACCOUNTS_PRIVILEGED "
1520 + "permissions to: get user icon");
1521 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001522 String iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001523 synchronized (mPackagesLock) {
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001524 UserInfo targetUserInfo = getUserInfoNoChecks(targetUserId);
1525 if (targetUserInfo == null || targetUserInfo.partial) {
1526 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + targetUserId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001527 return null;
1528 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001529
1530 final int callingUserId = UserHandle.getCallingUserId();
1531 final int callingGroupId = getUserInfoNoChecks(callingUserId).profileGroupId;
1532 final int targetGroupId = targetUserInfo.profileGroupId;
1533 final boolean sameGroup = (callingGroupId != UserInfo.NO_PROFILE_GROUP_ID
1534 && callingGroupId == targetGroupId);
1535 if ((callingUserId != targetUserId) && !sameGroup) {
Nicolas Prevot88cc3462014-05-14 14:51:48 +01001536 checkManageUsersPermission("get the icon of a user who is not related");
1537 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001538
1539 if (targetUserInfo.iconPath == null) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001540 return null;
1541 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001542 iconPath = targetUserInfo.iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001543 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001544
1545 try {
1546 return ParcelFileDescriptor.open(
1547 new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
1548 } catch (FileNotFoundException e) {
1549 Log.e(LOG_TAG, "Couldn't find icon file", e);
1550 }
1551 return null;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001552 }
1553
Bookatzf56f2582019-09-04 16:06:41 -07001554 public void makeInitialized(@UserIdInt int userId) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001555 checkManageUsersPermission("makeInitialized");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001556 boolean scheduleWriteUser = false;
Amith Yamasani12747872015-12-07 14:19:49 -08001557 UserData userData;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001558 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001559 userData = mUsers.get(userId);
1560 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001561 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001562 return;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001563 }
Amith Yamasani12747872015-12-07 14:19:49 -08001564 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1565 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001566 scheduleWriteUser = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001567 }
1568 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001569 if (scheduleWriteUser) {
Amith Yamasani12747872015-12-07 14:19:49 -08001570 scheduleWriteUser(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001571 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001572 }
1573
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001574 /**
1575 * If default guest restrictions haven't been initialized yet, add the basic
1576 * restrictions.
1577 */
1578 private void initDefaultGuestRestrictions() {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001579 synchronized (mGuestRestrictions) {
1580 if (mGuestRestrictions.isEmpty()) {
Samuel Tand9453b82016-03-14 15:57:02 -07001581 mGuestRestrictions.putBoolean(UserManager.DISALLOW_CONFIG_WIFI, true);
Fyodor Kupolove04462c2015-11-30 15:02:53 -08001582 mGuestRestrictions.putBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, true);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001583 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
1584 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
1585 }
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001586 }
1587 }
1588
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001589 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301590 public Bundle getDefaultGuestRestrictions() {
1591 checkManageUsersPermission("getDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001592 synchronized (mGuestRestrictions) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301593 return new Bundle(mGuestRestrictions);
1594 }
1595 }
1596
1597 @Override
1598 public void setDefaultGuestRestrictions(Bundle restrictions) {
1599 checkManageUsersPermission("setDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001600 synchronized (mGuestRestrictions) {
1601 mGuestRestrictions.clear();
1602 mGuestRestrictions.putAll(restrictions);
1603 }
1604 synchronized (mPackagesLock) {
1605 writeUserListLP();
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301606 }
1607 }
1608
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001609 /**
Pavel Grafov6a40f092016-10-25 15:46:51 +01001610 * See {@link UserManagerInternal#setDevicePolicyUserRestrictions}
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001611 */
Bookatzf56f2582019-09-04 16:06:41 -07001612 private void setDevicePolicyUserRestrictionsInner(@UserIdInt int userId,
1613 @Nullable Bundle restrictions, boolean isDeviceOwner, int cameraRestrictionScope) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001614 final Bundle global = new Bundle();
1615 final Bundle local = new Bundle();
1616
1617 // Sort restrictions into local and global ensuring they don't overlap.
1618 UserRestrictionsUtils.sortToGlobalAndLocal(restrictions, isDeviceOwner,
1619 cameraRestrictionScope, global, local);
1620
1621 boolean globalChanged, localChanged;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001622 synchronized (mRestrictionsLock) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001623 // Update global and local restrictions if they were changed.
1624 globalChanged = updateRestrictionsIfNeededLR(
1625 userId, global, mDevicePolicyGlobalUserRestrictions);
1626 localChanged = updateRestrictionsIfNeededLR(
1627 userId, local, mDevicePolicyLocalUserRestrictions);
1628
1629 if (isDeviceOwner) {
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001630 // Remember the global restriction owner userId to be able to make a distinction
1631 // in getUserRestrictionSource on who set local policies.
Pavel Grafov6a40f092016-10-25 15:46:51 +01001632 mDeviceOwnerUserId = userId;
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001633 } else {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001634 if (mDeviceOwnerUserId == userId) {
Zoltan Szatmary-Ban8a5536d2016-05-27 17:56:44 +01001635 // When profile owner sets restrictions it passes null global bundle and we
1636 // reset global restriction owner userId.
1637 // This means this user used to have DO, but now the DO is gone and the user
1638 // instead has PO.
Pavel Grafov6a40f092016-10-25 15:46:51 +01001639 mDeviceOwnerUserId = UserHandle.USER_NULL;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001640 }
1641 }
1642 }
1643 if (DBG) {
1644 Log.d(LOG_TAG, "setDevicePolicyUserRestrictions: userId=" + userId
1645 + " global=" + global + (globalChanged ? " (changed)" : "")
1646 + " local=" + local + (localChanged ? " (changed)" : "")
1647 );
1648 }
1649 // Don't call them within the mRestrictionsLock.
1650 synchronized (mPackagesLock) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001651 if (localChanged || globalChanged) {
Amith Yamasani12747872015-12-07 14:19:49 -08001652 writeUserLP(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001653 }
1654 }
1655
1656 synchronized (mRestrictionsLock) {
1657 if (globalChanged) {
1658 applyUserRestrictionsForAllUsersLR();
1659 } else if (localChanged) {
1660 applyUserRestrictionsLR(userId);
1661 }
1662 }
1663 }
1664
Pavel Grafov6a40f092016-10-25 15:46:51 +01001665 /**
1666 * Updates restriction bundle for a given user in a given restriction array. If new bundle is
1667 * empty, record is removed from the array.
1668 * @return whether restrictions bundle is different from the old one.
1669 */
Bookatzf56f2582019-09-04 16:06:41 -07001670 private boolean updateRestrictionsIfNeededLR(@UserIdInt int userId,
1671 @Nullable Bundle restrictions, SparseArray<Bundle> restrictionsArray) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001672 final boolean changed =
1673 !UserRestrictionsUtils.areEqual(restrictionsArray.get(userId), restrictions);
1674 if (changed) {
1675 if (!UserRestrictionsUtils.isEmpty(restrictions)) {
1676 restrictionsArray.put(userId, restrictions);
1677 } else {
1678 restrictionsArray.delete(userId);
1679 }
1680 }
1681 return changed;
1682 }
1683
Makoto Onuki068c54a2015-10-13 14:34:03 -07001684 @GuardedBy("mRestrictionsLock")
Bookatzf56f2582019-09-04 16:06:41 -07001685 private Bundle computeEffectiveUserRestrictionsLR(@UserIdInt int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001686 final Bundle baseRestrictions =
1687 UserRestrictionsUtils.nonNull(mBaseUserRestrictions.get(userId));
Pavel Grafov6a40f092016-10-25 15:46:51 +01001688 final Bundle global = UserRestrictionsUtils.mergeAll(mDevicePolicyGlobalUserRestrictions);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001689 final Bundle local = mDevicePolicyLocalUserRestrictions.get(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001690
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001691 if (UserRestrictionsUtils.isEmpty(global) && UserRestrictionsUtils.isEmpty(local)) {
1692 // Common case first.
1693 return baseRestrictions;
Makoto Onuki068c54a2015-10-13 14:34:03 -07001694 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001695 final Bundle effective = UserRestrictionsUtils.clone(baseRestrictions);
1696 UserRestrictionsUtils.merge(effective, global);
1697 UserRestrictionsUtils.merge(effective, local);
1698
Makoto Onuki068c54a2015-10-13 14:34:03 -07001699 return effective;
1700 }
1701
1702 @GuardedBy("mRestrictionsLock")
Bookatzf56f2582019-09-04 16:06:41 -07001703 private void invalidateEffectiveUserRestrictionsLR(@UserIdInt int userId) {
Makoto Onuki068c54a2015-10-13 14:34:03 -07001704 if (DBG) {
1705 Log.d(LOG_TAG, "invalidateEffectiveUserRestrictions userId=" + userId);
1706 }
1707 mCachedEffectiveUserRestrictions.remove(userId);
1708 }
1709
Bookatzf56f2582019-09-04 16:06:41 -07001710 private Bundle getEffectiveUserRestrictions(@UserIdInt int userId) {
Makoto Onuki068c54a2015-10-13 14:34:03 -07001711 synchronized (mRestrictionsLock) {
1712 Bundle restrictions = mCachedEffectiveUserRestrictions.get(userId);
1713 if (restrictions == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001714 restrictions = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001715 mCachedEffectiveUserRestrictions.put(userId, restrictions);
1716 }
1717 return restrictions;
Amith Yamasani8cd28b52014-06-08 17:54:27 -07001718 }
1719 }
1720
Makoto Onuki068c54a2015-10-13 14:34:03 -07001721 /** @return a specific user restriction that's in effect currently. */
1722 @Override
Bookatzf56f2582019-09-04 16:06:41 -07001723 public boolean hasUserRestriction(String restrictionKey, @UserIdInt int userId) {
Patrick Baumann2f2fd712019-07-31 15:18:53 -07001724 return mLocalService.hasUserRestriction(restrictionKey, userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001725 }
1726
Makoto Onukiacc50462018-02-14 14:13:49 -08001727 /** @return if any user has the given restriction. */
1728 @Override
1729 public boolean hasUserRestrictionOnAnyUser(String restrictionKey) {
1730 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1731 return false;
1732 }
1733 final List<UserInfo> users = getUsers(/* excludeDying= */ true);
1734 for (int i = 0; i < users.size(); i++) {
1735 final int userId = users.get(i).id;
1736 Bundle restrictions = getEffectiveUserRestrictions(userId);
1737 if (restrictions != null && restrictions.getBoolean(restrictionKey)) {
1738 return true;
1739 }
1740 }
1741 return false;
1742 }
1743
Christopher Tate65fb2e42019-10-11 17:00:23 -07001744 @Override
1745 public boolean isSettingRestrictedForUser(String setting, @UserIdInt int userId,
1746 String value, int callingUid) {
1747 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
1748 throw new SecurityException("Non-system caller");
1749 }
1750 return UserRestrictionsUtils.isSettingRestrictedForUser(mContext, setting, userId,
1751 value, callingUid);
1752 }
1753
1754 @Override
1755 public void addUserRestrictionsListener(final IUserRestrictionsListener listener) {
1756 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
1757 throw new SecurityException("Non-system caller");
1758 }
1759
1760 // NOTE: unregistering not supported; only client is the settings provider,
1761 // which installs a single static permanent listener. If that listener goes
1762 // bad it implies the whole system process is going to crash.
1763 mLocalService.addUserRestrictionsListener(
1764 (int userId, Bundle newRestrict, Bundle prevRestrict) -> {
1765 try {
1766 listener.onUserRestrictionsChanged(userId, newRestrict, prevRestrict);
1767 } catch (RemoteException re) {
1768 Slog.e("IUserRestrictionsListener",
1769 "Unable to invoke listener: " + re.getMessage());
1770 }
1771 });
1772 }
1773
Makoto Onuki068c54a2015-10-13 14:34:03 -07001774 /**
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001775 * @hide
1776 *
1777 * Returns who set a user restriction on a user.
1778 * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
1779 * @param restrictionKey the string key representing the restriction
1780 * @param userId the id of the user for whom to retrieve the restrictions.
1781 * @return The source of user restriction. Any combination of
1782 * {@link UserManager#RESTRICTION_NOT_SET},
1783 * {@link UserManager#RESTRICTION_SOURCE_SYSTEM},
1784 * {@link UserManager#RESTRICTION_SOURCE_DEVICE_OWNER}
1785 * and {@link UserManager#RESTRICTION_SOURCE_PROFILE_OWNER}
1786 */
1787 @Override
Bookatzf56f2582019-09-04 16:06:41 -07001788 public int getUserRestrictionSource(String restrictionKey, @UserIdInt int userId) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001789 List<EnforcingUser> enforcingUsers = getUserRestrictionSources(restrictionKey, userId);
1790 // Get "bitwise or" of restriction sources for all enforcing users.
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001791 int result = UserManager.RESTRICTION_NOT_SET;
Pavel Grafov6a40f092016-10-25 15:46:51 +01001792 for (int i = enforcingUsers.size() - 1; i >= 0; i--) {
1793 result |= enforcingUsers.get(i).getUserRestrictionSource();
1794 }
1795 return result;
1796 }
1797
1798 @Override
1799 public List<EnforcingUser> getUserRestrictionSources(
1800 String restrictionKey, @UserIdInt int userId) {
1801 checkManageUsersPermission("getUserRestrictionSource");
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001802
1803 // Shortcut for the most common case
1804 if (!hasUserRestriction(restrictionKey, userId)) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001805 return Collections.emptyList();
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001806 }
1807
Pavel Grafov6a40f092016-10-25 15:46:51 +01001808 final List<EnforcingUser> result = new ArrayList<>();
1809
1810 // Check if it is base restriction.
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001811 if (hasBaseUserRestriction(restrictionKey, userId)) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001812 result.add(new EnforcingUser(
1813 UserHandle.USER_NULL, UserManager.RESTRICTION_SOURCE_SYSTEM));
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001814 }
1815
Pavel Grafov6a40f092016-10-25 15:46:51 +01001816 synchronized (mRestrictionsLock) {
1817 // Check if it is set by profile owner.
1818 Bundle profileOwnerRestrictions = mDevicePolicyLocalUserRestrictions.get(userId);
1819 if (UserRestrictionsUtils.contains(profileOwnerRestrictions, restrictionKey)) {
1820 result.add(getEnforcingUserLocked(userId));
1821 }
1822
1823 // Iterate over all users who enforce global restrictions.
1824 for (int i = mDevicePolicyGlobalUserRestrictions.size() - 1; i >= 0; i--) {
1825 Bundle globalRestrictions = mDevicePolicyGlobalUserRestrictions.valueAt(i);
1826 int profileUserId = mDevicePolicyGlobalUserRestrictions.keyAt(i);
1827 if (UserRestrictionsUtils.contains(globalRestrictions, restrictionKey)) {
1828 result.add(getEnforcingUserLocked(profileUserId));
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001829 }
1830 }
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001831 }
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001832 return result;
1833 }
1834
Andreas Gampea36dc622018-02-05 17:19:22 -08001835 @GuardedBy("mRestrictionsLock")
Pavel Grafov6a40f092016-10-25 15:46:51 +01001836 private EnforcingUser getEnforcingUserLocked(@UserIdInt int userId) {
1837 int source = mDeviceOwnerUserId == userId ? UserManager.RESTRICTION_SOURCE_DEVICE_OWNER
1838 : UserManager.RESTRICTION_SOURCE_PROFILE_OWNER;
1839 return new EnforcingUser(userId, source);
1840 }
1841
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001842 /**
Makoto Onuki068c54a2015-10-13 14:34:03 -07001843 * @return UserRestrictions that are in effect currently. This always returns a new
1844 * {@link Bundle}.
1845 */
Amith Yamasani8cd28b52014-06-08 17:54:27 -07001846 @Override
Bookatzf56f2582019-09-04 16:06:41 -07001847 public Bundle getUserRestrictions(@UserIdInt int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001848 return UserRestrictionsUtils.clone(getEffectiveUserRestrictions(userId));
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001849 }
1850
1851 @Override
Bookatzf56f2582019-09-04 16:06:41 -07001852 public boolean hasBaseUserRestriction(String restrictionKey, @UserIdInt int userId) {
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +00001853 checkManageUsersPermission("hasBaseUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001854 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1855 return false;
1856 }
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +00001857 synchronized (mRestrictionsLock) {
1858 Bundle bundle = mBaseUserRestrictions.get(userId);
1859 return (bundle != null && bundle.getBoolean(restrictionKey, false));
1860 }
1861 }
1862
1863 @Override
Bookatzf56f2582019-09-04 16:06:41 -07001864 public void setUserRestriction(String key, boolean value, @UserIdInt int userId) {
Fyodor Kupolovd4b26042015-07-27 14:30:59 -07001865 checkManageUsersPermission("setUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001866 if (!UserRestrictionsUtils.isValidRestriction(key)) {
1867 return;
1868 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001869 synchronized (mRestrictionsLock) {
1870 // Note we can't modify Bundles stored in mBaseUserRestrictions directly, so create
1871 // a copy.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001872 final Bundle newRestrictions = UserRestrictionsUtils.clone(
1873 mBaseUserRestrictions.get(userId));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001874 newRestrictions.putBoolean(key, value);
1875
Fyodor Kupolov82402752015-10-28 14:54:51 -07001876 updateUserRestrictionsInternalLR(newRestrictions, userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001877 }
1878 }
1879
Makoto Onuki068c54a2015-10-13 14:34:03 -07001880 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001881 * Optionally updating user restrictions, calculate the effective user restrictions and also
1882 * propagate to other services and system settings.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001883 *
Pavel Grafov6a40f092016-10-25 15:46:51 +01001884 * @param newBaseRestrictions User restrictions to set.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001885 * If null, will not update user restrictions and only does the propagation.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001886 * @param userId target user ID.
1887 */
1888 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001889 private void updateUserRestrictionsInternalLR(
Bookatzf56f2582019-09-04 16:06:41 -07001890 @Nullable Bundle newBaseRestrictions, @UserIdInt int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001891 final Bundle prevAppliedRestrictions = UserRestrictionsUtils.nonNull(
1892 mAppliedUserRestrictions.get(userId));
1893
1894 // Update base restrictions.
Pavel Grafov6a40f092016-10-25 15:46:51 +01001895 if (newBaseRestrictions != null) {
1896 // If newBaseRestrictions == the current one, it's probably a bug.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001897 final Bundle prevBaseRestrictions = mBaseUserRestrictions.get(userId);
1898
Pavel Grafov6a40f092016-10-25 15:46:51 +01001899 Preconditions.checkState(prevBaseRestrictions != newBaseRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001900 Preconditions.checkState(mCachedEffectiveUserRestrictions.get(userId)
Pavel Grafov6a40f092016-10-25 15:46:51 +01001901 != newBaseRestrictions);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001902
Pavel Grafov6a40f092016-10-25 15:46:51 +01001903 if (updateRestrictionsIfNeededLR(userId, newBaseRestrictions, mBaseUserRestrictions)) {
Amith Yamasani12747872015-12-07 14:19:49 -08001904 scheduleWriteUser(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001905 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001906 }
1907
Fyodor Kupolov82402752015-10-28 14:54:51 -07001908 final Bundle effective = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001909
Makoto Onuki759a7632015-10-28 16:43:10 -07001910 mCachedEffectiveUserRestrictions.put(userId, effective);
1911
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001912 // Apply the new restrictions.
Makoto Onuki4f160732015-10-27 17:15:38 -07001913 if (DBG) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001914 debug("Applying user restrictions: userId=" + userId
1915 + " new=" + effective + " prev=" + prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001916 }
1917
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001918 if (mAppOpsService != null) { // We skip it until system-ready.
Fyodor Kupolovec30ca32016-06-16 15:09:29 -07001919 mHandler.post(new Runnable() {
1920 @Override
1921 public void run() {
1922 try {
1923 mAppOpsService.setUserRestrictions(effective, mUserRestriconToken, userId);
1924 } catch (RemoteException e) {
1925 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
1926 }
1927 }
1928 });
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001929 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001930
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001931 propagateUserRestrictionsLR(userId, effective, prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001932
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001933 mAppliedUserRestrictions.put(userId, new Bundle(effective));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001934 }
1935
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001936 private void propagateUserRestrictionsLR(final int userId,
Makoto Onukid45a4a22015-11-02 17:17:38 -08001937 Bundle newRestrictions, Bundle prevRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001938 // Note this method doesn't touch any state, meaning it doesn't require mRestrictionsLock
1939 // actually, but we still need some kind of synchronization otherwise we might end up
1940 // calling listeners out-of-order, thus "LR".
1941
1942 if (UserRestrictionsUtils.areEqual(newRestrictions, prevRestrictions)) {
1943 return;
1944 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08001945
1946 final Bundle newRestrictionsFinal = new Bundle(newRestrictions);
1947 final Bundle prevRestrictionsFinal = new Bundle(prevRestrictions);
1948
1949 mHandler.post(new Runnable() {
1950 @Override
1951 public void run() {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07001952 UserRestrictionsUtils.applyUserRestrictions(
1953 mContext, userId, newRestrictionsFinal, prevRestrictionsFinal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001954
Makoto Onukid45a4a22015-11-02 17:17:38 -08001955 final UserRestrictionsListener[] listeners;
1956 synchronized (mUserRestrictionsListeners) {
1957 listeners = new UserRestrictionsListener[mUserRestrictionsListeners.size()];
1958 mUserRestrictionsListeners.toArray(listeners);
1959 }
1960 for (int i = 0; i < listeners.length; i++) {
1961 listeners[i].onUserRestrictionsChanged(userId,
1962 newRestrictionsFinal, prevRestrictionsFinal);
1963 }
Makoto Onukie72f81b2017-03-16 14:08:19 -07001964
1965 final Intent broadcast = new Intent(UserManager.ACTION_USER_RESTRICTIONS_CHANGED)
1966 .setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
1967 mContext.sendBroadcastAsUser(broadcast, UserHandle.of(userId));
Makoto Onukid45a4a22015-11-02 17:17:38 -08001968 }
1969 });
1970 }
1971
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001972 // Package private for the inner class.
Andreas Gampe2e8c7672018-07-20 13:01:08 -07001973 @GuardedBy("mRestrictionsLock")
Bookatzf56f2582019-09-04 16:06:41 -07001974 void applyUserRestrictionsLR(@UserIdInt int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001975 updateUserRestrictionsInternalLR(null, userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001976 }
1977
1978 @GuardedBy("mRestrictionsLock")
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001979 // Package private for the inner class.
1980 void applyUserRestrictionsForAllUsersLR() {
1981 if (DBG) {
1982 debug("applyUserRestrictionsForAllUsersLR");
1983 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001984 // First, invalidate all cached values.
Makoto Onuki4f160732015-10-27 17:15:38 -07001985 mCachedEffectiveUserRestrictions.clear();
1986
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001987 // We don't want to call into ActivityManagerService while taking a lock, so we'll call
Makoto Onuki068c54a2015-10-13 14:34:03 -07001988 // it on a handler.
1989 final Runnable r = new Runnable() {
1990 @Override
1991 public void run() {
1992 // Then get the list of running users.
1993 final int[] runningUsers;
1994 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001995 runningUsers = ActivityManager.getService().getRunningUserIds();
Makoto Onuki068c54a2015-10-13 14:34:03 -07001996 } catch (RemoteException e) {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001997 Log.w(LOG_TAG, "Unable to access ActivityManagerService");
Makoto Onuki068c54a2015-10-13 14:34:03 -07001998 return;
1999 }
2000 // Then re-calculate the effective restrictions and apply, only for running users.
2001 // It's okay if a new user has started after the getRunningUserIds() call,
2002 // because we'll do the same thing (re-calculate the restrictions and apply)
2003 // when we start a user.
Makoto Onuki068c54a2015-10-13 14:34:03 -07002004 synchronized (mRestrictionsLock) {
2005 for (int i = 0; i < runningUsers.length; i++) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002006 applyUserRestrictionsLR(runningUsers[i]);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002007 }
2008 }
2009 }
2010 };
2011 mHandler.post(r);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07002012 }
2013
Amith Yamasani258848d2012-08-10 17:06:33 -07002014 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -07002015 * Check if we've hit the limit of how many users can be created.
2016 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002017 private boolean isUserLimitReached() {
2018 int count;
2019 synchronized (mUsersLock) {
2020 count = getAliveUsersExcludingGuestsCountLU();
2021 }
2022 return count >= UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07002023 }
2024
Bookatz029832a2019-10-04 16:50:22 -07002025 /**
2026 * Returns whether more users of the given type can be added (based on how many users of that
2027 * type already exist).
2028 *
2029 * <p>For checking whether more profiles can be added to a particular parent use
2030 * {@link #canAddMoreProfilesToUser}.
2031 */
2032 private boolean canAddMoreUsersOfType(UserTypeDetails userTypeDetails) {
2033 final int max = userTypeDetails.getMaxAllowed();
2034 if (max == UserTypeDetails.UNLIMITED_NUMBER_OF_USERS) {
2035 return true; // Indicates that there is no max.
2036 }
2037 return getNumberOfUsersOfType(userTypeDetails.getName()) < max;
2038 }
2039
2040 /**
2041 * Gets the number of users of the given user type.
2042 * Does not include users that are about to die.
2043 */
2044 private int getNumberOfUsersOfType(String userType) {
2045 int count = 0;
2046 synchronized (mUsersLock) {
2047 final int size = mUsers.size();
2048 for (int i = 0; i < size; i++) {
2049 final UserInfo user = mUsers.valueAt(i).info;
2050 if (user.userType.equals(userType)
2051 && !user.guestToRemove
2052 && !mRemovingUserIds.get(user.id)
2053 && !user.preCreated) {
2054 count++;
2055 }
2056 }
2057 }
2058 return count;
2059 }
2060
Nicolas Prevot12678a92015-05-13 12:15:03 -07002061 @Override
Bookatzf56f2582019-09-04 16:06:41 -07002062 public boolean canAddMoreManagedProfiles(@UserIdInt int userId, boolean allowedToRemoveOne) {
Bookatz029832a2019-10-04 16:50:22 -07002063 return canAddMoreProfilesToUser(UserManager.USER_TYPE_PROFILE_MANAGED, userId,
2064 allowedToRemoveOne);
2065 }
2066
2067 /** Returns whether more profiles of the given type can be added to the given parent userId. */
2068 @Override
2069 public boolean canAddMoreProfilesToUser(String userType, @UserIdInt int userId,
2070 boolean allowedToRemoveOne) {
2071 checkManageUsersPermission("check if more profiles can be added.");
2072 final UserTypeDetails type = mUserTypes.get(userType);
2073 if (type == null) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07002074 return false;
2075 }
Bookatz029832a2019-10-04 16:50:22 -07002076 // Managed profiles have their own specific rules.
2077 final boolean isManagedProfile = type.isManagedProfile();
2078 if (isManagedProfile) {
2079 if (ActivityManager.isLowRamDeviceStatic()) {
2080 return false;
2081 }
2082 if (!mContext.getPackageManager().hasSystemFeature(
2083 PackageManager.FEATURE_MANAGED_USERS)) {
2084 return false;
2085 }
Fyodor Kupolovb6157992015-06-05 15:32:28 -07002086 }
Bookatz029832a2019-10-04 16:50:22 -07002087 synchronized (mUsersLock) {
2088 // Check if the parent exists and its type is even allowed to have a profile.
Fyodor Kupolov82402752015-10-28 14:54:51 -07002089 UserInfo userInfo = getUserInfoLU(userId);
yuanhao47f9f7c2017-01-18 09:54:45 +08002090 if (userInfo == null || !userInfo.canHaveProfile()) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07002091 return false;
2092 }
Bookatz029832a2019-10-04 16:50:22 -07002093
2094 // Limit the number of profiles that can be created
2095 final int maxUsersOfType = getMaxUsersOfTypePerParent(type);
2096 if (maxUsersOfType != UserTypeDetails.UNLIMITED_NUMBER_OF_USERS) {
2097 final int userTypeCount = getProfileIds(userId, userType, false).length;
2098 final int profilesRemovedCount = userTypeCount > 0 && allowedToRemoveOne ? 1 : 0;
2099 if (userTypeCount - profilesRemovedCount >= maxUsersOfType) {
2100 return false;
2101 }
2102 // Allow creating a managed profile in the special case where there is only one user
2103 if (isManagedProfile) {
2104 int usersCountAfterRemoving = getAliveUsersExcludingGuestsCountLU()
2105 - profilesRemovedCount;
2106 return usersCountAfterRemoving == 1
2107 || usersCountAfterRemoving < UserManager.getMaxSupportedUsers();
2108 }
2109 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07002110 }
Bookatz029832a2019-10-04 16:50:22 -07002111 return true;
Nicolas Prevot12678a92015-05-13 12:15:03 -07002112 }
2113
Andreas Gampe2e8c7672018-07-20 13:01:08 -07002114 @GuardedBy("mUsersLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07002115 private int getAliveUsersExcludingGuestsCountLU() {
Amith Yamasanif584f012014-05-19 17:57:25 -07002116 int aliveUserCount = 0;
2117 final int totalUserCount = mUsers.size();
2118 // Skip over users being removed
2119 for (int i = 0; i < totalUserCount; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002120 UserInfo user = mUsers.valueAt(i).info;
Felipe Lemec1ca4412019-09-11 09:23:26 -07002121 if (!mRemovingUserIds.get(user.id) && !user.isGuest() && !user.preCreated) {
Amith Yamasanif584f012014-05-19 17:57:25 -07002122 aliveUserCount++;
2123 }
2124 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07002125 return aliveUserCount;
Amith Yamasanifaea76f2012-09-11 10:59:48 -07002126 }
2127
2128 /**
Amith Yamasani195263742012-08-21 15:40:12 -07002129 * Enforces that only the system UID or root's UID or apps that have the
Xiaohui Chenb3b92582015-12-07 11:22:13 -08002130 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} and
2131 * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL INTERACT_ACROSS_USERS_FULL}
2132 * permissions can make certain calls to the UserManager.
2133 *
2134 * @param message used as message if SecurityException is thrown
2135 * @throws SecurityException if the caller does not have enough privilege.
2136 */
2137 private static final void checkManageUserAndAcrossUsersFullPermission(String message) {
2138 final int uid = Binder.getCallingUid();
jovanakf24ad492018-05-18 12:15:59 -07002139
2140 if (uid == Process.SYSTEM_UID || uid == 0) {
2141 // System UID or root's UID are granted privilege.
2142 return;
Xiaohui Chenb3b92582015-12-07 11:22:13 -08002143 }
jovanakf24ad492018-05-18 12:15:59 -07002144
2145 if (hasPermissionGranted(Manifest.permission.MANAGE_USERS, uid)
2146 && hasPermissionGranted(Manifest.permission.INTERACT_ACROSS_USERS_FULL, uid)) {
2147 // Apps with both permissions are granted privilege.
2148 return;
2149 }
2150
2151 throw new SecurityException(
2152 "You need MANAGE_USERS and INTERACT_ACROSS_USERS_FULL permission to: " + message);
2153 }
2154
2155 private static boolean hasPermissionGranted(String permission, int uid) {
2156 return ActivityManager.checkComponentPermission(
2157 permission, uid, /* owningUid = */-1, /* exported = */ true) ==
2158 PackageManager.PERMISSION_GRANTED;
Xiaohui Chenb3b92582015-12-07 11:22:13 -08002159 }
2160
2161 /**
2162 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -07002163 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -07002164 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -07002165 *
2166 * @param message used as message if SecurityException is thrown
2167 * @throws SecurityException if the caller is not system or root
Tony Mak4dc008c2016-03-16 10:46:49 +00002168 * @see #hasManageUsersPermission()
Amith Yamasani258848d2012-08-10 17:06:33 -07002169 */
Amith Yamasanibe465322014-04-24 13:45:17 -07002170 private static final void checkManageUsersPermission(String message) {
Tony Mak4dc008c2016-03-16 10:46:49 +00002171 if (!hasManageUsersPermission()) {
Amith Yamasanibe465322014-04-24 13:45:17 -07002172 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
2173 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -04002174 }
2175
Esteban Talavera5b9f1672015-12-11 15:22:34 +00002176 /**
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002177 * Enforces that only the system UID or root's UID or apps that have the
2178 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or
2179 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS}
2180 * can make certain calls to the UserManager.
2181 *
2182 * @param message used as message if SecurityException is thrown
2183 * @throws SecurityException if the caller is not system or root
2184 * @see #hasManageOrCreateUsersPermission()
2185 */
2186 private static final void checkManageOrCreateUsersPermission(String message) {
2187 if (!hasManageOrCreateUsersPermission()) {
2188 throw new SecurityException(
2189 "You either need MANAGE_USERS or CREATE_USERS permission to: " + message);
2190 }
2191 }
2192
2193 /**
2194 * Similar to {@link #checkManageOrCreateUsersPermission(String)} but when the caller is tries
2195 * to create user/profiles other than what is allowed for
2196 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS} permission, then it will only
2197 * allow callers with {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} permission.
2198 */
2199 private static final void checkManageOrCreateUsersPermission(int creationFlags) {
2200 if ((creationFlags & ~ALLOWED_FLAGS_FOR_CREATE_USERS_PERMISSION) == 0) {
2201 if (!hasManageOrCreateUsersPermission()) {
2202 throw new SecurityException("You either need MANAGE_USERS or CREATE_USERS "
2203 + "permission to create an user with flags: " + creationFlags);
2204 }
2205 } else if (!hasManageUsersPermission()) {
2206 throw new SecurityException("You need MANAGE_USERS permission to create an user "
2207 + " with flags: " + creationFlags);
2208 }
2209 }
2210
2211 /**
Tony Mak4dc008c2016-03-16 10:46:49 +00002212 * @return whether the calling UID is system UID or root's UID or the calling app has the
2213 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}.
2214 */
2215 private static final boolean hasManageUsersPermission() {
2216 final int callingUid = Binder.getCallingUid();
2217 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
2218 || callingUid == Process.ROOT_UID
jovanakf24ad492018-05-18 12:15:59 -07002219 || hasPermissionGranted(android.Manifest.permission.MANAGE_USERS, callingUid);
Tony Mak4dc008c2016-03-16 10:46:49 +00002220 }
2221
2222 /**
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002223 * @return whether the calling UID is system UID or root's UID or the calling app has the
Bookatzcde3d922019-03-08 14:30:00 -08002224 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or the provided permission.
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002225 */
Bookatzcde3d922019-03-08 14:30:00 -08002226 private static final boolean hasManageUsersOrPermission(String alternativePermission) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002227 final int callingUid = Binder.getCallingUid();
2228 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
2229 || callingUid == Process.ROOT_UID
jovanakf24ad492018-05-18 12:15:59 -07002230 || hasPermissionGranted(android.Manifest.permission.MANAGE_USERS, callingUid)
Bookatzcde3d922019-03-08 14:30:00 -08002231 || hasPermissionGranted(alternativePermission, callingUid);
2232 }
2233
2234 /**
2235 * @return whether the calling UID is system UID or root's UID or the calling app has the
2236 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or
2237 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS}.
2238 */
2239 private static final boolean hasManageOrCreateUsersPermission() {
2240 return hasManageUsersOrPermission(android.Manifest.permission.CREATE_USERS);
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002241 }
2242
2243 /**
Esteban Talavera5b9f1672015-12-11 15:22:34 +00002244 * Enforces that only the system UID or root's UID (on any user) can make certain calls to the
2245 * UserManager.
2246 *
2247 * @param message used as message if SecurityException is thrown
2248 * @throws SecurityException if the caller is not system or root
2249 */
2250 private static void checkSystemOrRoot(String message) {
2251 final int uid = Binder.getCallingUid();
2252 if (!UserHandle.isSameApp(uid, Process.SYSTEM_UID) && uid != Process.ROOT_UID) {
2253 throw new SecurityException("Only system may: " + message);
2254 }
2255 }
2256
Fyodor Kupolov82402752015-10-28 14:54:51 -07002257 private void writeBitmapLP(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002258 try {
2259 File dir = new File(mUsersDir, Integer.toString(info.id));
2260 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +01002261 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002262 if (!dir.exists()) {
2263 dir.mkdir();
2264 FileUtils.setPermissions(
2265 dir.getPath(),
2266 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
2267 -1, -1);
2268 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07002269 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +01002270 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01002271 && tmp.renameTo(file) && SELinux.restorecon(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -07002272 info.iconPath = file.getAbsolutePath();
2273 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07002274 try {
2275 os.close();
2276 } catch (IOException ioe) {
2277 // What the ... !
2278 }
Adrian Roos1bdff912015-02-17 15:51:35 +01002279 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002280 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002281 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002282 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002283 }
2284
Amith Yamasani0b285492011-04-14 17:35:23 -07002285 /**
2286 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
2287 * cache it elsewhere.
2288 * @return the array of user ids.
2289 */
Dianne Hackborn1676c852012-09-10 14:52:30 -07002290 public int[] getUserIds() {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002291 synchronized (mUsersLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07002292 return mUserIds;
2293 }
Amith Yamasani0b285492011-04-14 17:35:23 -07002294 }
2295
Andreas Gampe2e8c7672018-07-20 13:01:08 -07002296 @GuardedBy({"mRestrictionsLock", "mPackagesLock"})
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002297 private void readUserListLP() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002298 if (!mUserListFile.exists()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002299 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002300 return;
2301 }
2302 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07002303 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002304 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07002305 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002306 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002307 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002308 int type;
2309 while ((type = parser.next()) != XmlPullParser.START_TAG
2310 && type != XmlPullParser.END_DOCUMENT) {
Amith Yamasani12747872015-12-07 14:19:49 -08002311 // Skip
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002312 }
2313
2314 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07002315 Slog.e(LOG_TAG, "Unable to read user list");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002316 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002317 return;
2318 }
2319
Amith Yamasani2a003292012-08-14 18:25:45 -07002320 mNextSerialNumber = -1;
2321 if (parser.getName().equals(TAG_USERS)) {
2322 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
2323 if (lastSerialNumber != null) {
2324 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
2325 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07002326 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
2327 if (versionNumber != null) {
2328 mUserVersion = Integer.parseInt(versionNumber);
2329 }
Amith Yamasani2a003292012-08-14 18:25:45 -07002330 }
2331
Pavel Grafov6a40f092016-10-25 15:46:51 +01002332 // Pre-O global user restriction were stored as a single bundle (as opposed to per-user
2333 // currently), take care of it in case of upgrade.
2334 Bundle oldDevicePolicyGlobalUserRestrictions = null;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002335
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002336 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05302337 if (type == XmlPullParser.START_TAG) {
2338 final String name = parser.getName();
2339 if (name.equals(TAG_USER)) {
2340 String id = parser.getAttributeValue(null, ATTR_ID);
Amith Yamasani6f34b412012-10-22 18:19:27 -07002341
Amith Yamasani12747872015-12-07 14:19:49 -08002342 UserData userData = readUserLP(Integer.parseInt(id));
2343
2344 if (userData != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002345 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002346 mUsers.put(userData.info.id, userData);
2347 if (mNextSerialNumber < 0
2348 || mNextSerialNumber <= userData.info.id) {
2349 mNextSerialNumber = userData.info.id + 1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002350 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05302351 }
Amith Yamasani2a003292012-08-14 18:25:45 -07002352 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05302353 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -08002354 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2355 && type != XmlPullParser.END_TAG) {
2356 if (type == XmlPullParser.START_TAG) {
2357 if (parser.getName().equals(TAG_RESTRICTIONS)) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002358 synchronized (mGuestRestrictions) {
Fyodor Kupoloveafee022017-03-15 17:09:04 -07002359 UserRestrictionsUtils
2360 .readRestrictions(parser, mGuestRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002361 }
Amith Yamasanida0b1682014-11-21 12:58:17 -08002362 }
2363 break;
2364 }
2365 }
Pavel Grafov6a40f092016-10-25 15:46:51 +01002366 } else if (name.equals(TAG_DEVICE_OWNER_USER_ID)
2367 // Legacy name, should only be encountered when upgrading from pre-O.
2368 || name.equals(TAG_GLOBAL_RESTRICTION_OWNER_ID)) {
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01002369 String ownerUserId = parser.getAttributeValue(null, ATTR_ID);
2370 if (ownerUserId != null) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01002371 mDeviceOwnerUserId = Integer.parseInt(ownerUserId);
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01002372 }
Pavel Grafov6a40f092016-10-25 15:46:51 +01002373 } else if (name.equals(TAG_DEVICE_POLICY_RESTRICTIONS)) {
2374 // Should only happen when upgrading from pre-O (version < 7).
2375 oldDevicePolicyGlobalUserRestrictions =
2376 UserRestrictionsUtils.readRestrictions(parser);
Amith Yamasani258848d2012-08-10 17:06:33 -07002377 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002378 }
2379 }
Pavel Grafov6a40f092016-10-25 15:46:51 +01002380
Fyodor Kupolov82402752015-10-28 14:54:51 -07002381 updateUserIds();
Pavel Grafov6a40f092016-10-25 15:46:51 +01002382 upgradeIfNecessaryLP(oldDevicePolicyGlobalUserRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002383 } catch (IOException | XmlPullParserException e) {
2384 fallbackToSingleUserLP();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08002385 } finally {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002386 IoUtils.closeQuietly(fis);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002387 }
2388 }
2389
Amith Yamasani6f34b412012-10-22 18:19:27 -07002390 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -08002391 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Pavel Grafov6a40f092016-10-25 15:46:51 +01002392 * @param oldGlobalUserRestrictions Pre-O global device policy restrictions.
Amith Yamasani6f34b412012-10-22 18:19:27 -07002393 */
Andreas Gampe2e8c7672018-07-20 13:01:08 -07002394 @GuardedBy({"mRestrictionsLock", "mPackagesLock"})
Pavel Grafov6a40f092016-10-25 15:46:51 +01002395 private void upgradeIfNecessaryLP(Bundle oldGlobalUserRestrictions) {
Bookatz029832a2019-10-04 16:50:22 -07002396 upgradeIfNecessaryLP(oldGlobalUserRestrictions, mUserVersion);
2397 }
2398
2399 /**
2400 * Version of {@link #upgradeIfNecessaryLP(Bundle)} that takes in the userVersion for testing
2401 * purposes. For non-tests, use {@link #upgradeIfNecessaryLP(Bundle)}.
2402 */
2403 @GuardedBy({"mRestrictionsLock", "mPackagesLock"})
2404 @VisibleForTesting
2405 void upgradeIfNecessaryLP(Bundle oldGlobalUserRestrictions, int userVersion) {
Bookatz75f0a072019-08-05 14:12:16 -07002406 Set<Integer> userIdsToWrite = new ArraySet<>();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002407 final int originalVersion = mUserVersion;
Amith Yamasani6f34b412012-10-22 18:19:27 -07002408 if (userVersion < 1) {
2409 // Assign a proper name for the owner, if not initialized correctly before
Amith Yamasani12747872015-12-07 14:19:49 -08002410 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
2411 if ("Primary".equals(userData.info.name)) {
2412 userData.info.name =
2413 mContext.getResources().getString(com.android.internal.R.string.owner_name);
Bookatz75f0a072019-08-05 14:12:16 -07002414 userIdsToWrite.add(userData.info.id);
Amith Yamasani6f34b412012-10-22 18:19:27 -07002415 }
2416 userVersion = 1;
2417 }
2418
Amith Yamasanibc9625052012-11-15 14:39:18 -08002419 if (userVersion < 2) {
2420 // Owner should be marked as initialized
Amith Yamasani12747872015-12-07 14:19:49 -08002421 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
2422 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
2423 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
Bookatz75f0a072019-08-05 14:12:16 -07002424 userIdsToWrite.add(userData.info.id);
Amith Yamasanibc9625052012-11-15 14:39:18 -08002425 }
2426 userVersion = 2;
2427 }
2428
Amith Yamasani350962c2013-08-06 11:18:53 -07002429
Amith Yamasani5e486f52013-08-07 11:06:44 -07002430 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -07002431 userVersion = 4;
2432 }
2433
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07002434 if (userVersion < 5) {
2435 initDefaultGuestRestrictions();
2436 userVersion = 5;
2437 }
2438
Fyodor Kupolov1c363152015-09-02 13:27:21 -07002439 if (userVersion < 6) {
2440 final boolean splitSystemUser = UserManager.isSplitSystemUser();
Fyodor Kupolov82402752015-10-28 14:54:51 -07002441 synchronized (mUsersLock) {
2442 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002443 UserData userData = mUsers.valueAt(i);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002444 // In non-split mode, only user 0 can have restricted profiles
Amith Yamasani12747872015-12-07 14:19:49 -08002445 if (!splitSystemUser && userData.info.isRestricted()
2446 && (userData.info.restrictedProfileParentId
2447 == UserInfo.NO_PROFILE_GROUP_ID)) {
2448 userData.info.restrictedProfileParentId = UserHandle.USER_SYSTEM;
Bookatz75f0a072019-08-05 14:12:16 -07002449 userIdsToWrite.add(userData.info.id);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002450 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07002451 }
2452 }
2453 userVersion = 6;
2454 }
2455
Pavel Grafov6a40f092016-10-25 15:46:51 +01002456 if (userVersion < 7) {
2457 // Previously only one user could enforce global restrictions, now it is per-user.
2458 synchronized (mRestrictionsLock) {
2459 if (!UserRestrictionsUtils.isEmpty(oldGlobalUserRestrictions)
2460 && mDeviceOwnerUserId != UserHandle.USER_NULL) {
2461 mDevicePolicyGlobalUserRestrictions.put(
2462 mDeviceOwnerUserId, oldGlobalUserRestrictions);
2463 }
2464 // ENSURE_VERIFY_APPS is now enforced globally even if put by profile owner, so move
2465 // it from local to global bundle for all users who set it.
2466 UserRestrictionsUtils.moveRestriction(UserManager.ENSURE_VERIFY_APPS,
2467 mDevicePolicyLocalUserRestrictions, mDevicePolicyGlobalUserRestrictions
2468 );
2469 }
2470 userVersion = 7;
2471 }
2472
Bookatz75f0a072019-08-05 14:12:16 -07002473 if (userVersion < 8) {
2474 // Added FLAG_FULL and FLAG_SYSTEM flags.
2475 synchronized (mUsersLock) {
2476 UserData userData = mUsers.get(UserHandle.USER_SYSTEM);
2477 userData.info.flags |= UserInfo.FLAG_SYSTEM;
2478 if (!UserManager.isHeadlessSystemUserMode()) {
2479 userData.info.flags |= UserInfo.FLAG_FULL;
2480 }
2481 userIdsToWrite.add(userData.info.id);
2482
2483 // Mark FULL all non-profile users except USER_SYSTEM.
2484 // Start index at 1 since USER_SYSTEM is the smallest userId and we're skipping it.
2485 for (int i = 1; i < mUsers.size(); i++) {
2486 userData = mUsers.valueAt(i);
2487 if ((userData.info.flags & UserInfo.FLAG_MANAGED_PROFILE) == 0) {
2488 userData.info.flags |= UserInfo.FLAG_FULL;
2489 userIdsToWrite.add(userData.info.id);
2490 }
2491 }
2492 }
2493 userVersion = 8;
2494 }
2495
Bookatz029832a2019-10-04 16:50:22 -07002496 if (userVersion < 9) {
2497 // Convert from UserInfo flags to UserTypes. Apply FLAG_PROFILE to FLAG_MANAGED_PROFILE.
2498 synchronized (mUsersLock) {
2499 for (int i = 0; i < mUsers.size(); i++) {
2500 UserData userData = mUsers.valueAt(i);
2501 final int flags = userData.info.flags;
2502 if ((flags & UserInfo.FLAG_SYSTEM) != 0) {
2503 if ((flags & UserInfo.FLAG_FULL) != 0) {
2504 userData.info.userType = UserManager.USER_TYPE_FULL_SYSTEM;
2505 } else {
2506 userData.info.userType = UserManager.USER_TYPE_SYSTEM_HEADLESS;
2507 }
2508 } else {
2509 try {
2510 userData.info.userType = UserInfo.getDefaultUserType(flags);
2511 } catch (IllegalArgumentException e) {
2512 // TODO(b/142482943): What should we do here? Delete user? Crashloop?
2513 throw new IllegalStateException("Cannot upgrade user with flags "
2514 + Integer.toHexString(flags) + " because it doesn't correspond "
2515 + "to a valid user type.", e);
2516 }
2517 }
2518 // OEMs are responsible for their own custom upgrade logic here.
2519
2520 final UserTypeDetails userTypeDetails = mUserTypes.get(userData.info.userType);
2521 if (userTypeDetails == null) {
2522 throw new IllegalStateException(
2523 "Cannot upgrade user with flags " + Integer.toHexString(flags)
2524 + " because " + userData.info.userType + " isn't defined"
2525 + " on this device!");
2526 }
2527 userData.info.flags |= userTypeDetails.getDefaultUserInfoFlags();
2528 userIdsToWrite.add(userData.info.id);
2529 }
2530 }
2531 userVersion = 9;
2532 }
2533
Amith Yamasani6f34b412012-10-22 18:19:27 -07002534 if (userVersion < USER_VERSION) {
2535 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
2536 + USER_VERSION);
2537 } else {
2538 mUserVersion = userVersion;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002539
2540 if (originalVersion < mUserVersion) {
Bookatz75f0a072019-08-05 14:12:16 -07002541 for (int userId : userIdsToWrite) {
2542 UserData userData = getUserDataNoChecks(userId);
2543 if (userData != null) {
2544 writeUserLP(userData);
2545 }
2546 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002547 writeUserListLP();
2548 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07002549 }
2550 }
2551
Andreas Gampe2e8c7672018-07-20 13:01:08 -07002552 @GuardedBy({"mPackagesLock", "mRestrictionsLock"})
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002553 private void fallbackToSingleUserLP() {
Ying Zheng215116f2019-09-11 12:50:09 -07002554 int flags = UserInfo.FLAG_SYSTEM | UserInfo.FLAG_INITIALIZED | UserInfo.FLAG_ADMIN
2555 | UserInfo.FLAG_PRIMARY;
Xiaohui Chen70f6c382015-04-28 14:21:43 -07002556 // Create the system user
Bookatz029832a2019-10-04 16:50:22 -07002557 String systemUserType = UserManager.isHeadlessSystemUserMode() ?
2558 UserManager.USER_TYPE_SYSTEM_HEADLESS : UserManager.USER_TYPE_FULL_SYSTEM;
2559 flags |= mUserTypes.get(systemUserType).getDefaultUserInfoFlags();
2560 UserInfo system = new UserInfo(UserHandle.USER_SYSTEM, null, null, flags, systemUserType);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002561 UserData userData = putUserInfo(system);
Amith Yamasani634cf312012-10-04 17:34:21 -07002562 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -04002563 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -08002564
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05002565 Bundle restrictions = new Bundle();
Mahaver Chopra3d9805d2016-07-07 16:25:05 +01002566 try {
2567 final String[] defaultFirstUserRestrictions = mContext.getResources().getStringArray(
2568 com.android.internal.R.array.config_defaultFirstUserRestrictions);
2569 for (String userRestriction : defaultFirstUserRestrictions) {
2570 if (UserRestrictionsUtils.isValidRestriction(userRestriction)) {
2571 restrictions.putBoolean(userRestriction, true);
2572 }
2573 }
2574 } catch (Resources.NotFoundException e) {
2575 Log.e(LOG_TAG, "Couldn't find resource: config_defaultFirstUserRestrictions", e);
2576 }
2577
Pavel Grafov6a40f092016-10-25 15:46:51 +01002578 if (!restrictions.isEmpty()) {
2579 synchronized (mRestrictionsLock) {
2580 mBaseUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions);
2581 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07002582 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08002583
Fyodor Kupolov82402752015-10-28 14:54:51 -07002584 updateUserIds();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07002585 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002586
Amith Yamasani12747872015-12-07 14:19:49 -08002587 writeUserLP(userData);
Jeff Sharkeycd575992016-03-29 14:12:49 -06002588 writeUserListLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002589 }
2590
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07002591 private String getOwnerName() {
2592 return mContext.getResources().getString(com.android.internal.R.string.owner_name);
2593 }
2594
Bookatz75f0a072019-08-05 14:12:16 -07002595 private void scheduleWriteUser(UserData userData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002596 if (DBG) {
2597 debug("scheduleWriteUser");
2598 }
Makoto Onuki9e935a32015-11-06 14:24:24 -08002599 // No need to wrap it within a lock -- worst case, we'll just post the same message
2600 // twice.
Bookatz75f0a072019-08-05 14:12:16 -07002601 if (!mHandler.hasMessages(WRITE_USER_MSG, userData)) {
2602 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, userData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002603 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
2604 }
2605 }
2606
Amith Yamasani12747872015-12-07 14:19:49 -08002607 private void writeUserLP(UserData userData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002608 if (DBG) {
Amith Yamasani12747872015-12-07 14:19:49 -08002609 debug("writeUserLP " + userData);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002610 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002611 FileOutputStream fos = null;
Amith Yamasani12747872015-12-07 14:19:49 -08002612 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userData.info.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002613 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07002614 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002615 final BufferedOutputStream bos = new BufferedOutputStream(fos);
Kenny Guy02c89902016-11-15 19:36:38 +00002616 writeUserLP(userData, bos);
Amith Yamasani2a003292012-08-14 18:25:45 -07002617 userFile.finishWrite(fos);
2618 } catch (Exception ioe) {
Jeff Sharkeycd575992016-03-29 14:12:49 -06002619 Slog.e(LOG_TAG, "Error writing user info " + userData.info.id, ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -07002620 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002621 }
2622 }
2623
2624 /*
Kenny Guy02c89902016-11-15 19:36:38 +00002625 * Writes the user file in this format:
2626 *
2627 * <user flags="20039023" id="0">
2628 * <name>Primary</name>
2629 * </user>
2630 */
2631 @VisibleForTesting
2632 void writeUserLP(UserData userData, OutputStream os)
2633 throws IOException, XmlPullParserException {
2634 // XmlSerializer serializer = XmlUtils.serializerInstance();
2635 final XmlSerializer serializer = new FastXmlSerializer();
2636 serializer.setOutput(os, StandardCharsets.UTF_8.name());
2637 serializer.startDocument(null, true);
2638 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2639
2640 final UserInfo userInfo = userData.info;
2641 serializer.startTag(null, TAG_USER);
2642 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
2643 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
2644 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Bookatz029832a2019-10-04 16:50:22 -07002645 serializer.attribute(null, ATTR_TYPE, userInfo.userType);
Kenny Guy02c89902016-11-15 19:36:38 +00002646 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
2647 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
2648 Long.toString(userInfo.lastLoggedInTime));
2649 if (userInfo.lastLoggedInFingerprint != null) {
2650 serializer.attribute(null, ATTR_LAST_LOGGED_IN_FINGERPRINT,
2651 userInfo.lastLoggedInFingerprint);
2652 }
2653 if (userInfo.iconPath != null) {
2654 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
2655 }
2656 if (userInfo.partial) {
2657 serializer.attribute(null, ATTR_PARTIAL, "true");
2658 }
Felipe Lemec1ca4412019-09-11 09:23:26 -07002659 if (userInfo.preCreated) {
2660 serializer.attribute(null, ATTR_PRE_CREATED, "true");
2661 }
Kenny Guy02c89902016-11-15 19:36:38 +00002662 if (userInfo.guestToRemove) {
2663 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
2664 }
2665 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
2666 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
2667 Integer.toString(userInfo.profileGroupId));
2668 }
2669 serializer.attribute(null, ATTR_PROFILE_BADGE,
2670 Integer.toString(userInfo.profileBadge));
2671 if (userInfo.restrictedProfileParentId != UserInfo.NO_PROFILE_GROUP_ID) {
2672 serializer.attribute(null, ATTR_RESTRICTED_PROFILE_PARENT_ID,
2673 Integer.toString(userInfo.restrictedProfileParentId));
2674 }
2675 // Write seed data
2676 if (userData.persistSeedData) {
2677 if (userData.seedAccountName != null) {
2678 serializer.attribute(null, ATTR_SEED_ACCOUNT_NAME, userData.seedAccountName);
2679 }
2680 if (userData.seedAccountType != null) {
2681 serializer.attribute(null, ATTR_SEED_ACCOUNT_TYPE, userData.seedAccountType);
2682 }
2683 }
2684 if (userInfo.name != null) {
2685 serializer.startTag(null, TAG_NAME);
2686 serializer.text(userInfo.name);
2687 serializer.endTag(null, TAG_NAME);
2688 }
2689 synchronized (mRestrictionsLock) {
2690 UserRestrictionsUtils.writeRestrictions(serializer,
2691 mBaseUserRestrictions.get(userInfo.id), TAG_RESTRICTIONS);
2692 UserRestrictionsUtils.writeRestrictions(serializer,
2693 mDevicePolicyLocalUserRestrictions.get(userInfo.id),
2694 TAG_DEVICE_POLICY_RESTRICTIONS);
Pavel Grafov6a40f092016-10-25 15:46:51 +01002695 UserRestrictionsUtils.writeRestrictions(serializer,
2696 mDevicePolicyGlobalUserRestrictions.get(userInfo.id),
2697 TAG_DEVICE_POLICY_GLOBAL_RESTRICTIONS);
Kenny Guy02c89902016-11-15 19:36:38 +00002698 }
2699
2700 if (userData.account != null) {
2701 serializer.startTag(null, TAG_ACCOUNT);
2702 serializer.text(userData.account);
2703 serializer.endTag(null, TAG_ACCOUNT);
2704 }
2705
2706 if (userData.persistSeedData && userData.seedAccountOptions != null) {
2707 serializer.startTag(null, TAG_SEED_ACCOUNT_OPTIONS);
2708 userData.seedAccountOptions.saveToXml(serializer);
2709 serializer.endTag(null, TAG_SEED_ACCOUNT_OPTIONS);
2710 }
2711
arangelov9b632d72018-12-07 23:21:22 +00002712 if (userData.getLastRequestQuietModeEnabledMillis() != 0L) {
2713 serializer.startTag(/* namespace */ null, TAG_LAST_REQUEST_QUIET_MODE_ENABLED_CALL);
2714 serializer.text(String.valueOf(userData.getLastRequestQuietModeEnabledMillis()));
2715 serializer.endTag(/* namespace */ null, TAG_LAST_REQUEST_QUIET_MODE_ENABLED_CALL);
2716 }
2717
Kenny Guy02c89902016-11-15 19:36:38 +00002718 serializer.endTag(null, TAG_USER);
2719
2720 serializer.endDocument();
2721 }
2722
2723 /*
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002724 * Writes the user list file in this format:
2725 *
Amith Yamasani2a003292012-08-14 18:25:45 -07002726 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002727 * <user id="0"></user>
2728 * <user id="2"></user>
2729 * </users>
2730 */
Andreas Gampe2e8c7672018-07-20 13:01:08 -07002731 @GuardedBy({"mRestrictionsLock", "mPackagesLock"})
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002732 private void writeUserListLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002733 if (DBG) {
2734 debug("writeUserList");
2735 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002736 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07002737 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002738 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07002739 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002740 final BufferedOutputStream bos = new BufferedOutputStream(fos);
2741
2742 // XmlSerializer serializer = XmlUtils.serializerInstance();
2743 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002744 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002745 serializer.startDocument(null, true);
2746 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2747
2748 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -07002749 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -07002750 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002751
Adam Lesinskieddeb492014-09-08 17:50:03 -07002752 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002753 synchronized (mGuestRestrictions) {
2754 UserRestrictionsUtils
2755 .writeRestrictions(serializer, mGuestRestrictions, TAG_RESTRICTIONS);
2756 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05302757 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Pavel Grafov6a40f092016-10-25 15:46:51 +01002758 serializer.startTag(null, TAG_DEVICE_OWNER_USER_ID);
2759 serializer.attribute(null, ATTR_ID, Integer.toString(mDeviceOwnerUserId));
2760 serializer.endTag(null, TAG_DEVICE_OWNER_USER_ID);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002761 int[] userIdsToWrite;
2762 synchronized (mUsersLock) {
2763 userIdsToWrite = new int[mUsers.size()];
2764 for (int i = 0; i < userIdsToWrite.length; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002765 UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002766 userIdsToWrite[i] = user.id;
2767 }
2768 }
2769 for (int id : userIdsToWrite) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002770 serializer.startTag(null, TAG_USER);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002771 serializer.attribute(null, ATTR_ID, Integer.toString(id));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002772 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002773 }
2774
2775 serializer.endTag(null, TAG_USERS);
2776
2777 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07002778 userListFile.finishWrite(fos);
2779 } catch (Exception e) {
2780 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -07002781 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002782 }
2783 }
2784
Amith Yamasani12747872015-12-07 14:19:49 -08002785 private UserData readUserLP(int id) {
Kenny Guy02c89902016-11-15 19:36:38 +00002786 FileInputStream fis = null;
2787 try {
2788 AtomicFile userFile =
2789 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
2790 fis = userFile.openRead();
2791 return readUserLP(id, fis);
2792 } catch (IOException ioe) {
2793 Slog.e(LOG_TAG, "Error reading user list");
2794 } catch (XmlPullParserException pe) {
2795 Slog.e(LOG_TAG, "Error reading user list");
2796 } finally {
2797 IoUtils.closeQuietly(fis);
2798 }
2799 return null;
2800 }
2801
2802 @VisibleForTesting
2803 UserData readUserLP(int id, InputStream is) throws IOException,
2804 XmlPullParserException {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002805 int flags = 0;
Bookatz029832a2019-10-04 16:50:22 -07002806 String userType = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07002807 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002808 String name = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -08002809 String account = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002810 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -07002811 long creationTime = 0L;
2812 long lastLoggedInTime = 0L;
arangelov9b632d72018-12-07 23:21:22 +00002813 long lastRequestQuietModeEnabledTimestamp = 0L;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002814 String lastLoggedInFingerprint = null;
Kenny Guy2a764942014-04-02 13:29:20 +01002815 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Kenny Guy02c89902016-11-15 19:36:38 +00002816 int profileBadge = 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002817 int restrictedProfileParentId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002818 boolean partial = false;
Felipe Lemec1ca4412019-09-11 09:23:26 -07002819 boolean preCreated = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -07002820 boolean guestToRemove = false;
Amith Yamasani12747872015-12-07 14:19:49 -08002821 boolean persistSeedData = false;
2822 String seedAccountName = null;
2823 String seedAccountType = null;
2824 PersistableBundle seedAccountOptions = null;
Pavel Grafov6a40f092016-10-25 15:46:51 +01002825 Bundle baseRestrictions = null;
2826 Bundle localRestrictions = null;
2827 Bundle globalRestrictions = null;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002828
Kenny Guy02c89902016-11-15 19:36:38 +00002829 XmlPullParser parser = Xml.newPullParser();
2830 parser.setInput(is, StandardCharsets.UTF_8.name());
2831 int type;
2832 while ((type = parser.next()) != XmlPullParser.START_TAG
2833 && type != XmlPullParser.END_DOCUMENT) {
2834 // Skip
2835 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002836
Kenny Guy02c89902016-11-15 19:36:38 +00002837 if (type != XmlPullParser.START_TAG) {
2838 Slog.e(LOG_TAG, "Unable to read user " + id);
2839 return null;
2840 }
2841
2842 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
2843 int storedId = readIntAttribute(parser, ATTR_ID, -1);
2844 if (storedId != id) {
2845 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002846 return null;
2847 }
Kenny Guy02c89902016-11-15 19:36:38 +00002848 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
2849 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Bookatz029832a2019-10-04 16:50:22 -07002850 userType = parser.getAttributeValue(null, ATTR_TYPE);
2851 userType = userType != null ? userType.intern() : null;
Kenny Guy02c89902016-11-15 19:36:38 +00002852 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
2853 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
2854 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
2855 lastLoggedInFingerprint = parser.getAttributeValue(null,
2856 ATTR_LAST_LOGGED_IN_FINGERPRINT);
2857 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
2858 UserInfo.NO_PROFILE_GROUP_ID);
2859 profileBadge = readIntAttribute(parser, ATTR_PROFILE_BADGE, 0);
2860 restrictedProfileParentId = readIntAttribute(parser,
2861 ATTR_RESTRICTED_PROFILE_PARENT_ID, UserInfo.NO_PROFILE_GROUP_ID);
2862 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
2863 if ("true".equals(valueString)) {
2864 partial = true;
2865 }
Felipe Lemec1ca4412019-09-11 09:23:26 -07002866 valueString = parser.getAttributeValue(null, ATTR_PRE_CREATED);
2867 if ("true".equals(valueString)) {
2868 preCreated = true;
2869 }
Kenny Guy02c89902016-11-15 19:36:38 +00002870 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
2871 if ("true".equals(valueString)) {
2872 guestToRemove = true;
2873 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002874
Kenny Guy02c89902016-11-15 19:36:38 +00002875 seedAccountName = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_NAME);
2876 seedAccountType = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_TYPE);
2877 if (seedAccountName != null || seedAccountType != null) {
2878 persistSeedData = true;
2879 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002880
Kenny Guy02c89902016-11-15 19:36:38 +00002881 int outerDepth = parser.getDepth();
2882 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2883 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2884 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2885 continue;
2886 }
2887 String tag = parser.getName();
2888 if (TAG_NAME.equals(tag)) {
2889 type = parser.next();
2890 if (type == XmlPullParser.TEXT) {
2891 name = parser.getText();
2892 }
2893 } else if (TAG_RESTRICTIONS.equals(tag)) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01002894 baseRestrictions = UserRestrictionsUtils.readRestrictions(parser);
Kenny Guy02c89902016-11-15 19:36:38 +00002895 } else if (TAG_DEVICE_POLICY_RESTRICTIONS.equals(tag)) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01002896 localRestrictions = UserRestrictionsUtils.readRestrictions(parser);
2897 } else if (TAG_DEVICE_POLICY_GLOBAL_RESTRICTIONS.equals(tag)) {
2898 globalRestrictions = UserRestrictionsUtils.readRestrictions(parser);
Kenny Guy02c89902016-11-15 19:36:38 +00002899 } else if (TAG_ACCOUNT.equals(tag)) {
2900 type = parser.next();
2901 if (type == XmlPullParser.TEXT) {
2902 account = parser.getText();
2903 }
2904 } else if (TAG_SEED_ACCOUNT_OPTIONS.equals(tag)) {
2905 seedAccountOptions = PersistableBundle.restoreFromXml(parser);
Amith Yamasani12747872015-12-07 14:19:49 -08002906 persistSeedData = true;
arangelov9b632d72018-12-07 23:21:22 +00002907 } else if (TAG_LAST_REQUEST_QUIET_MODE_ENABLED_CALL.equals(tag)) {
2908 type = parser.next();
2909 if (type == XmlPullParser.TEXT) {
2910 lastRequestQuietModeEnabledTimestamp = Long.parseLong(parser.getText());
2911 }
Amith Yamasani12747872015-12-07 14:19:49 -08002912 }
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08002913 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002914 }
Kenny Guy02c89902016-11-15 19:36:38 +00002915
2916 // Create the UserInfo object that gets passed around
Bookatz029832a2019-10-04 16:50:22 -07002917 UserInfo userInfo = new UserInfo(id, name, iconPath, flags, userType);
Kenny Guy02c89902016-11-15 19:36:38 +00002918 userInfo.serialNumber = serialNumber;
2919 userInfo.creationTime = creationTime;
2920 userInfo.lastLoggedInTime = lastLoggedInTime;
2921 userInfo.lastLoggedInFingerprint = lastLoggedInFingerprint;
2922 userInfo.partial = partial;
Felipe Lemec1ca4412019-09-11 09:23:26 -07002923 userInfo.preCreated = preCreated;
Kenny Guy02c89902016-11-15 19:36:38 +00002924 userInfo.guestToRemove = guestToRemove;
2925 userInfo.profileGroupId = profileGroupId;
2926 userInfo.profileBadge = profileBadge;
2927 userInfo.restrictedProfileParentId = restrictedProfileParentId;
2928
2929 // Create the UserData object that's internal to this class
2930 UserData userData = new UserData();
2931 userData.info = userInfo;
2932 userData.account = account;
2933 userData.seedAccountName = seedAccountName;
2934 userData.seedAccountType = seedAccountType;
2935 userData.persistSeedData = persistSeedData;
2936 userData.seedAccountOptions = seedAccountOptions;
arangelov9b632d72018-12-07 23:21:22 +00002937 userData.setLastRequestQuietModeEnabledMillis(lastRequestQuietModeEnabledTimestamp);
Kenny Guy02c89902016-11-15 19:36:38 +00002938
2939 synchronized (mRestrictionsLock) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01002940 if (baseRestrictions != null) {
2941 mBaseUserRestrictions.put(id, baseRestrictions);
2942 }
2943 if (localRestrictions != null) {
2944 mDevicePolicyLocalUserRestrictions.put(id, localRestrictions);
2945 }
2946 if (globalRestrictions != null) {
2947 mDevicePolicyGlobalUserRestrictions.put(id, globalRestrictions);
2948 }
Kenny Guy02c89902016-11-15 19:36:38 +00002949 }
2950 return userData;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002951 }
2952
Amith Yamasani920ace02012-09-20 22:15:37 -07002953 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
2954 String valueString = parser.getAttributeValue(null, attr);
2955 if (valueString == null) return defaultValue;
2956 try {
2957 return Integer.parseInt(valueString);
2958 } catch (NumberFormatException nfe) {
2959 return defaultValue;
2960 }
2961 }
2962
2963 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
2964 String valueString = parser.getAttributeValue(null, attr);
2965 if (valueString == null) return defaultValue;
2966 try {
2967 return Long.parseLong(valueString);
2968 } catch (NumberFormatException nfe) {
2969 return defaultValue;
2970 }
2971 }
2972
Amith Yamasanib82add22013-07-09 11:24:44 -07002973 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002974 * Removes the app restrictions file for a specific package and user id, if it exists.
2975 */
Bookatzf56f2582019-09-04 16:06:41 -07002976 private static void cleanAppRestrictionsForPackageLAr(String pkg, @UserIdInt int userId) {
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07002977 File dir = Environment.getUserSystemDirectory(userId);
2978 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
2979 if (resFile.exists()) {
2980 resFile.delete();
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002981 }
2982 }
2983
Bookatz029832a2019-10-04 16:50:22 -07002984 /**
2985 * Creates a profile user. Used for actual profiles, like
2986 * {@link UserManager#USER_TYPE_PROFILE_MANAGED}, as well as for
2987 * {@link UserManager#USER_TYPE_FULL_RESTRICTED}.
2988 */
Kenny Guya52dc3e2014-02-11 15:33:14 +00002989 @Override
Bookatz029832a2019-10-04 16:50:22 -07002990 public UserInfo createProfileForUser(String name, @NonNull String userType,
2991 @UserInfoFlag int flags, @UserIdInt int userId, @Nullable String[] disallowedPackages) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002992 checkManageOrCreateUsersPermission(flags);
Bookatz029832a2019-10-04 16:50:22 -07002993 return createUserInternal(name, userType, flags, userId, disallowedPackages);
2994 }
2995
2996 /** @see #createProfileForUser */
2997 @Override
2998 public UserInfo createProfileForUserEvenWhenDisallowed(String name, @NonNull String userType,
2999 @UserInfoFlag int flags, @UserIdInt int userId, @Nullable String[] disallowedPackages) {
3000 checkManageOrCreateUsersPermission(flags);
3001 return createUserInternalUnchecked(name, userType, flags, userId,
3002 /* preCreate= */ false, disallowedPackages);
Kenny Guya52dc3e2014-02-11 15:33:14 +00003003 }
3004
Amith Yamasani258848d2012-08-10 17:06:33 -07003005 @Override
Bookatz029832a2019-10-04 16:50:22 -07003006 public UserInfo createUser(String name, @NonNull String userType, @UserInfoFlag int flags) {
Tony Mak6dc428f2016-10-10 15:48:27 +01003007 checkManageOrCreateUsersPermission(flags);
Bookatz029832a2019-10-04 16:50:22 -07003008 return createUserInternal(name, userType, flags, UserHandle.USER_NULL,
3009 /* disallowedPackages= */ null);
Tony Mak6dc428f2016-10-10 15:48:27 +01003010 }
3011
3012 @Override
Bookatz029832a2019-10-04 16:50:22 -07003013 public UserInfo preCreateUser(String userType) {
3014 final UserTypeDetails userTypeDetails = mUserTypes.get(userType);
3015 final int flags = userTypeDetails != null ? userTypeDetails.getDefaultUserInfoFlags() : 0;
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00003016
Felipe Lemec1ca4412019-09-11 09:23:26 -07003017 checkManageOrCreateUsersPermission(flags);
3018
Bookatz029832a2019-10-04 16:50:22 -07003019 Preconditions.checkArgument(isUserTypeEligibleForPreCreation(userTypeDetails),
3020 "cannot pre-create user of type " + userType);
3021 Slog.i(LOG_TAG, "Pre-creating user of type " + userType);
Felipe Lemec1ca4412019-09-11 09:23:26 -07003022
Bookatz029832a2019-10-04 16:50:22 -07003023 return createUserInternalUnchecked(/* name= */ null, userType, flags,
Felipe Lemec1ca4412019-09-11 09:23:26 -07003024 /* parentId= */ UserHandle.USER_NULL, /* preCreate= */ true,
3025 /* disallowedPackages= */ null);
3026 }
3027
Bookatz029832a2019-10-04 16:50:22 -07003028 private UserInfo createUserInternal(@Nullable String name, @NonNull String userType,
3029 @UserInfoFlag int flags, @UserIdInt int parentId,
3030 @Nullable String[] disallowedPackages) {
3031 String restriction = (UserManager.isUserTypeManagedProfile(userType))
Esteban Talavera6c9116a2016-11-24 16:12:44 +00003032 ? UserManager.DISALLOW_ADD_MANAGED_PROFILE
3033 : UserManager.DISALLOW_ADD_USER;
3034 if (hasUserRestriction(restriction, UserHandle.getCallingUserId())) {
3035 Log.w(LOG_TAG, "Cannot add user. " + restriction + " is enabled.");
Julia Reynolds75175022014-06-26 16:35:00 -04003036 return null;
3037 }
Bookatz029832a2019-10-04 16:50:22 -07003038 return createUserInternalUnchecked(name, userType, flags, parentId,
3039 /* preCreate= */ false, disallowedPackages);
Tony Mak6dc428f2016-10-10 15:48:27 +01003040 }
3041
Bookatz029832a2019-10-04 16:50:22 -07003042 private UserInfo createUserInternalUnchecked(@Nullable String name,
3043 @NonNull String userType, @UserInfoFlag int flags, @UserIdInt int parentId,
3044 boolean preCreate, @Nullable String[] disallowedPackages) {
Felipe Lemec1ca4412019-09-11 09:23:26 -07003045 final TimingsTraceAndSlog t = new TimingsTraceAndSlog();
3046 t.traceBegin("createUser-" + flags);
3047 try {
Bookatz029832a2019-10-04 16:50:22 -07003048 return createUserInternalUncheckedNoTracing(name, userType, flags, parentId,
3049 preCreate, disallowedPackages, t);
Felipe Lemec1ca4412019-09-11 09:23:26 -07003050 } finally {
3051 t.traceEnd();
3052 }
jovanakdd7e4752019-09-04 12:35:45 -07003053 }
3054
Felipe Lemec1ca4412019-09-11 09:23:26 -07003055 private UserInfo createUserInternalUncheckedNoTracing(@Nullable String name,
Bookatz029832a2019-10-04 16:50:22 -07003056 @NonNull String userType, @UserInfoFlag int flags, @UserIdInt int parentId,
3057 boolean preCreate, @Nullable String[] disallowedPackages,
3058 @NonNull TimingsTraceAndSlog t) {
3059
3060 final UserTypeDetails userTypeDetails = mUserTypes.get(userType);
3061 if (userTypeDetails == null) {
3062 Slog.e(LOG_TAG, "Cannot create user of invalid user type: " + userType);
3063 return null;
3064 }
3065 userType = userType.intern(); // Now that we know it's valid, we can intern it.
3066 flags |= userTypeDetails.getDefaultUserInfoFlags();
3067 if (!checkUserTypeConsistency(flags)) {
3068 Slog.e(LOG_TAG, "Cannot add user. Flags (" + Integer.toHexString(flags)
3069 + ") and userTypeDetails (" + userType + ") are inconsistent.");
3070 return null;
3071 }
3072 if ((flags & UserInfo.FLAG_SYSTEM) != 0) {
3073 Slog.e(LOG_TAG, "Cannot add user. Flags (" + Integer.toHexString(flags)
3074 + ") indicated SYSTEM user, which cannot be created.");
3075 return null;
3076 }
3077 synchronized (mUsersLock) {
3078 if (mForceEphemeralUsers) {
3079 flags |= UserInfo.FLAG_EPHEMERAL;
3080 }
3081 }
Felipe Lemec1ca4412019-09-11 09:23:26 -07003082
3083 // First try to use a pre-created user (if available).
Bookatz029832a2019-10-04 16:50:22 -07003084 // TODO(b/142482943): Move this to its own function later.
3085 if (!preCreate
3086 && (parentId < 0 && isUserTypeEligibleForPreCreation(userTypeDetails))) {
Felipe Lemec1ca4412019-09-11 09:23:26 -07003087 final UserData preCreatedUserData;
3088 synchronized (mUsersLock) {
Bookatz029832a2019-10-04 16:50:22 -07003089 preCreatedUserData = getPreCreatedUserLU(userType);
Felipe Lemec1ca4412019-09-11 09:23:26 -07003090 }
3091 if (preCreatedUserData != null) {
3092 final UserInfo preCreatedUser = preCreatedUserData.info;
Bookatz029832a2019-10-04 16:50:22 -07003093 final int newFlags = preCreatedUser.flags | flags;
3094 if (!checkUserTypeConsistency(newFlags)) {
3095 Slog.wtf(LOG_TAG, "Cannot reuse pre-created user " + preCreatedUser.id
3096 + " of type " + userType + " because flags are inconsistent. "
3097 + "Flags (" + Integer.toHexString(flags) + "); preCreatedUserFlags ( "
3098 + Integer.toHexString(preCreatedUser.flags) + ").");
3099 } else {
3100 Log.i(LOG_TAG, "Reusing pre-created user " + preCreatedUser.id + " of type "
3101 + userType + " and bestowing on it flags "
3102 + UserInfo.flagsToString(flags));
3103 preCreatedUser.name = name;
3104 preCreatedUser.flags = newFlags;
3105 preCreatedUser.preCreated = false;
3106 preCreatedUser.creationTime = getCreationTime();
3107
3108 dispatchUserAddedIntent(preCreatedUser);
3109 writeUserLP(preCreatedUserData);
3110 writeUserListLP();
3111 return preCreatedUser;
Felipe Lemec1ca4412019-09-11 09:23:26 -07003112 }
Felipe Lemec1ca4412019-09-11 09:23:26 -07003113 }
3114 }
3115
Suprabh Shuklac5e057c2016-08-08 16:22:44 -07003116 DeviceStorageMonitorInternal dsm = LocalServices
3117 .getService(DeviceStorageMonitorInternal.class);
3118 if (dsm.isMemoryLow()) {
3119 Log.w(LOG_TAG, "Cannot add user. Not enough space on disk.");
3120 return null;
3121 }
jovanakdd7e4752019-09-04 12:35:45 -07003122
Bookatz029832a2019-10-04 16:50:22 -07003123 final boolean isProfile = userTypeDetails.isProfile();
3124 final boolean isGuest = UserManager.isUserTypeGuest(userType);
3125 final boolean isRestricted = UserManager.isUserTypeRestricted(userType);
3126 final boolean isDemo = UserManager.isUserTypeDemo(userType);
3127
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07003128 final long ident = Binder.clearCallingIdentity();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003129 UserInfo userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08003130 UserData userData;
Amith Yamasanibb054c92015-07-09 14:16:27 -07003131 final int userId;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07003132 try {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003133 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08003134 UserData parent = null;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003135 if (parentId != UserHandle.USER_NULL) {
3136 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08003137 parent = getUserDataLU(parentId);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00003138 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003139 if (parent == null) return null;
3140 }
Bookatz029832a2019-10-04 16:50:22 -07003141 if (!preCreate && !canAddMoreUsersOfType(userTypeDetails)) {
3142 Log.e(LOG_TAG, "Cannot add more users of type " + userType
3143 + ". Maximum number of that type already exists.");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003144 return null;
3145 }
Bookatz029832a2019-10-04 16:50:22 -07003146 // TODO(b/142482943): Perhaps let the following code apply to restricted users too.
3147 if (isProfile && !canAddMoreProfilesToUser(userType, parentId, false)) {
3148 Log.e(LOG_TAG, "Cannot add more profiles of type " + userType
3149 + " for user " + parentId);
3150 return null;
3151 }
3152 if (!isGuest && !isProfile && !isDemo && isUserLimitReached()) {
3153 // If we're not adding a guest/demo user or a profile and the 'user limit' has
3154 // been reached, cannot add a user.
jovanaka6763a32018-12-03 17:23:20 -08003155 Log.e(LOG_TAG, "Cannot add user. Maximum user limit is reached.");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003156 return null;
3157 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003158 // In legacy mode, restricted profile's parent can only be the owner user
3159 if (isRestricted && !UserManager.isSplitSystemUser()
3160 && (parentId != UserHandle.USER_SYSTEM)) {
3161 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
3162 return null;
3163 }
3164 if (isRestricted && UserManager.isSplitSystemUser()) {
3165 if (parent == null) {
3166 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be "
3167 + "specified");
Nicolas Prevot12678a92015-05-13 12:15:03 -07003168 return null;
3169 }
Amith Yamasani12747872015-12-07 14:19:49 -08003170 if (!parent.info.canHaveProfile()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003171 Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be "
3172 + "created for the specified parent user id " + parentId);
Amith Yamasani95ab7842014-08-11 17:09:26 -07003173 return null;
3174 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003175 }
Ying Zheng215116f2019-09-11 12:50:09 -07003176
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01003177 userId = getNextAvailableId();
3178 Environment.getUserSystemDirectory(userId).mkdirs();
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01003179
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003180 synchronized (mUsersLock) {
Bookatz029832a2019-10-04 16:50:22 -07003181 // Inherit ephemeral flag from parent.
3182 if (parent != null && parent.info.isEphemeral()) {
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01003183 flags |= UserInfo.FLAG_EPHEMERAL;
3184 }
3185
Bookatz029832a2019-10-04 16:50:22 -07003186 userInfo = new UserInfo(userId, name, null, flags, userType);
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01003187 userInfo.serialNumber = mNextSerialNumber++;
Felipe Lemec1ca4412019-09-11 09:23:26 -07003188 userInfo.creationTime = getCreationTime();
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01003189 userInfo.partial = true;
Felipe Lemec1ca4412019-09-11 09:23:26 -07003190 userInfo.preCreated = preCreate;
Fyodor Kupolov83c24242016-03-31 13:30:42 -07003191 userInfo.lastLoggedInFingerprint = Build.FINGERPRINT;
Bookatz029832a2019-10-04 16:50:22 -07003192 if (userTypeDetails.hasBadge() && parentId != UserHandle.USER_NULL) {
3193 userInfo.profileBadge = getFreeProfileBadgeLU(parentId, userType);
Kenny Guy02c89902016-11-15 19:36:38 +00003194 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01003195 userData = new UserData();
3196 userData.info = userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08003197 mUsers.put(userId, userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003198 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06003199 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003200 writeUserListLP();
3201 if (parent != null) {
Bookatz029832a2019-10-04 16:50:22 -07003202 if (isProfile) {
Amith Yamasani12747872015-12-07 14:19:49 -08003203 if (parent.info.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
3204 parent.info.profileGroupId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003205 writeUserLP(parent);
Kenny Guya52dc3e2014-02-11 15:33:14 +00003206 }
Amith Yamasani12747872015-12-07 14:19:49 -08003207 userInfo.profileGroupId = parent.info.profileGroupId;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003208 } else if (isRestricted) {
Amith Yamasani12747872015-12-07 14:19:49 -08003209 if (parent.info.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) {
3210 parent.info.restrictedProfileParentId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003211 writeUserLP(parent);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07003212 }
Amith Yamasani12747872015-12-07 14:19:49 -08003213 userInfo.restrictedProfileParentId = parent.info.restrictedProfileParentId;
Makoto Onuki068c54a2015-10-13 14:34:03 -07003214 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07003215 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07003216 }
jovanakdd7e4752019-09-04 12:35:45 -07003217
3218 t.traceBegin("createUserKey");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003219 final StorageManager storage = mContext.getSystemService(StorageManager.class);
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01003220 storage.createUserKey(userId, userInfo.serialNumber, userInfo.isEphemeral());
jovanakdd7e4752019-09-04 12:35:45 -07003221 t.traceEnd();
3222
3223 t.traceBegin("prepareUserData");
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -08003224 mUserDataPreparer.prepareUserData(userId, userInfo.serialNumber,
Jeff Sharkey47f71082016-02-01 17:03:54 -07003225 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
jovanakdd7e4752019-09-04 12:35:45 -07003226 t.traceEnd();
3227
Bookatz029832a2019-10-04 16:50:22 -07003228 final Set<String> installablePackages = // TODO(b/142482943): use userType
Bookatz04d7ae52019-08-05 14:07:12 -07003229 mSystemPackageInstaller.getInstallablePackagesForUserType(flags);
jovanakdd7e4752019-09-04 12:35:45 -07003230 t.traceBegin("PM.createNewUser");
Bookatz04d7ae52019-08-05 14:07:12 -07003231 mPm.createNewUser(userId, installablePackages, disallowedPackages);
jovanakdd7e4752019-09-04 12:35:45 -07003232 t.traceEnd();
3233
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003234 userInfo.partial = false;
3235 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08003236 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003237 }
3238 updateUserIds();
3239 Bundle restrictions = new Bundle();
Bookatz029832a2019-10-04 16:50:22 -07003240 // TODO(b/142482943): Generalize this using UserTypeDetails default restrictions.
Fyodor Kupolove04462c2015-11-30 15:02:53 -08003241 if (isGuest) {
3242 synchronized (mGuestRestrictions) {
3243 restrictions.putAll(mGuestRestrictions);
3244 }
3245 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003246 synchronized (mRestrictionsLock) {
3247 mBaseUserRestrictions.append(userId, restrictions);
3248 }
jovanakdd7e4752019-09-04 12:35:45 -07003249
3250 t.traceBegin("PM.onNewUserCreated");
Fyodor Kupolov5fd967d2016-07-12 14:46:19 -07003251 mPm.onNewUserCreated(userId);
jovanakdd7e4752019-09-04 12:35:45 -07003252
Felipe Lemec1ca4412019-09-11 09:23:26 -07003253 if (preCreate) {
3254 // Must start user (which will be stopped right away, through
3255 // UserController.finishUserUnlockedCompleted) so services can properly
3256 // intialize it.
Felipe Lemec6e015d2019-10-21 12:51:08 -07003257 // TODO(b/143092698): in the long-term, it might be better to add a onCreateUser()
3258 // callback on SystemService instead.
Felipe Lemec1ca4412019-09-11 09:23:26 -07003259 Slog.i(LOG_TAG, "starting pre-created user " + userInfo.toFullString());
3260 final IActivityManager am = ActivityManager.getService();
3261 try {
3262 am.startUserInBackground(userId);
3263 } catch (RemoteException e) {
3264 Slog.w(LOG_TAG, "could not start pre-created user " + userId, e);
3265 }
3266 } else {
3267 dispatchUserAddedIntent(userInfo);
3268 }
3269
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07003270 } finally {
3271 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07003272 }
Felipe Lemec1ca4412019-09-11 09:23:26 -07003273
Felipe Lemec6e015d2019-10-21 12:51:08 -07003274 // TODO(b/143092698): it's possible to reach "max users overflow" when the user is created
Felipe Lemec1ca4412019-09-11 09:23:26 -07003275 // "from scratch" (i.e., not from a pre-created user) and reaches the maximum number of
3276 // users without counting the pre-created one. Then when the pre-created is converted, the
3277 // "effective" number of max users is exceeds. Example:
3278 // Max: 3 Current: 2 full (u0 and u10) + 1 pre-created (u11)
3279 // Step 1: create(/* flags doesn't match u11 */): u12 is created, "effective max" is now 3
3280 // (u0, u10, u12) but "real" max is 4 (u0, u10, u11, u12)
3281 // Step 2: create(/* flags match u11 */): u11 is converted, now "effective max" is also 4
3282 // (u0, u10, u11, u12)
3283 // One way to avoid this issue is by removing a pre-created user from the pool when the
3284 // "real" max exceeds the max here.
3285
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003286 return userInfo;
3287 }
3288
Bookatz029832a2019-10-04 16:50:22 -07003289 /** Checks that the flags do not contain mutually exclusive types/properties. */
3290 static boolean checkUserTypeConsistency(@UserInfoFlag int flags) {
3291 // Mask to check that flags don't refer to multiple user types.
3292 final int userTypeFlagMask = UserInfo.FLAG_GUEST | UserInfo.FLAG_DEMO
3293 | UserInfo.FLAG_RESTRICTED | UserInfo.FLAG_PROFILE;
3294 return isAtMostOneFlag(flags & userTypeFlagMask)
3295 && isAtMostOneFlag(flags & (UserInfo.FLAG_PROFILE | UserInfo.FLAG_FULL))
3296 && isAtMostOneFlag(flags & (UserInfo.FLAG_PROFILE | UserInfo.FLAG_SYSTEM));
3297 }
3298
3299 /** Returns whether the given flags contains at most one 1. */
3300 private static boolean isAtMostOneFlag(int flags) {
3301 return (flags & (flags - 1)) == 0;
3302 // If !=0, this means that flags is not a power of 2, and therefore is multiple types.
3303 }
3304
Bookatz04d7ae52019-08-05 14:07:12 -07003305 /** Install/uninstall system packages for all users based on their user-type, as applicable. */
3306 boolean installWhitelistedSystemPackages(boolean isFirstBoot, boolean isUpgrade) {
3307 return mSystemPackageInstaller.installWhitelistedSystemPackages(isFirstBoot, isUpgrade);
3308 }
3309
Felipe Lemec1ca4412019-09-11 09:23:26 -07003310 private long getCreationTime() {
3311 final long now = System.currentTimeMillis();
3312 return (now > EPOCH_PLUS_30_YEARS) ? now : 0;
3313 }
3314
3315 private void dispatchUserAddedIntent(@NonNull UserInfo userInfo) {
3316 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
3317 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userInfo.id);
3318 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
3319 android.Manifest.permission.MANAGE_USERS);
3320 MetricsLogger.count(mContext, userInfo.isGuest() ? TRON_GUEST_CREATED
3321 : (userInfo.isDemo() ? TRON_DEMO_CREATED : TRON_USER_CREATED), 1);
3322 }
3323
Felipe Lemec1ca4412019-09-11 09:23:26 -07003324 /**
Bookatz029832a2019-10-04 16:50:22 -07003325 * Gets a pre-created user for the given user type.
Felipe Lemec1ca4412019-09-11 09:23:26 -07003326 *
3327 * <p>Should be used only during user creation, so the pre-created user can be used (instead of
3328 * creating and initializing a new user from scratch).
3329 */
Felipe Lemec6e015d2019-10-21 12:51:08 -07003330 // TODO(b/143092698): add unit test
Felipe Lemec1ca4412019-09-11 09:23:26 -07003331 @GuardedBy("mUsersLock")
Bookatz029832a2019-10-04 16:50:22 -07003332 private @Nullable UserData getPreCreatedUserLU(String userType) {
3333 if (DBG) Slog.d(LOG_TAG, "getPreCreatedUser(): userType= " + userType);
Felipe Lemec1ca4412019-09-11 09:23:26 -07003334 final int userSize = mUsers.size();
3335 for (int i = 0; i < userSize; i++) {
3336 final UserData user = mUsers.valueAt(i);
3337 if (DBG) Slog.d(LOG_TAG, i + ":" + user.info.toFullString());
Bookatz029832a2019-10-04 16:50:22 -07003338 if (user.info.preCreated && user.info.userType.equals(userType)) {
Felipe Lemec1ca4412019-09-11 09:23:26 -07003339 if (!user.info.isInitialized()) {
Bookatz029832a2019-10-04 16:50:22 -07003340 Slog.w(LOG_TAG, "found pre-created user of type " + userType
Felipe Lemec1ca4412019-09-11 09:23:26 -07003341 + ", but it's not initialized yet: " + user.info.toFullString());
3342 continue;
3343 }
3344 return user;
3345 }
3346 }
3347 return null;
3348 }
3349
Bookatz029832a2019-10-04 16:50:22 -07003350 /**
3351 * Returns whether a user with the given userTypeDetails is eligible to be
3352 * {@link UserInfo#preCreated}.
3353 */
3354 private static boolean isUserTypeEligibleForPreCreation(UserTypeDetails userTypeDetails) {
3355 if (userTypeDetails == null) {
3356 return false;
3357 }
3358 return !userTypeDetails.isProfile()
3359 && !userTypeDetails.getName().equals(UserManager.USER_TYPE_FULL_RESTRICTED);
3360 }
3361
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003362 @VisibleForTesting
3363 UserData putUserInfo(UserInfo userInfo) {
3364 final UserData userData = new UserData();
3365 userData.info = userInfo;
3366 synchronized (mUsers) {
3367 mUsers.put(userInfo.id, userData);
3368 }
3369 return userData;
3370 }
3371
3372 @VisibleForTesting
Bookatzf56f2582019-09-04 16:06:41 -07003373 void removeUserInfo(@UserIdInt int userId) {
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003374 synchronized (mUsers) {
3375 mUsers.remove(userId);
3376 }
3377 }
3378
Amith Yamasani0b285492011-04-14 17:35:23 -07003379 /**
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003380 * @hide
3381 */
Amith Yamasani12747872015-12-07 14:19:49 -08003382 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003383 public UserInfo createRestrictedProfile(String name, int parentUserId) {
Sudheer Shanka53d41472016-06-16 09:11:08 -07003384 checkManageOrCreateUsersPermission("setupRestrictedProfile");
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07003385 final UserInfo user = createProfileForUser(
Bookatz029832a2019-10-04 16:50:22 -07003386 name, UserManager.USER_TYPE_FULL_RESTRICTED, 0, parentUserId, null);
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003387 if (user == null) {
3388 return null;
3389 }
Fyodor Kupolov9e912ba2016-02-09 18:29:43 -08003390 long identity = Binder.clearCallingIdentity();
3391 try {
3392 setUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, true, user.id);
3393 // Change the setting before applying the DISALLOW_SHARE_LOCATION restriction, otherwise
3394 // the putIntForUser() will fail.
3395 android.provider.Settings.Secure.putIntForUser(mContext.getContentResolver(),
3396 android.provider.Settings.Secure.LOCATION_MODE,
3397 android.provider.Settings.Secure.LOCATION_MODE_OFF, user.id);
3398 setUserRestriction(UserManager.DISALLOW_SHARE_LOCATION, true, user.id);
3399 } finally {
3400 Binder.restoreCallingIdentity(identity);
3401 }
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003402 return user;
3403 }
3404
3405 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07003406 * Find the current guest user. If the Guest user is partial,
3407 * then do not include it in the results as it is about to die.
Adam Lesinskieddeb492014-09-08 17:50:03 -07003408 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07003409 private UserInfo findCurrentGuestUser() {
3410 synchronized (mUsersLock) {
3411 final int size = mUsers.size();
3412 for (int i = 0; i < size; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003413 final UserInfo user = mUsers.valueAt(i).info;
Felipe Lemee35f5b02019-10-14 15:37:44 -07003414 if (user.isGuest() && !user.guestToRemove && !user.preCreated
3415 && !mRemovingUserIds.get(user.id)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003416 return user;
3417 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07003418 }
3419 }
3420 return null;
3421 }
3422
3423 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07003424 * Mark this guest user for deletion to allow us to create another guest
3425 * and switch to that user before actually removing this guest.
Bookatzf56f2582019-09-04 16:06:41 -07003426 * @param userId the userid of the current guest
Amith Yamasani1df14732014-08-29 21:37:27 -07003427 * @return whether the user could be marked for deletion
3428 */
Amith Yamasani12747872015-12-07 14:19:49 -08003429 @Override
Bookatzf56f2582019-09-04 16:06:41 -07003430 public boolean markGuestForDeletion(@UserIdInt int userId) {
Amith Yamasani1df14732014-08-29 21:37:27 -07003431 checkManageUsersPermission("Only the system can remove users");
3432 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
3433 UserManager.DISALLOW_REMOVE_USER, false)) {
3434 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
3435 return false;
3436 }
3437
3438 long ident = Binder.clearCallingIdentity();
3439 try {
Amith Yamasani12747872015-12-07 14:19:49 -08003440 final UserData userData;
Amith Yamasani1df14732014-08-29 21:37:27 -07003441 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003442 synchronized (mUsersLock) {
Bookatzf56f2582019-09-04 16:06:41 -07003443 userData = mUsers.get(userId);
3444 if (userId == 0 || userData == null || mRemovingUserIds.get(userId)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003445 return false;
3446 }
Amith Yamasani1df14732014-08-29 21:37:27 -07003447 }
Amith Yamasani12747872015-12-07 14:19:49 -08003448 if (!userData.info.isGuest()) {
Amith Yamasani1df14732014-08-29 21:37:27 -07003449 return false;
3450 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07003451 // We set this to a guest user that is to be removed. This is a temporary state
3452 // where we are allowed to add new Guest users, even if this one is still not
3453 // removed. This user will still show up in getUserInfo() calls.
3454 // If we don't get around to removing this Guest user, it will be purged on next
3455 // startup.
Amith Yamasani12747872015-12-07 14:19:49 -08003456 userData.info.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07003457 // Mark it as disabled, so that it isn't returned any more when
3458 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08003459 userData.info.flags |= UserInfo.FLAG_DISABLED;
3460 writeUserLP(userData);
Amith Yamasani1df14732014-08-29 21:37:27 -07003461 }
3462 } finally {
3463 Binder.restoreCallingIdentity(ident);
3464 }
3465 return true;
3466 }
3467
3468 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07003469 * Removes a user and all data directories created for that user. This method should be called
3470 * after the user's processes have been terminated.
Bookatzf56f2582019-09-04 16:06:41 -07003471 * @param userId the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07003472 */
Amith Yamasani12747872015-12-07 14:19:49 -08003473 @Override
Bookatzf56f2582019-09-04 16:06:41 -07003474 public boolean removeUser(@UserIdInt int userId) {
3475 Slog.i(LOG_TAG, "removeUser u" + userId);
Sudheer Shankaf5cea032016-06-08 17:13:24 -07003476 checkManageOrCreateUsersPermission("Only the system can remove users");
Esteban Talavera6c9116a2016-11-24 16:12:44 +00003477
3478 final boolean isManagedProfile;
3479 synchronized (mUsersLock) {
Bookatzf56f2582019-09-04 16:06:41 -07003480 UserInfo userInfo = getUserInfoLU(userId);
Esteban Talavera6c9116a2016-11-24 16:12:44 +00003481 isManagedProfile = userInfo != null && userInfo.isManagedProfile();
3482 }
3483 String restriction = isManagedProfile
3484 ? UserManager.DISALLOW_REMOVE_MANAGED_PROFILE : UserManager.DISALLOW_REMOVE_USER;
3485 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(restriction, false)) {
3486 Log.w(LOG_TAG, "Cannot remove user. " + restriction + " is enabled.");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04003487 return false;
3488 }
Bookatzf56f2582019-09-04 16:06:41 -07003489 return removeUserUnchecked(userId);
Nicolas Prevotdf1b87d2016-10-25 13:57:08 +01003490 }
Julia Reynolds4ac5f852014-06-23 17:38:51 -04003491
Bookatz029832a2019-10-04 16:50:22 -07003492 @Override
3493 public boolean removeUserEvenWhenDisallowed(@UserIdInt int userId) {
3494 checkManageOrCreateUsersPermission("Only the system can remove users");
3495 return removeUserUnchecked(userId);
3496 }
3497
Bookatzf56f2582019-09-04 16:06:41 -07003498 private boolean removeUserUnchecked(@UserIdInt int userId) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01003499 long ident = Binder.clearCallingIdentity();
3500 try {
Amith Yamasani12747872015-12-07 14:19:49 -08003501 final UserData userData;
Fyodor Kupolov0df68cd2015-10-01 13:54:22 -07003502 int currentUser = ActivityManager.getCurrentUser();
Bookatzf56f2582019-09-04 16:06:41 -07003503 if (currentUser == userId) {
jovanaka6763a32018-12-03 17:23:20 -08003504 Log.w(LOG_TAG, "Current user cannot be removed.");
Fyodor Kupolov0df68cd2015-10-01 13:54:22 -07003505 return false;
3506 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01003507 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003508 synchronized (mUsersLock) {
Bookatzf56f2582019-09-04 16:06:41 -07003509 userData = mUsers.get(userId);
3510 if (userId == UserHandle.USER_SYSTEM) {
jovanaka6763a32018-12-03 17:23:20 -08003511 Log.e(LOG_TAG, "System user cannot be removed.");
3512 return false;
3513 }
3514
3515 if (userData == null) {
3516 Log.e(LOG_TAG, String.format(
Bookatzf56f2582019-09-04 16:06:41 -07003517 "Cannot remove user %d, invalid user id provided.", userId));
jovanaka6763a32018-12-03 17:23:20 -08003518 return false;
3519 }
3520
Bookatzf56f2582019-09-04 16:06:41 -07003521 if (mRemovingUserIds.get(userId)) {
jovanaka6763a32018-12-03 17:23:20 -08003522 Log.e(LOG_TAG, String.format(
Bookatzf56f2582019-09-04 16:06:41 -07003523 "User %d is already scheduled for removal.", userId));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003524 return false;
3525 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08003526
Bookatzf56f2582019-09-04 16:06:41 -07003527 addRemovingUserIdLocked(userId);
Fyodor Kupolov82402752015-10-28 14:54:51 -07003528 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08003529
Kenny Guyee58b4f2014-05-23 15:19:53 +01003530 // Set this to a partially created user, so that the user will be purged
3531 // on next startup, in case the runtime stops now before stopping and
3532 // removing the user completely.
Amith Yamasani12747872015-12-07 14:19:49 -08003533 userData.info.partial = true;
Kenny Guyee58b4f2014-05-23 15:19:53 +01003534 // Mark it as disabled, so that it isn't returned any more when
3535 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08003536 userData.info.flags |= UserInfo.FLAG_DISABLED;
3537 writeUserLP(userData);
Kenny Guyee58b4f2014-05-23 15:19:53 +01003538 }
Fyodor Kupolov6c96f7f2017-06-28 18:22:59 -07003539 try {
Bookatzf56f2582019-09-04 16:06:41 -07003540 mAppOpsService.removeUser(userId);
Fyodor Kupolov6c96f7f2017-06-28 18:22:59 -07003541 } catch (RemoteException e) {
jovanaka6763a32018-12-03 17:23:20 -08003542 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user.", e);
Fyodor Kupolov6c96f7f2017-06-28 18:22:59 -07003543 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01003544
Bookatz029832a2019-10-04 16:50:22 -07003545 // TODO(b/142482943): Send some sort of broadcast for profiles even if non-managed?
Amith Yamasani12747872015-12-07 14:19:49 -08003546 if (userData.info.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
3547 && userData.info.isManagedProfile()) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01003548 // Send broadcast to notify system that the user removed was a
3549 // managed user.
Amith Yamasani12747872015-12-07 14:19:49 -08003550 sendProfileRemovedBroadcast(userData.info.profileGroupId, userData.info.id);
Kenny Guyee58b4f2014-05-23 15:19:53 +01003551 }
3552
Bookatzf56f2582019-09-04 16:06:41 -07003553 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userId);
Kenny Guyee58b4f2014-05-23 15:19:53 +01003554 int res;
3555 try {
Bookatzf56f2582019-09-04 16:06:41 -07003556 res = ActivityManager.getService().stopUser(userId, /* force= */ true,
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07003557 new IStopUserCallback.Stub() {
Kenny Guyee58b4f2014-05-23 15:19:53 +01003558 @Override
Bookatzf56f2582019-09-04 16:06:41 -07003559 public void userStopped(int userIdParam) {
3560 finishRemoveUser(userIdParam);
Kenny Guyee58b4f2014-05-23 15:19:53 +01003561 }
3562 @Override
Bookatzf56f2582019-09-04 16:06:41 -07003563 public void userStopAborted(int userIdParam) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01003564 }
3565 });
3566 } catch (RemoteException e) {
jovanaka6763a32018-12-03 17:23:20 -08003567 Log.w(LOG_TAG, "Failed to stop user during removal.", e);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003568 return false;
3569 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01003570 return res == ActivityManager.USER_OP_SUCCESS;
3571 } finally {
3572 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003573 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003574 }
3575
Andreas Gampea36dc622018-02-05 17:19:22 -08003576 @GuardedBy("mUsersLock")
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003577 @VisibleForTesting
Bookatzf56f2582019-09-04 16:06:41 -07003578 void addRemovingUserIdLocked(@UserIdInt int userId) {
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003579 // We remember deleted user IDs to prevent them from being
3580 // reused during the current boot; they can still be reused
3581 // after a reboot or recycling of userIds.
3582 mRemovingUserIds.put(userId, true);
3583 mRecentlyRemovedIds.add(userId);
3584 // Keep LRU queue of recently removed IDs for recycling
3585 if (mRecentlyRemovedIds.size() > MAX_RECENTLY_REMOVED_IDS_SIZE) {
3586 mRecentlyRemovedIds.removeFirst();
3587 }
3588 }
3589
Bookatzf56f2582019-09-04 16:06:41 -07003590 void finishRemoveUser(final @UserIdInt int userId) {
3591 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userId);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07003592 // Let other services shutdown any activity and clean up their state before completely
3593 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07003594 long ident = Binder.clearCallingIdentity();
3595 try {
3596 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
Bookatzf56f2582019-09-04 16:06:41 -07003597 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07003598 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
3599 android.Manifest.permission.MANAGE_USERS,
3600
3601 new BroadcastReceiver() {
3602 @Override
3603 public void onReceive(Context context, Intent intent) {
3604 if (DBG) {
3605 Slog.i(LOG_TAG,
3606 "USER_REMOVED broadcast sent, cleaning up user data "
Bookatzf56f2582019-09-04 16:06:41 -07003607 + userId);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07003608 }
3609 new Thread() {
Amith Yamasani12747872015-12-07 14:19:49 -08003610 @Override
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07003611 public void run() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003612 // Clean up any ActivityTaskManager state
3613 LocalServices.getService(ActivityTaskManagerInternal.class)
Bookatzf56f2582019-09-04 16:06:41 -07003614 .onUserStopped(userId);
3615 removeUserState(userId);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07003616 }
3617 }.start();
3618 }
3619 },
3620
3621 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07003622 } finally {
3623 Binder.restoreCallingIdentity(ident);
3624 }
Amith Yamasani2a003292012-08-14 18:25:45 -07003625 }
3626
Bookatzf56f2582019-09-04 16:06:41 -07003627 private void removeUserState(final @UserIdInt int userId) {
Paul Crowley91293792016-03-25 15:23:07 -07003628 try {
Bookatzf56f2582019-09-04 16:06:41 -07003629 mContext.getSystemService(StorageManager.class).destroyUserKey(userId);
Paul Crowley91293792016-03-25 15:23:07 -07003630 } catch (IllegalStateException e) {
3631 // This may be simply because the user was partially created.
Bookatzf56f2582019-09-04 16:06:41 -07003632 Slog.i(LOG_TAG, "Destroying key for user " + userId + " failed, continuing anyway", e);
Paul Crowley91293792016-03-25 15:23:07 -07003633 }
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06003634
Amith Yamasanid04aaa32016-06-13 12:09:36 -07003635 // Cleanup gatekeeper secure user id
3636 try {
3637 final IGateKeeperService gk = GateKeeper.getService();
3638 if (gk != null) {
Bookatzf56f2582019-09-04 16:06:41 -07003639 gk.clearSecureUserId(userId);
Amith Yamasanid04aaa32016-06-13 12:09:36 -07003640 }
3641 } catch (Exception ex) {
3642 Slog.w(LOG_TAG, "unable to clear GK secure user id");
3643 }
3644
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003645 // Cleanup package manager settings
Bookatzf56f2582019-09-04 16:06:41 -07003646 mPm.cleanUpUser(this, userId);
Amith Yamasanid04aaa32016-06-13 12:09:36 -07003647
3648 // Clean up all data before removing metadata
Bookatzf56f2582019-09-04 16:06:41 -07003649 mUserDataPreparer.destroyUserData(userId,
Amith Yamasanid04aaa32016-06-13 12:09:36 -07003650 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
3651
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003652 // Remove this user from the list
Fyodor Kupolov82402752015-10-28 14:54:51 -07003653 synchronized (mUsersLock) {
Bookatzf56f2582019-09-04 16:06:41 -07003654 mUsers.remove(userId);
3655 mIsUserManaged.delete(userId);
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003656 }
3657 synchronized (mUserStates) {
Bookatzf56f2582019-09-04 16:06:41 -07003658 mUserStates.delete(userId);
Makoto Onukie7927da2015-11-25 10:05:17 -08003659 }
3660 synchronized (mRestrictionsLock) {
Bookatzf56f2582019-09-04 16:06:41 -07003661 mBaseUserRestrictions.remove(userId);
3662 mAppliedUserRestrictions.remove(userId);
3663 mCachedEffectiveUserRestrictions.remove(userId);
3664 mDevicePolicyLocalUserRestrictions.remove(userId);
3665 if (mDevicePolicyGlobalUserRestrictions.get(userId) != null) {
3666 mDevicePolicyGlobalUserRestrictions.remove(userId);
Pavel Grafov6a40f092016-10-25 15:46:51 +01003667 applyUserRestrictionsForAllUsersLR();
3668 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07003669 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003670 // Update the user list
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003671 synchronized (mPackagesLock) {
3672 writeUserListLP();
3673 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06003674 // Remove user file
Bookatzf56f2582019-09-04 16:06:41 -07003675 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userId + XML_SUFFIX));
Jeff Sharkeycd575992016-03-29 14:12:49 -06003676 userFile.delete();
Fyodor Kupolov82402752015-10-28 14:54:51 -07003677 updateUserIds();
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003678 if (RELEASE_DELETED_USER_ID) {
3679 synchronized (mUsers) {
Bookatzf56f2582019-09-04 16:06:41 -07003680 mRemovingUserIds.delete(userId);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003681 }
3682 }
Amith Yamasani61f57372012-08-31 12:12:28 -07003683 }
3684
Kenny Guyf8d3a232014-05-15 16:09:52 +01003685 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01003686 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01003687 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
3688 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01003689 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
Jeff Sharkeyaf6ec292015-12-17 11:19:00 -07003690 managedProfileIntent.putExtra(Intent.EXTRA_USER_HANDLE, removedUserId);
Kenny Guyf8d3a232014-05-15 16:09:52 +01003691 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01003692 }
3693
Amith Yamasani2a003292012-08-14 18:25:45 -07003694 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07003695 public Bundle getApplicationRestrictions(String packageName) {
3696 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
3697 }
3698
3699 @Override
Bookatzf56f2582019-09-04 16:06:41 -07003700 public Bundle getApplicationRestrictionsForUser(String packageName, @UserIdInt int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003701 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07003702 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07003703 checkSystemOrRoot("get application restrictions for other user/app " + packageName);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003704 }
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003705 synchronized (mAppRestrictionsLock) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003706 // Read the restrictions from XML
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003707 return readApplicationRestrictionsLAr(packageName, userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003708 }
3709 }
3710
3711 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07003712 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Bookatzf56f2582019-09-04 16:06:41 -07003713 @UserIdInt int userId) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00003714 checkSystemOrRoot("set application restrictions");
Fyodor Kupolov0d88d542016-04-19 11:37:22 -07003715 if (restrictions != null) {
3716 restrictions.setDefusable(true);
3717 }
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003718 synchronized (mAppRestrictionsLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01003719 if (restrictions == null || restrictions.isEmpty()) {
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003720 cleanAppRestrictionsForPackageLAr(packageName, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01003721 } else {
3722 // Write the restrictions to XML
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003723 writeApplicationRestrictionsLAr(packageName, restrictions, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01003724 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003725 }
Robin Lee66e5d962014-04-09 16:44:21 +01003726
Fyodor Kupolovd2846122016-02-11 18:06:34 -08003727 // Notify package of changes via an intent - only sent to explicitly registered receivers.
3728 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
3729 changeIntent.setPackage(packageName);
3730 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3731 mContext.sendBroadcastAsUser(changeIntent, UserHandle.of(userId));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003732 }
3733
3734 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07003735 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003736 try {
3737 return mContext.getPackageManager().getApplicationInfo(packageName,
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07003738 PackageManager.MATCH_ANY_USER).uid;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003739 } catch (NameNotFoundException nnfe) {
3740 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07003741 } finally {
3742 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003743 }
3744 }
3745
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003746 @GuardedBy("mAppRestrictionsLock")
Bookatzf56f2582019-09-04 16:06:41 -07003747 private static Bundle readApplicationRestrictionsLAr(String packageName,
3748 @UserIdInt int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003749 AtomicFile restrictionsFile =
3750 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
3751 packageToRestrictionsFileName(packageName)));
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003752 return readApplicationRestrictionsLAr(restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003753 }
3754
3755 @VisibleForTesting
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003756 @GuardedBy("mAppRestrictionsLock")
3757 static Bundle readApplicationRestrictionsLAr(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07003758 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003759 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07003760 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07003761 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07003762 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003763
3764 FileInputStream fis = null;
3765 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003766 fis = restrictionsFile.openRead();
3767 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01003768 parser.setInput(fis, StandardCharsets.UTF_8.name());
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003769 XmlUtils.nextElement(parser);
3770 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003771 Slog.e(LOG_TAG, "Unable to read restrictions file "
3772 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07003773 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003774 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003775 while (parser.next() != XmlPullParser.END_DOCUMENT) {
3776 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003777 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003778 } catch (IOException|XmlPullParserException e) {
3779 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003780 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003781 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003782 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07003783 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003784 }
3785
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003786 private static void readEntry(Bundle restrictions, ArrayList<String> values,
3787 XmlPullParser parser) throws XmlPullParserException, IOException {
3788 int type = parser.getEventType();
3789 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
3790 String key = parser.getAttributeValue(null, ATTR_KEY);
3791 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
3792 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
3793 if (multiple != null) {
3794 values.clear();
3795 int count = Integer.parseInt(multiple);
3796 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
3797 if (type == XmlPullParser.START_TAG
3798 && parser.getName().equals(TAG_VALUE)) {
3799 values.add(parser.nextText().trim());
3800 count--;
3801 }
3802 }
3803 String [] valueStrings = new String[values.size()];
3804 values.toArray(valueStrings);
3805 restrictions.putStringArray(key, valueStrings);
3806 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
3807 restrictions.putBundle(key, readBundleEntry(parser, values));
3808 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
3809 final int outerDepth = parser.getDepth();
3810 ArrayList<Bundle> bundleList = new ArrayList<>();
3811 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
3812 Bundle childBundle = readBundleEntry(parser, values);
3813 bundleList.add(childBundle);
3814 }
3815 restrictions.putParcelableArray(key,
3816 bundleList.toArray(new Bundle[bundleList.size()]));
3817 } else {
3818 String value = parser.nextText().trim();
3819 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
3820 restrictions.putBoolean(key, Boolean.parseBoolean(value));
3821 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
3822 restrictions.putInt(key, Integer.parseInt(value));
3823 } else {
3824 restrictions.putString(key, value);
3825 }
3826 }
3827 }
3828 }
3829
3830 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
3831 throws IOException, XmlPullParserException {
3832 Bundle childBundle = new Bundle();
3833 final int outerDepth = parser.getDepth();
3834 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
3835 readEntry(childBundle, values, parser);
3836 }
3837 return childBundle;
3838 }
3839
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003840 @GuardedBy("mAppRestrictionsLock")
3841 private static void writeApplicationRestrictionsLAr(String packageName,
Bookatzf56f2582019-09-04 16:06:41 -07003842 Bundle restrictions, @UserIdInt int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003843 AtomicFile restrictionsFile = new AtomicFile(
3844 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07003845 packageToRestrictionsFileName(packageName)));
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003846 writeApplicationRestrictionsLAr(restrictions, restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003847 }
3848
3849 @VisibleForTesting
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003850 @GuardedBy("mAppRestrictionsLock")
3851 static void writeApplicationRestrictionsLAr(Bundle restrictions, AtomicFile restrictionsFile) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003852 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003853 try {
3854 fos = restrictionsFile.startWrite();
3855 final BufferedOutputStream bos = new BufferedOutputStream(fos);
3856
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003857 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01003858 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003859 serializer.startDocument(null, true);
3860 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
3861
3862 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003863 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003864 serializer.endTag(null, TAG_RESTRICTIONS);
3865
3866 serializer.endDocument();
3867 restrictionsFile.finishWrite(fos);
3868 } catch (Exception e) {
3869 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003870 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
3871 }
3872 }
3873
3874 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
3875 throws IOException {
3876 for (String key : restrictions.keySet()) {
3877 Object value = restrictions.get(key);
3878 serializer.startTag(null, TAG_ENTRY);
3879 serializer.attribute(null, ATTR_KEY, key);
3880
3881 if (value instanceof Boolean) {
3882 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
3883 serializer.text(value.toString());
3884 } else if (value instanceof Integer) {
3885 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
3886 serializer.text(value.toString());
3887 } else if (value == null || value instanceof String) {
3888 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
3889 serializer.text(value != null ? (String) value : "");
3890 } else if (value instanceof Bundle) {
3891 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
3892 writeBundle((Bundle) value, serializer);
3893 } else if (value instanceof Parcelable[]) {
3894 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
3895 Parcelable[] array = (Parcelable[]) value;
3896 for (Parcelable parcelable : array) {
3897 if (!(parcelable instanceof Bundle)) {
3898 throw new IllegalArgumentException("bundle-array can only hold Bundles");
3899 }
3900 serializer.startTag(null, TAG_ENTRY);
3901 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
3902 writeBundle((Bundle) parcelable, serializer);
3903 serializer.endTag(null, TAG_ENTRY);
3904 }
3905 } else {
3906 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
3907 String[] values = (String[]) value;
3908 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
3909 for (String choice : values) {
3910 serializer.startTag(null, TAG_VALUE);
3911 serializer.text(choice != null ? choice : "");
3912 serializer.endTag(null, TAG_VALUE);
3913 }
3914 }
3915 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003916 }
3917 }
3918
3919 @Override
Bookatzf56f2582019-09-04 16:06:41 -07003920 public int getUserSerialNumber(@UserIdInt int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003921 synchronized (mUsersLock) {
Bookatzf56f2582019-09-04 16:06:41 -07003922 final UserInfo userInfo = getUserInfoLU(userId);
Pavel Grafov9c295d42019-03-26 19:42:08 +00003923 return userInfo != null ? userInfo.serialNumber : -1;
Amith Yamasani2a003292012-08-14 18:25:45 -07003924 }
3925 }
3926
3927 @Override
Bookatzf56f2582019-09-04 16:06:41 -07003928 public boolean isUserNameSet(@UserIdInt int userId) {
Fyodor Kupolov605b12a2017-05-10 15:58:09 -07003929 synchronized (mUsersLock) {
Bookatzf56f2582019-09-04 16:06:41 -07003930 final UserInfo userInfo = getUserInfoLU(userId);
Fyodor Kupolov605b12a2017-05-10 15:58:09 -07003931 return userInfo != null && userInfo.name != null;
3932 }
3933 }
3934
3935 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07003936 public int getUserHandle(int userSerialNumber) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003937 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07003938 for (int userId : mUserIds) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003939 UserInfo info = getUserInfoLU(userId);
Kenny Guy945f8832015-02-10 15:17:26 +00003940 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07003941 }
3942 // Not found
3943 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07003944 }
3945 }
3946
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003947 @Override
Bookatzf56f2582019-09-04 16:06:41 -07003948 public long getUserCreationTime(@UserIdInt int userId) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003949 int callingUserId = UserHandle.getCallingUserId();
3950 UserInfo userInfo = null;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003951 synchronized (mUsersLock) {
Bookatzf56f2582019-09-04 16:06:41 -07003952 if (callingUserId == userId) {
3953 userInfo = getUserInfoLU(userId);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003954 } else {
Bookatzf56f2582019-09-04 16:06:41 -07003955 UserInfo parent = getProfileParentLU(userId);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003956 if (parent != null && parent.id == callingUserId) {
Bookatzf56f2582019-09-04 16:06:41 -07003957 userInfo = getUserInfoLU(userId);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003958 }
3959 }
3960 }
3961 if (userInfo == null) {
Bookatzf56f2582019-09-04 16:06:41 -07003962 throw new SecurityException("userId can only be the calling user or a managed "
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003963 + "profile associated with this user");
3964 }
3965 return userInfo.creationTime;
3966 }
3967
Amith Yamasani0b285492011-04-14 17:35:23 -07003968 /**
3969 * Caches the list of user ids in an array, adjusting the array size when necessary.
3970 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07003971 private void updateUserIds() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003972 int num = 0;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003973 synchronized (mUsersLock) {
3974 final int userSize = mUsers.size();
3975 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003976 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003977 num++;
3978 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003979 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07003980 final int[] newUsers = new int[num];
3981 int n = 0;
3982 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003983 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003984 newUsers[n++] = mUsers.keyAt(i);
3985 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003986 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07003987 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07003988 }
3989 }
3990
3991 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003992 * Called right before a user is started. This gives us a chance to prepare
3993 * app storage and apply any user restrictions.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003994 */
Bookatzf56f2582019-09-04 16:06:41 -07003995 public void onBeforeStartUser(@UserIdInt int userId) {
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003996 UserInfo userInfo = getUserInfo(userId);
3997 if (userInfo == null) {
3998 return;
3999 }
Felipe Leme3aad1be2019-05-31 11:43:12 -07004000 TimingsTraceAndSlog t = new TimingsTraceAndSlog();
4001 t.traceBegin("onBeforeStartUser-" + userId);
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07004002 final int userSerial = userInfo.serialNumber;
4003 // Migrate only if build fingerprints mismatch
4004 boolean migrateAppsData = !Build.FINGERPRINT.equals(userInfo.lastLoggedInFingerprint);
Felipe Leme3aad1be2019-05-31 11:43:12 -07004005 t.traceBegin("prepareUserData");
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -08004006 mUserDataPreparer.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_DE);
Felipe Leme3aad1be2019-05-31 11:43:12 -07004007 t.traceEnd();
4008 t.traceBegin("reconcileAppsData");
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07004009 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_DE, migrateAppsData);
Felipe Leme3aad1be2019-05-31 11:43:12 -07004010 t.traceEnd();
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07004011
4012 if (userId != UserHandle.USER_SYSTEM) {
Felipe Leme3aad1be2019-05-31 11:43:12 -07004013 t.traceBegin("applyUserRestrictions");
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07004014 synchronized (mRestrictionsLock) {
4015 applyUserRestrictionsLR(userId);
4016 }
Felipe Leme3aad1be2019-05-31 11:43:12 -07004017 t.traceEnd();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08004018 }
Felipe Leme3aad1be2019-05-31 11:43:12 -07004019 t.traceEnd(); // onBeforeStartUser
Makoto Onuki1a2cd742015-11-16 13:51:27 -08004020 }
4021
4022 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07004023 * Called right before a user is unlocked. This gives us a chance to prepare
4024 * app storage.
4025 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06004026 public void onBeforeUnlockUser(@UserIdInt int userId) {
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07004027 UserInfo userInfo = getUserInfo(userId);
4028 if (userInfo == null) {
4029 return;
4030 }
4031 final int userSerial = userInfo.serialNumber;
4032 // Migrate only if build fingerprints mismatch
4033 boolean migrateAppsData = !Build.FINGERPRINT.equals(userInfo.lastLoggedInFingerprint);
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -08004034 mUserDataPreparer.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_CE);
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07004035 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_CE, migrateAppsData);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07004036 }
4037
4038 /**
Fyodor Kupolov50979d12017-01-27 17:36:32 -08004039 * Examine all users present on given mounted volume, and destroy data
4040 * belonging to users that are no longer valid, or whose user ID has been
4041 * recycled.
4042 */
4043 void reconcileUsers(String volumeUuid) {
4044 mUserDataPreparer.reconcileUsers(volumeUuid, getUsers(true /* excludeDying */));
4045 }
4046
4047 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07004048 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasanieb437d42016-04-29 09:31:25 -07004049 * This is called with ActivityManagerService lock held.
Amith Yamasani920ace02012-09-20 22:15:37 -07004050 * @param userId the user that was just foregrounded
4051 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06004052 public void onUserLoggedIn(@UserIdInt int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -08004053 UserData userData = getUserDataNoChecks(userId);
4054 if (userData == null || userData.info.partial) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08004055 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
4056 return;
4057 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06004058
4059 final long now = System.currentTimeMillis();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08004060 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani12747872015-12-07 14:19:49 -08004061 userData.info.lastLoggedInTime = now;
Amith Yamasani920ace02012-09-20 22:15:37 -07004062 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06004063 userData.info.lastLoggedInFingerprint = Build.FINGERPRINT;
4064 scheduleWriteUser(userData);
Amith Yamasani920ace02012-09-20 22:15:37 -07004065 }
4066
4067 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07004068 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani0b285492011-04-14 17:35:23 -07004069 */
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07004070 @VisibleForTesting
4071 int getNextAvailableId() {
4072 int nextId;
Fyodor Kupolov82402752015-10-28 14:54:51 -07004073 synchronized (mUsersLock) {
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07004074 nextId = scanNextAvailableIdLocked();
4075 if (nextId >= 0) {
4076 return nextId;
4077 }
4078 // All ids up to MAX_USER_ID were used. Remove all mRemovingUserIds,
4079 // except most recently removed
4080 if (mRemovingUserIds.size() > 0) {
4081 Slog.i(LOG_TAG, "All available IDs are used. Recycling LRU ids.");
4082 mRemovingUserIds.clear();
4083 for (Integer recentlyRemovedId : mRecentlyRemovedIds) {
4084 mRemovingUserIds.put(recentlyRemovedId, true);
Amith Yamasani195263742012-08-21 15:40:12 -07004085 }
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07004086 nextId = scanNextAvailableIdLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07004087 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07004088 }
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07004089 if (nextId < 0) {
4090 throw new IllegalStateException("No user id available!");
4091 }
4092 return nextId;
4093 }
4094
Andreas Gampea36dc622018-02-05 17:19:22 -08004095 @GuardedBy("mUsersLock")
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07004096 private int scanNextAvailableIdLocked() {
4097 for (int i = MIN_USER_ID; i < MAX_USER_ID; i++) {
4098 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
4099 return i;
4100 }
4101 }
4102 return -1;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07004103 }
Amith Yamasani920ace02012-09-20 22:15:37 -07004104
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07004105 private static String packageToRestrictionsFileName(String packageName) {
Amith Yamasanifc95e702013-09-26 13:20:17 -07004106 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
4107 }
4108
Amith Yamasani920ace02012-09-20 22:15:37 -07004109 @Override
Bookatzf56f2582019-09-04 16:06:41 -07004110 public void setSeedAccountData(@UserIdInt int userId, String accountName, String accountType,
Amith Yamasani12747872015-12-07 14:19:49 -08004111 PersistableBundle accountOptions, boolean persist) {
4112 checkManageUsersPermission("Require MANAGE_USERS permission to set user seed data");
4113 synchronized (mPackagesLock) {
4114 final UserData userData;
4115 synchronized (mUsersLock) {
4116 userData = getUserDataLU(userId);
4117 if (userData == null) {
4118 Slog.e(LOG_TAG, "No such user for settings seed data u=" + userId);
4119 return;
4120 }
4121 userData.seedAccountName = accountName;
4122 userData.seedAccountType = accountType;
4123 userData.seedAccountOptions = accountOptions;
4124 userData.persistSeedData = persist;
4125 }
4126 if (persist) {
4127 writeUserLP(userData);
4128 }
4129 }
4130 }
4131
4132 @Override
4133 public String getSeedAccountName() throws RemoteException {
4134 checkManageUsersPermission("Cannot get seed account information");
4135 synchronized (mUsersLock) {
4136 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
4137 return userData.seedAccountName;
4138 }
4139 }
4140
4141 @Override
4142 public String getSeedAccountType() throws RemoteException {
4143 checkManageUsersPermission("Cannot get seed account information");
4144 synchronized (mUsersLock) {
4145 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
4146 return userData.seedAccountType;
4147 }
4148 }
4149
4150 @Override
4151 public PersistableBundle getSeedAccountOptions() throws RemoteException {
4152 checkManageUsersPermission("Cannot get seed account information");
4153 synchronized (mUsersLock) {
4154 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
4155 return userData.seedAccountOptions;
4156 }
4157 }
4158
4159 @Override
4160 public void clearSeedAccountData() throws RemoteException {
4161 checkManageUsersPermission("Cannot clear seed account information");
4162 synchronized (mPackagesLock) {
4163 UserData userData;
4164 synchronized (mUsersLock) {
4165 userData = getUserDataLU(UserHandle.getCallingUserId());
4166 if (userData == null) return;
4167 userData.clearSeedAccountData();
4168 }
4169 writeUserLP(userData);
4170 }
4171 }
4172
4173 @Override
4174 public boolean someUserHasSeedAccount(String accountName, String accountType)
4175 throws RemoteException {
4176 checkManageUsersPermission("Cannot check seed account information");
4177 synchronized (mUsersLock) {
4178 final int userSize = mUsers.size();
4179 for (int i = 0; i < userSize; i++) {
4180 final UserData data = mUsers.valueAt(i);
4181 if (data.info.isInitialized()) continue;
4182 if (data.seedAccountName == null || !data.seedAccountName.equals(accountName)) {
4183 continue;
4184 }
4185 if (data.seedAccountType == null || !data.seedAccountType.equals(accountType)) {
4186 continue;
4187 }
4188 return true;
4189 }
4190 }
4191 return false;
4192 }
4193
4194 @Override
Todd Kennedy60459ab2015-10-30 11:32:16 -07004195 public void onShellCommand(FileDescriptor in, FileDescriptor out,
Dianne Hackborn354736e2016-08-22 17:00:05 -07004196 FileDescriptor err, String[] args, ShellCallback callback,
4197 ResultReceiver resultReceiver) {
4198 (new Shell()).exec(this, in, out, err, args, callback, resultReceiver);
Todd Kennedy60459ab2015-10-30 11:32:16 -07004199 }
4200
4201 int onShellCommand(Shell shell, String cmd) {
4202 if (cmd == null) {
4203 return shell.handleDefaultCommands(cmd);
4204 }
4205
4206 final PrintWriter pw = shell.getOutPrintWriter();
4207 try {
4208 switch(cmd) {
4209 case "list":
Felipe Lemec1ca4412019-09-11 09:23:26 -07004210 return runList(pw, shell);
Hui Yu8ba65972018-04-16 18:45:48 -07004211 default:
4212 return shell.handleDefaultCommands(cmd);
Todd Kennedy60459ab2015-10-30 11:32:16 -07004213 }
4214 } catch (RemoteException e) {
4215 pw.println("Remote exception: " + e);
4216 }
4217 return -1;
4218 }
4219
Felipe Lemec1ca4412019-09-11 09:23:26 -07004220 private int runList(PrintWriter pw, Shell shell) throws RemoteException {
4221 boolean all = false;
4222 boolean verbose = false;
4223 String opt;
4224 while ((opt = shell.getNextOption()) != null) {
4225 switch (opt) {
4226 case "-v":
4227 verbose = true;
4228 break;
4229 case "--all":
4230 all = true;
4231 break;
4232 default:
4233 pw.println("Invalid option: " + opt);
4234 return -1;
4235 }
4236 }
Sudheer Shankadc589ac2016-11-10 15:30:17 -08004237 final IActivityManager am = ActivityManager.getService();
Felipe Lemec1ca4412019-09-11 09:23:26 -07004238 final List<UserInfo> users = getUsers(/* excludePartial= */ !all,
4239 /* excludingDying=*/ false, /* excludePreCreated= */ !all);
Todd Kennedy60459ab2015-10-30 11:32:16 -07004240 if (users == null) {
4241 pw.println("Error: couldn't get users");
4242 return 1;
4243 } else {
Felipe Lemec1ca4412019-09-11 09:23:26 -07004244 final int size = users.size();
4245 int currentUser = UserHandle.USER_NULL;
4246 if (verbose) {
4247 pw.printf("%d users:\n\n", size);
4248 currentUser = am.getCurrentUser().id;
4249 } else {
4250 // NOTE: the standard "list users" command is used by integration tests and
4251 // hence should not be changed. If you need to add more info, use the
4252 // verbose option.
4253 pw.println("Users:");
4254 }
4255 for (int i = 0; i < size; i++) {
4256 final UserInfo user = users.get(i);
4257 final boolean running = am.isUserRunning(user.id, 0);
4258 final boolean current = user.id == currentUser;
4259 if (verbose) {
4260 pw.printf("%d: id=%d, name=%s, flags=%s%s%s%s%s\n", i, user.id, user.name,
4261 UserInfo.flagsToString(user.flags),
4262 running ? " (running)" : "",
4263 user.partial ? " (partial)" : "",
4264 user.preCreated ? " (pre-created)" : "",
4265 current ? " (current)" : "");
4266 } else {
4267 // NOTE: the standard "list users" command is used by integration tests and
4268 // hence should not be changed. If you need to add more info, use the
4269 // verbose option.
4270 pw.printf("\t%s%s\n", user, running ? " running" : "");
4271 }
Todd Kennedy60459ab2015-10-30 11:32:16 -07004272 }
4273 return 0;
4274 }
4275 }
4276
4277 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -07004278 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06004279 if (!DumpUtils.checkDumpPermission(mContext, LOG_TAG, pw)) return;
Amith Yamasani920ace02012-09-20 22:15:37 -07004280
4281 long now = System.currentTimeMillis();
Makoto Onuki73dded22017-12-20 13:14:48 +09004282 final long nowRealtime = SystemClock.elapsedRealtime();
Felipe Lemed7b88382019-06-12 17:40:53 -07004283
4284 final int currentUser = LocalServices.getService(ActivityManagerInternal.class)
4285 .getCurrentUserId();
4286 pw.print("Current user: "); pw.println(currentUser);
4287
Amith Yamasani920ace02012-09-20 22:15:37 -07004288 StringBuilder sb = new StringBuilder();
4289 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07004290 synchronized (mUsersLock) {
4291 pw.println("Users:");
4292 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08004293 UserData userData = mUsers.valueAt(i);
4294 if (userData == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07004295 continue;
4296 }
Amith Yamasani12747872015-12-07 14:19:49 -08004297 UserInfo userInfo = userData.info;
4298 final int userId = userInfo.id;
4299 pw.print(" "); pw.print(userInfo);
4300 pw.print(" serialNo="); pw.print(userInfo.serialNumber);
Felipe Lemed7b88382019-06-12 17:40:53 -07004301 pw.print(" isPrimary="); pw.print(userInfo.isPrimary());
Makoto Onukie7927da2015-11-25 10:05:17 -08004302 if (mRemovingUserIds.get(userId)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07004303 pw.print(" <removing> ");
4304 }
Amith Yamasani12747872015-12-07 14:19:49 -08004305 if (userInfo.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07004306 pw.print(" <partial>");
4307 }
Felipe Lemec1ca4412019-09-11 09:23:26 -07004308 if (userInfo.preCreated) {
4309 pw.print(" <pre-created>");
4310 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07004311 pw.println();
Bookatz029832a2019-10-04 16:50:22 -07004312 pw.print(" Type: "); pw.println(userInfo.userType);
Felipe Lemee5434c32019-08-13 09:28:33 -07004313 pw.print(" Flags: "); pw.print(userInfo.flags); pw.print(" (");
4314 pw.print(UserInfo.flagsToString(userInfo.flags)); pw.println(")");
Makoto Onuki88aef752017-03-29 16:52:03 -07004315 pw.print(" State: ");
4316 final int state;
4317 synchronized (mUserStates) {
4318 state = mUserStates.get(userId, -1);
4319 }
4320 pw.println(UserState.stateToString(state));
Fyodor Kupolov82402752015-10-28 14:54:51 -07004321 pw.print(" Created: ");
Makoto Onuki73dded22017-12-20 13:14:48 +09004322 dumpTimeAgo(pw, sb, now, userInfo.creationTime);
4323
Fyodor Kupolov82402752015-10-28 14:54:51 -07004324 pw.print(" Last logged in: ");
Makoto Onuki73dded22017-12-20 13:14:48 +09004325 dumpTimeAgo(pw, sb, now, userInfo.lastLoggedInTime);
4326
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06004327 pw.print(" Last logged in fingerprint: ");
4328 pw.println(userInfo.lastLoggedInFingerprint);
Makoto Onuki73dded22017-12-20 13:14:48 +09004329
4330 pw.print(" Start time: ");
4331 dumpTimeAgo(pw, sb, nowRealtime, userData.startRealtime);
4332
4333 pw.print(" Unlock time: ");
4334 dumpTimeAgo(pw, sb, nowRealtime, userData.unlockRealtime);
4335
Makoto Onukie7927da2015-11-25 10:05:17 -08004336 pw.print(" Has profile owner: ");
4337 pw.println(mIsUserManaged.get(userId));
Fyodor Kupolov82402752015-10-28 14:54:51 -07004338 pw.println(" Restrictions:");
4339 synchronized (mRestrictionsLock) {
4340 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08004341 pw, " ", mBaseUserRestrictions.get(userInfo.id));
Pavel Grafov6a40f092016-10-25 15:46:51 +01004342 pw.println(" Device policy global restrictions:");
4343 UserRestrictionsUtils.dumpRestrictions(
4344 pw, " ", mDevicePolicyGlobalUserRestrictions.get(userInfo.id));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08004345 pw.println(" Device policy local restrictions:");
4346 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08004347 pw, " ", mDevicePolicyLocalUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07004348 pw.println(" Effective restrictions:");
4349 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08004350 pw, " ", mCachedEffectiveUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07004351 }
Amith Yamasani12747872015-12-07 14:19:49 -08004352
4353 if (userData.account != null) {
4354 pw.print(" Account name: " + userData.account);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08004355 pw.println();
4356 }
Amith Yamasani12747872015-12-07 14:19:49 -08004357
4358 if (userData.seedAccountName != null) {
4359 pw.print(" Seed account name: " + userData.seedAccountName);
4360 pw.println();
4361 if (userData.seedAccountType != null) {
4362 pw.print(" account type: " + userData.seedAccountType);
4363 pw.println();
4364 }
4365 if (userData.seedAccountOptions != null) {
4366 pw.print(" account options exist");
4367 pw.println();
4368 }
4369 }
Amith Yamasani920ace02012-09-20 22:15:37 -07004370 }
Amith Yamasani920ace02012-09-20 22:15:37 -07004371 }
Amith Yamasani12747872015-12-07 14:19:49 -08004372 pw.println();
Pavel Grafov6a40f092016-10-25 15:46:51 +01004373 pw.println(" Device owner id:" + mDeviceOwnerUserId);
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01004374 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08004375 pw.println(" Guest restrictions:");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08004376 synchronized (mGuestRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08004377 UserRestrictionsUtils.dumpRestrictions(pw, " ", mGuestRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08004378 }
Makoto Onukie7927da2015-11-25 10:05:17 -08004379 synchronized (mUsersLock) {
4380 pw.println();
4381 pw.println(" Device managed: " + mIsDeviceManaged);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07004382 if (mRemovingUserIds.size() > 0) {
4383 pw.println();
4384 pw.println(" Recently removed userIds: " + mRecentlyRemovedIds);
4385 }
Makoto Onukie7927da2015-11-25 10:05:17 -08004386 }
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00004387 synchronized (mUserStates) {
4388 pw.println(" Started users state: " + mUserStates);
4389 }
Felipe Lemed7b88382019-06-12 17:40:53 -07004390 } // synchronized (mPackagesLock)
4391
4392 // Dump some capabilities
4393 pw.println();
Felipe Lemec1ca4412019-09-11 09:23:26 -07004394 pw.print(" Max users: " + UserManager.getMaxSupportedUsers());
4395 pw.println(" (limit reached: " + isUserLimitReached() + ")");
Felipe Lemed7b88382019-06-12 17:40:53 -07004396 pw.println(" Supports switchable users: " + UserManager.supportsMultipleUsers());
Bookatz029832a2019-10-04 16:50:22 -07004397 pw.println(" All guests ephemeral: " + Resources.getSystem().getBoolean(
4398 com.android.internal.R.bool.config_guestUserEphemeral));
Felipe Lemed7b88382019-06-12 17:40:53 -07004399 pw.println(" Is split-system user: " + UserManager.isSplitSystemUser());
Felipe Lemee5434c32019-08-13 09:28:33 -07004400 pw.println(" Is headless-system mode: " + UserManager.isHeadlessSystemUserMode());
4401 pw.println(" User version: " + mUserVersion);
Bookatz04d7ae52019-08-05 14:07:12 -07004402
Bookatz029832a2019-10-04 16:50:22 -07004403 // Dump UserTypes
4404 pw.println();
4405 pw.println(" User types (" + mUserTypes.size() + " types):");
4406 for (int i = 0; i < mUserTypes.size(); i++) {
4407 pw.println(" " + mUserTypes.keyAt(i) + ": ");
4408 mUserTypes.valueAt(i).dump(pw);
4409 }
4410
Bookatz04d7ae52019-08-05 14:07:12 -07004411 // Dump package whitelist
4412 pw.println();
4413 mSystemPackageInstaller.dump(pw);
Amith Yamasani920ace02012-09-20 22:15:37 -07004414 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08004415
Makoto Onuki73dded22017-12-20 13:14:48 +09004416 private static void dumpTimeAgo(PrintWriter pw, StringBuilder sb, long nowTime, long time) {
4417 if (time == 0) {
4418 pw.println("<unknown>");
4419 } else {
4420 sb.setLength(0);
4421 TimeUtils.formatDuration(nowTime - time, sb);
4422 sb.append(" ago");
4423 pw.println(sb);
4424 }
4425 }
4426
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08004427 final class MainHandler extends Handler {
4428
4429 @Override
4430 public void handleMessage(Message msg) {
4431 switch (msg.what) {
4432 case WRITE_USER_MSG:
4433 removeMessages(WRITE_USER_MSG, msg.obj);
4434 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08004435 int userId = ((UserData) msg.obj).info.id;
4436 UserData userData = getUserDataNoChecks(userId);
4437 if (userData != null) {
4438 writeUserLP(userData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08004439 }
4440 }
4441 }
4442 }
4443 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07004444
4445 /**
4446 * @param userId
4447 * @return whether the user has been initialized yet
4448 */
Bookatzf56f2582019-09-04 16:06:41 -07004449 boolean isUserInitialized(@UserIdInt int userId) {
Todd Kennedy0eb97382017-10-03 16:57:22 -07004450 return mLocalService.isUserInitialized(userId);
Amith Yamasanibb054c92015-07-09 14:16:27 -07004451 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07004452
4453 private class LocalService extends UserManagerInternal {
Makoto Onuki068c54a2015-10-13 14:34:03 -07004454 @Override
Bookatzf56f2582019-09-04 16:06:41 -07004455 public void setDevicePolicyUserRestrictions(@UserIdInt int userId,
4456 @Nullable Bundle restrictions, boolean isDeviceOwner, int cameraRestrictionScope) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01004457 UserManagerService.this.setDevicePolicyUserRestrictionsInner(userId, restrictions,
4458 isDeviceOwner, cameraRestrictionScope);
Makoto Onuki068c54a2015-10-13 14:34:03 -07004459 }
4460
4461 @Override
Bookatzf56f2582019-09-04 16:06:41 -07004462 public Bundle getBaseUserRestrictions(@UserIdInt int userId) {
Makoto Onuki068c54a2015-10-13 14:34:03 -07004463 synchronized (mRestrictionsLock) {
4464 return mBaseUserRestrictions.get(userId);
4465 }
4466 }
4467
4468 @Override
4469 public void setBaseUserRestrictionsByDpmsForMigration(
Bookatzf56f2582019-09-04 16:06:41 -07004470 @UserIdInt int userId, Bundle baseRestrictions) {
Makoto Onuki068c54a2015-10-13 14:34:03 -07004471 synchronized (mRestrictionsLock) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01004472 if (updateRestrictionsIfNeededLR(
4473 userId, new Bundle(baseRestrictions), mBaseUserRestrictions)) {
4474 invalidateEffectiveUserRestrictionsLR(userId);
4475 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07004476 }
4477
Amith Yamasani12747872015-12-07 14:19:49 -08004478 final UserData userData = getUserDataNoChecks(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07004479 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08004480 if (userData != null) {
4481 writeUserLP(userData);
Makoto Onuki068c54a2015-10-13 14:34:03 -07004482 } else {
4483 Slog.w(LOG_TAG, "UserInfo not found for " + userId);
4484 }
4485 }
4486 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08004487
4488 @Override
Bookatzf56f2582019-09-04 16:06:41 -07004489 public boolean getUserRestriction(@UserIdInt int userId, String key) {
Makoto Onukid45a4a22015-11-02 17:17:38 -08004490 return getUserRestrictions(userId).getBoolean(key);
4491 }
4492
4493 @Override
4494 public void addUserRestrictionsListener(UserRestrictionsListener listener) {
4495 synchronized (mUserRestrictionsListeners) {
4496 mUserRestrictionsListeners.add(listener);
4497 }
4498 }
4499
4500 @Override
4501 public void removeUserRestrictionsListener(UserRestrictionsListener listener) {
4502 synchronized (mUserRestrictionsListeners) {
4503 mUserRestrictionsListeners.remove(listener);
4504 }
4505 }
Makoto Onukie7927da2015-11-25 10:05:17 -08004506
4507 @Override
4508 public void setDeviceManaged(boolean isManaged) {
4509 synchronized (mUsersLock) {
4510 mIsDeviceManaged = isManaged;
4511 }
4512 }
4513
4514 @Override
Rubin Xu0f1e56d2019-08-23 13:34:25 +01004515 public boolean isDeviceManaged() {
4516 synchronized (mUsersLock) {
4517 return mIsDeviceManaged;
4518 }
4519 }
4520
4521 @Override
Bookatzf56f2582019-09-04 16:06:41 -07004522 public void setUserManaged(@UserIdInt int userId, boolean isManaged) {
Makoto Onukie7927da2015-11-25 10:05:17 -08004523 synchronized (mUsersLock) {
4524 mIsUserManaged.put(userId, isManaged);
4525 }
4526 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01004527
4528 @Override
Rubin Xu0f1e56d2019-08-23 13:34:25 +01004529 public boolean isUserManaged(@UserIdInt int userId) {
4530 synchronized (mUsersLock) {
4531 return mIsUserManaged.get(userId);
4532 }
4533 }
4534
4535 @Override
Bookatzf56f2582019-09-04 16:06:41 -07004536 public void setUserIcon(@UserIdInt int userId, Bitmap bitmap) {
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01004537 long ident = Binder.clearCallingIdentity();
4538 try {
4539 synchronized (mPackagesLock) {
4540 UserData userData = getUserDataNoChecks(userId);
4541 if (userData == null || userData.info.partial) {
4542 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
4543 return;
4544 }
4545 writeBitmapLP(userData.info, bitmap);
4546 writeUserLP(userData);
4547 }
4548 sendUserInfoChangedBroadcast(userId);
4549 } finally {
4550 Binder.restoreCallingIdentity(ident);
4551 }
4552 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01004553
4554 @Override
4555 public void setForceEphemeralUsers(boolean forceEphemeralUsers) {
4556 synchronized (mUsersLock) {
4557 mForceEphemeralUsers = forceEphemeralUsers;
4558 }
4559 }
4560
4561 @Override
4562 public void removeAllUsers() {
4563 if (UserHandle.USER_SYSTEM == ActivityManager.getCurrentUser()) {
4564 // Remove the non-system users straight away.
4565 removeNonSystemUsers();
4566 } else {
4567 // Switch to the system user first and then remove the other users.
4568 BroadcastReceiver userSwitchedReceiver = new BroadcastReceiver() {
4569 @Override
4570 public void onReceive(Context context, Intent intent) {
4571 int userId =
4572 intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
4573 if (userId != UserHandle.USER_SYSTEM) {
4574 return;
4575 }
4576 mContext.unregisterReceiver(this);
4577 removeNonSystemUsers();
4578 }
4579 };
4580 IntentFilter userSwitchedFilter = new IntentFilter();
4581 userSwitchedFilter.addAction(Intent.ACTION_USER_SWITCHED);
4582 mContext.registerReceiver(
4583 userSwitchedReceiver, userSwitchedFilter, null, mHandler);
4584
4585 // Switch to the system user.
4586 ActivityManager am =
4587 (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
4588 am.switchUser(UserHandle.USER_SYSTEM);
4589 }
4590 }
phweisse9c44062016-02-10 12:57:38 +01004591
4592 @Override
Bookatzf56f2582019-09-04 16:06:41 -07004593 public void onEphemeralUserStop(@UserIdInt int userId) {
Lenka Trochtova1ddda472016-02-12 10:42:12 +01004594 synchronized (mUsersLock) {
4595 UserInfo userInfo = getUserInfoLU(userId);
4596 if (userInfo != null && userInfo.isEphemeral()) {
4597 // Do not allow switching back to the ephemeral user again as the user is going
4598 // to be deleted.
4599 userInfo.flags |= UserInfo.FLAG_DISABLED;
4600 if (userInfo.isGuest()) {
4601 // Indicate that the guest will be deleted after it stops.
4602 userInfo.guestToRemove = true;
4603 }
4604 }
4605 }
4606 }
4607
4608 @Override
Bookatz029832a2019-10-04 16:50:22 -07004609 public UserInfo createUserEvenWhenDisallowed(String name, @NonNull String userType,
4610 @UserInfoFlag int flags, String[] disallowedPackages) {
4611 UserInfo user = createUserInternalUnchecked(name, userType, flags,
4612 UserHandle.USER_NULL, /* preCreated= */ false, disallowedPackages);
phweisse9c44062016-02-10 12:57:38 +01004613 // Keep this in sync with UserManager.createUser
Christine Franks97a54802017-08-09 10:06:43 -07004614 if (user != null && !user.isAdmin() && !user.isDemo()) {
phweisse9c44062016-02-10 12:57:38 +01004615 setUserRestriction(UserManager.DISALLOW_SMS, true, user.id);
4616 setUserRestriction(UserManager.DISALLOW_OUTGOING_CALLS, true, user.id);
4617 }
4618 return user;
4619 }
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07004620
4621 @Override
Bookatzf56f2582019-09-04 16:06:41 -07004622 public boolean removeUserEvenWhenDisallowed(@UserIdInt int userId) {
Nicolas Prevotdf1b87d2016-10-25 13:57:08 +01004623 return removeUserUnchecked(userId);
4624 }
4625
4626 @Override
Bookatzf56f2582019-09-04 16:06:41 -07004627 public boolean isUserRunning(@UserIdInt int userId) {
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00004628 synchronized (mUserStates) {
4629 return mUserStates.get(userId, -1) >= 0;
4630 }
4631 }
4632
4633 @Override
Bookatzf56f2582019-09-04 16:06:41 -07004634 public void setUserState(@UserIdInt int userId, int userState) {
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00004635 synchronized (mUserStates) {
4636 mUserStates.put(userId, userState);
4637 }
4638 }
4639
4640 @Override
Bookatzf56f2582019-09-04 16:06:41 -07004641 public void removeUserState(@UserIdInt int userId) {
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00004642 synchronized (mUserStates) {
4643 mUserStates.delete(userId);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07004644 }
4645 }
4646
4647 @Override
Michael Wachenschwanz3f2b6552017-05-15 13:53:09 -07004648 public int[] getUserIds() {
4649 return UserManagerService.this.getUserIds();
4650 }
4651
4652 @Override
Bookatzf56f2582019-09-04 16:06:41 -07004653 public boolean isUserUnlockingOrUnlocked(@UserIdInt int userId) {
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07004654 int state;
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00004655 synchronized (mUserStates) {
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07004656 state = mUserStates.get(userId, -1);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07004657 }
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07004658 // Special case, in the stopping/shutdown state user key can still be unlocked
4659 if (state == UserState.STATE_STOPPING || state == UserState.STATE_SHUTDOWN) {
4660 return StorageManager.isUserKeyUnlocked(userId);
4661 }
4662 return (state == UserState.STATE_RUNNING_UNLOCKING)
4663 || (state == UserState.STATE_RUNNING_UNLOCKED);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07004664 }
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08004665
4666 @Override
Bookatzf56f2582019-09-04 16:06:41 -07004667 public boolean isUserUnlocked(@UserIdInt int userId) {
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07004668 int state;
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08004669 synchronized (mUserStates) {
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07004670 state = mUserStates.get(userId, -1);
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08004671 }
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07004672 // Special case, in the stopping/shutdown state user key can still be unlocked
4673 if (state == UserState.STATE_STOPPING || state == UserState.STATE_SHUTDOWN) {
4674 return StorageManager.isUserKeyUnlocked(userId);
4675 }
4676 return state == UserState.STATE_RUNNING_UNLOCKED;
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08004677 }
Todd Kennedy0eb97382017-10-03 16:57:22 -07004678
4679 @Override
Bookatzf56f2582019-09-04 16:06:41 -07004680 public boolean isUserInitialized(@UserIdInt int userId) {
Todd Kennedy0eb97382017-10-03 16:57:22 -07004681 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
4682 }
4683
4684 @Override
Bookatzf56f2582019-09-04 16:06:41 -07004685 public boolean exists(@UserIdInt int userId) {
Todd Kennedy0eb97382017-10-03 16:57:22 -07004686 return getUserInfoNoChecks(userId) != null;
4687 }
Sunny Goyal145c8f82018-02-15 14:27:09 -08004688
4689 @Override
4690 public boolean isProfileAccessible(int callingUserId, int targetUserId, String debugMsg,
4691 boolean throwSecurityException) {
4692 if (targetUserId == callingUserId) {
4693 return true;
4694 }
4695 synchronized (mUsersLock) {
4696 UserInfo callingUserInfo = getUserInfoLU(callingUserId);
Bookatz029832a2019-10-04 16:50:22 -07004697 if (callingUserInfo == null || callingUserInfo.isProfile()) {
Sunny Goyal145c8f82018-02-15 14:27:09 -08004698 if (throwSecurityException) {
4699 throw new SecurityException(
4700 debugMsg + " for another profile "
4701 + targetUserId + " from " + callingUserId);
4702 }
4703 }
4704
4705 UserInfo targetUserInfo = getUserInfoLU(targetUserId);
4706 if (targetUserInfo == null || !targetUserInfo.isEnabled()) {
4707 // Do not throw any exception here as this could happen due to race conditions
4708 // between the system updating its state and the client getting notified.
4709 if (throwSecurityException) {
4710 Slog.w(LOG_TAG, debugMsg + " for disabled profile "
4711 + targetUserId + " from " + callingUserId);
4712 }
4713 return false;
4714 }
4715
4716 if (targetUserInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID ||
4717 targetUserInfo.profileGroupId != callingUserInfo.profileGroupId) {
4718 if (throwSecurityException) {
4719 throw new SecurityException(
4720 debugMsg + " for unrelated profile " + targetUserId);
4721 }
4722 return false;
4723 }
4724 }
4725 return true;
4726 }
4727
4728 @Override
Bookatzf56f2582019-09-04 16:06:41 -07004729 public int getProfileParentId(@UserIdInt int userId) {
Sunny Goyal145c8f82018-02-15 14:27:09 -08004730 synchronized (mUsersLock) {
4731 UserInfo profileParent = getProfileParentLU(userId);
4732 if (profileParent == null) {
4733 return userId;
4734 }
4735 return profileParent.id;
4736 }
4737 }
yuemingw1d13eae2018-01-30 17:27:54 +00004738
4739 @Override
4740 public boolean isSettingRestrictedForUser(String setting, @UserIdInt int userId,
4741 String value, int callingUid) {
Christopher Tate65fb2e42019-10-11 17:00:23 -07004742 return UserManagerService.this.isSettingRestrictedForUser(setting, userId,
yuemingw1d13eae2018-01-30 17:27:54 +00004743 value, callingUid);
4744 }
Patrick Baumann2f2fd712019-07-31 15:18:53 -07004745
4746 @Override
Bookatzf56f2582019-09-04 16:06:41 -07004747 public boolean hasUserRestriction(String restrictionKey, @UserIdInt int userId) {
Patrick Baumann2f2fd712019-07-31 15:18:53 -07004748 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
4749 return false;
4750 }
4751 Bundle restrictions = getEffectiveUserRestrictions(userId);
4752 return restrictions != null && restrictions.getBoolean(restrictionKey);
4753 }
Felipe Lemee5434c32019-08-13 09:28:33 -07004754
Rubin Xu0f1e56d2019-08-23 13:34:25 +01004755 @Override
Felipe Lemee5434c32019-08-13 09:28:33 -07004756 public @Nullable UserInfo getUserInfo(@UserIdInt int userId) {
4757 UserData userData;
4758 synchronized (mUsersLock) {
4759 userData = mUsers.get(userId);
4760 }
4761 return userData == null ? null : userData.info;
4762 }
Felipe Leme987655d2019-08-26 10:45:24 -07004763
4764 public @NonNull UserInfo[] getUserInfos() {
4765 synchronized (mUsersLock) {
4766 int userSize = mUsers.size();
4767 UserInfo[] allInfos = new UserInfo[userSize];
4768 for (int i = 0; i < userSize; i++) {
4769 allInfos[i] = mUsers.valueAt(i).info;
4770 }
4771 return allInfos;
4772 }
4773 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01004774 }
4775
4776 /* Remove all the users except of the system one. */
4777 private void removeNonSystemUsers() {
4778 ArrayList<UserInfo> usersToRemove = new ArrayList<>();
4779 synchronized (mUsersLock) {
4780 final int userSize = mUsers.size();
4781 for (int i = 0; i < userSize; i++) {
4782 UserInfo ui = mUsers.valueAt(i).info;
4783 if (ui.id != UserHandle.USER_SYSTEM) {
4784 usersToRemove.add(ui);
4785 }
4786 }
4787 }
4788 for (UserInfo ui: usersToRemove) {
4789 removeUser(ui.id);
4790 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07004791 }
Todd Kennedy60459ab2015-10-30 11:32:16 -07004792
4793 private class Shell extends ShellCommand {
4794 @Override
4795 public int onCommand(String cmd) {
4796 return onShellCommand(this, cmd);
4797 }
4798
4799 @Override
4800 public void onHelp() {
4801 final PrintWriter pw = getOutPrintWriter();
4802 pw.println("User manager (user) commands:");
4803 pw.println(" help");
4804 pw.println(" Print this help text.");
4805 pw.println("");
Felipe Lemec1ca4412019-09-11 09:23:26 -07004806 pw.println(" list [-v] [-all]");
Todd Kennedy60459ab2015-10-30 11:32:16 -07004807 pw.println(" Prints all users on the system.");
4808 }
4809 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08004810
4811 private static void debug(String message) {
4812 Log.d(LOG_TAG, message +
4813 (DBG_WITH_STACKTRACE ? " called at\n" + Debug.getCallers(10, " ") : ""));
4814 }
Kenny Guy02c89902016-11-15 19:36:38 +00004815
Bookatz029832a2019-10-04 16:50:22 -07004816 /** @see #getMaxUsersOfTypePerParent(UserTypeDetails) */
Kenny Guy02c89902016-11-15 19:36:38 +00004817 @VisibleForTesting
Bookatz029832a2019-10-04 16:50:22 -07004818 int getMaxUsersOfTypePerParent(String userType) {
4819 final UserTypeDetails type = mUserTypes.get(userType);
4820 if (type == null) {
4821 return 0;
Kenny Guy02c89902016-11-15 19:36:38 +00004822 }
Bookatz029832a2019-10-04 16:50:22 -07004823 return getMaxUsersOfTypePerParent(type);
4824 }
4825
4826 /**
4827 * Returns the maximum number of users allowed for the given userTypeDetails per parent user.
4828 * This is applicable for user types that are {@link UserTypeDetails#isProfile()}.
4829 * If there is no maximum, {@link UserTypeDetails#UNLIMITED_NUMBER_OF_USERS} is returned.
4830 */
4831 private static int getMaxUsersOfTypePerParent(UserTypeDetails userTypeDetails) {
4832 final int defaultMax = userTypeDetails.getMaxAllowedPerParent();
4833 if (!Build.IS_DEBUGGABLE) {
4834 return defaultMax;
4835 } else {
4836 if (userTypeDetails.isManagedProfile()) {
4837 return SystemProperties.getInt("persist.sys.max_profiles", defaultMax);
4838 }
4839 }
4840 return defaultMax;
Kenny Guy02c89902016-11-15 19:36:38 +00004841 }
4842
Andreas Gampe2e8c7672018-07-20 13:01:08 -07004843 @GuardedBy("mUsersLock")
Kenny Guy02c89902016-11-15 19:36:38 +00004844 @VisibleForTesting
Bookatz029832a2019-10-04 16:50:22 -07004845 int getFreeProfileBadgeLU(int parentUserId, String userType) {
4846 Set<Integer> usedBadges = new ArraySet<>();
Kenny Guy02c89902016-11-15 19:36:38 +00004847 final int userSize = mUsers.size();
4848 for (int i = 0; i < userSize; i++) {
4849 UserInfo ui = mUsers.valueAt(i).info;
4850 // Check which badge indexes are already used by this profile group.
Bookatz029832a2019-10-04 16:50:22 -07004851 if (ui.userType.equals(userType)
Kenny Guy02c89902016-11-15 19:36:38 +00004852 && ui.profileGroupId == parentUserId
Bookatz029832a2019-10-04 16:50:22 -07004853 && !mRemovingUserIds.get(ui.id)) {
4854 usedBadges.add(ui.profileBadge);
Kenny Guy02c89902016-11-15 19:36:38 +00004855 }
4856 }
Bookatz029832a2019-10-04 16:50:22 -07004857 int maxUsersOfType = getMaxUsersOfTypePerParent(userType);
4858 if (maxUsersOfType == UserTypeDetails.UNLIMITED_NUMBER_OF_USERS) {
4859 maxUsersOfType = Integer.MAX_VALUE;
4860 }
4861 for (int i = 0; i < maxUsersOfType; i++) {
4862 if (!usedBadges.contains(i)) {
Kenny Guy02c89902016-11-15 19:36:38 +00004863 return i;
4864 }
4865 }
4866 return 0;
4867 }
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07004868
4869 /**
4870 * Checks if the given user has a managed profile associated with it.
4871 * @param userId The parent user
4872 * @return
4873 */
Bookatzf56f2582019-09-04 16:06:41 -07004874 boolean hasManagedProfile(@UserIdInt int userId) {
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07004875 synchronized (mUsersLock) {
4876 UserInfo userInfo = getUserInfoLU(userId);
4877 final int userSize = mUsers.size();
4878 for (int i = 0; i < userSize; i++) {
4879 UserInfo profile = mUsers.valueAt(i).info;
4880 if (userId != profile.id && isProfileOf(userInfo, profile)) {
4881 return true;
4882 }
4883 }
4884 return false;
4885 }
4886 }
Tony Makd390ae92017-12-28 13:23:10 +00004887
4888 /**
4889 * Check if the calling package name matches with the calling UID, throw
4890 * {@link SecurityException} if not.
4891 */
4892 private void verifyCallingPackage(String callingPackage, int callingUid) {
4893 int packageUid = mPm.getPackageUid(callingPackage, 0, UserHandle.getUserId(callingUid));
4894 if (packageUid != callingUid) {
4895 throw new SecurityException("Specified package " + callingPackage
4896 + " does not match the calling uid " + callingUid);
4897 }
4898 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07004899}