blob: 62562a26c167eb5e7e43ed3f892a05761b604fa6 [file] [log] [blame]
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
Benjamin Franzf02420c2016-04-04 18:52:21 +010019import static android.content.Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS;
20import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
21
Xiaohui Chenb3b92582015-12-07 11:22:13 -080022import android.Manifest;
Xiaohui Chen594f2082015-08-18 11:04:20 -070023import android.annotation.NonNull;
Makoto Onuki068c54a2015-10-13 14:34:03 -070024import android.annotation.Nullable;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -060025import android.annotation.UserIdInt;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070026import android.app.Activity;
Amith Yamasani2a003292012-08-14 18:25:45 -070027import android.app.ActivityManager;
Amith Yamasani515d4062015-09-28 11:30:06 -070028import android.app.ActivityManagerInternal;
Andrew Scull85a63bc2016-10-24 13:47:47 +010029import android.app.ActivityManagerNative;
Todd Kennedy60459ab2015-10-30 11:32:16 -070030import android.app.IActivityManager;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070031import android.app.IStopUserCallback;
Benjamin Franzf02420c2016-04-04 18:52:21 +010032import android.app.KeyguardManager;
Ricky Waib1dd80b2016-06-07 18:00:55 +010033import android.app.PendingIntent;
arangelov9b632d72018-12-07 23:21:22 +000034import android.app.admin.DevicePolicyEventLogger;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070035import android.content.BroadcastReceiver;
Amith Yamasani258848d2012-08-10 17:06:33 -070036import android.content.Context;
37import android.content.Intent;
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +010038import android.content.IntentFilter;
Benjamin Franzf02420c2016-04-04 18:52:21 +010039import android.content.IntentSender;
Amith Yamasani0b285492011-04-14 17:35:23 -070040import android.content.pm.PackageManager;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -080041import android.content.pm.PackageManager.NameNotFoundException;
Tony Make3d1f652017-12-12 11:00:37 +000042import android.content.pm.ShortcutServiceInternal;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070043import android.content.pm.UserInfo;
Felipe Leme7ad2f6b2019-09-11 09:23:26 -070044import android.content.pm.UserInfo.UserInfoFlag;
Lenka Trochtova02fee152015-12-22 14:26:18 +010045import android.content.res.Resources;
Amith Yamasanie928d7d2012-09-17 21:46:51 -070046import android.graphics.Bitmap;
Amith Yamasani258848d2012-08-10 17:06:33 -070047import android.os.Binder;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -060048import android.os.Build;
Amith Yamasanie4cf7342012-12-17 11:12:09 -080049import android.os.Bundle;
Makoto Onuki1a2cd742015-11-16 13:51:27 -080050import android.os.Debug;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070051import android.os.Environment;
52import android.os.FileUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080053import android.os.Handler;
Svet Ganov9cea80cd2016-02-16 11:47:00 -080054import android.os.IBinder;
Tony Mak64fd8c02017-12-01 19:11:59 +000055import android.os.IProgressListener;
Amith Yamasani258848d2012-08-10 17:06:33 -070056import android.os.IUserManager;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -080057import android.os.Message;
Adrian Roos1bdff912015-02-17 15:51:35 +010058import android.os.ParcelFileDescriptor;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070059import android.os.Parcelable;
Amith Yamasani12747872015-12-07 14:19:49 -080060import android.os.PersistableBundle;
Amith Yamasani258848d2012-08-10 17:06:33 -070061import android.os.Process;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070062import android.os.RemoteException;
Todd Kennedy60459ab2015-10-30 11:32:16 -070063import android.os.ResultReceiver;
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +010064import android.os.SELinux;
Jason Monk62062992014-05-06 09:55:28 -040065import android.os.ServiceManager;
Dianne Hackborn354736e2016-08-22 17:00:05 -070066import android.os.ShellCallback;
Todd Kennedy60459ab2015-10-30 11:32:16 -070067import android.os.ShellCommand;
Makoto Onuki73dded22017-12-20 13:14:48 +090068import android.os.SystemClock;
Kenny Guy02c89902016-11-15 19:36:38 +000069import android.os.SystemProperties;
Felipe Leme7ad2f6b2019-09-11 09:23:26 -070070import android.os.Trace;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070071import android.os.UserHandle;
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070072import android.os.UserManager;
Pavel Grafov6a40f092016-10-25 15:46:51 +010073import android.os.UserManager.EnforcingUser;
Makoto Onuki068c54a2015-10-13 14:34:03 -070074import android.os.UserManagerInternal;
Makoto Onukid45a4a22015-11-02 17:17:38 -080075import android.os.UserManagerInternal.UserRestrictionsListener;
Paul Crowley85e4e812015-05-19 12:42:00 +010076import android.os.storage.StorageManager;
Amith Yamasanid04aaa32016-06-13 12:09:36 -070077import android.security.GateKeeper;
78import android.service.gatekeeper.IGateKeeperService;
arangelov9b632d72018-12-07 23:21:22 +000079import android.stats.devicepolicy.DevicePolicyEnums;
Amith Yamasani2a003292012-08-14 18:25:45 -070080import android.util.AtomicFile;
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -070081import android.util.IntArray;
Amith Yamasani655d0e22013-06-12 14:19:10 -070082import android.util.Log;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070083import android.util.Slog;
84import android.util.SparseArray;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080085import android.util.SparseBooleanArray;
Amith Yamasaniea1b9d72016-05-27 15:57:38 +000086import android.util.SparseIntArray;
Amith Yamasani920ace02012-09-20 22:15:37 -070087import android.util.TimeUtils;
Felipe Leme7ad2f6b2019-09-11 09:23:26 -070088import android.util.TimingsTraceLog;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070089import android.util.Xml;
90
Makoto Onuki068c54a2015-10-13 14:34:03 -070091import com.android.internal.annotations.GuardedBy;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070092import com.android.internal.annotations.VisibleForTesting;
Jason Monk62062992014-05-06 09:55:28 -040093import com.android.internal.app.IAppOpsService;
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -080094import com.android.internal.logging.MetricsLogger;
Fyodor Kupolova68a2862018-01-30 18:22:00 -080095import com.android.internal.os.BackgroundThread;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -060096import com.android.internal.util.DumpUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080097import com.android.internal.util.FastXmlSerializer;
Makoto Onuki068c54a2015-10-13 14:34:03 -070098import com.android.internal.util.Preconditions;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070099import com.android.internal.util.XmlUtils;
Clara Bayarri10ad84a2015-12-01 17:38:05 +0000100import com.android.internal.widget.LockPatternUtils;
Amith Yamasani515d4062015-09-28 11:30:06 -0700101import com.android.server.LocalServices;
Jeff Sharkey5f3e9342017-03-13 14:53:11 -0600102import com.android.server.LockGuard;
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700103import com.android.server.SystemService;
Amith Yamasaniea1b9d72016-05-27 15:57:38 +0000104import com.android.server.am.UserState;
Suprabh Shuklac5e057c2016-08-08 16:22:44 -0700105import com.android.server.storage.DeviceStorageMonitorInternal;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700106import com.android.server.wm.ActivityTaskManagerInternal;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800107
arangelov9b632d72018-12-07 23:21:22 +0000108import libcore.io.IoUtils;
109
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800110import org.xmlpull.v1.XmlPullParser;
111import org.xmlpull.v1.XmlPullParserException;
112import org.xmlpull.v1.XmlSerializer;
113
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700114import java.io.BufferedOutputStream;
115import java.io.File;
Amith Yamasani920ace02012-09-20 22:15:37 -0700116import java.io.FileDescriptor;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700117import java.io.FileInputStream;
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700118import java.io.FileNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700119import java.io.FileOutputStream;
Tony Mak64fd8c02017-12-01 19:11:59 +0000120import java.io.IOException;
Kenny Guy02c89902016-11-15 19:36:38 +0000121import java.io.InputStream;
122import java.io.OutputStream;
Amith Yamasani920ace02012-09-20 22:15:37 -0700123import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100124import java.nio.charset.StandardCharsets;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700125import java.util.ArrayList;
Pavel Grafov6a40f092016-10-25 15:46:51 +0100126import java.util.Collections;
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700127import java.util.LinkedList;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700128import java.util.List;
Narayan Kamath607223f2018-02-19 14:09:02 +0000129import java.util.Objects;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700130
Makoto Onuki068c54a2015-10-13 14:34:03 -0700131/**
132 * Service for {@link UserManager}.
133 *
134 * Method naming convention:
Fyodor Kupolov82402752015-10-28 14:54:51 -0700135 * <ul>
Fyodor Kupolovd31cee92017-09-05 16:31:08 -0700136 * <li> Methods suffixed with "LAr" should be called within the {@link #mAppRestrictionsLock} lock.
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800137 * <li> Methods suffixed with "LP" should be called within the {@link #mPackagesLock} lock.
Fyodor Kupolov82402752015-10-28 14:54:51 -0700138 * <li> Methods suffixed with "LR" should be called within the {@link #mRestrictionsLock} lock.
139 * <li> Methods suffixed with "LU" should be called within the {@link #mUsersLock} lock.
140 * </ul>
Makoto Onuki068c54a2015-10-13 14:34:03 -0700141 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700142public class UserManagerService extends IUserManager.Stub {
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700143
Amith Yamasani2a003292012-08-14 18:25:45 -0700144 private static final String LOG_TAG = "UserManagerService";
Makoto Onuki81c61ea2016-01-22 11:22:26 -0800145 static final boolean DBG = false; // DO NOT SUBMIT WITH TRUE
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800146 private static final boolean DBG_WITH_STACKTRACE = false; // DO NOT SUBMIT WITH TRUE
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700147 // Can be used for manual testing of id recycling
148 private static final boolean RELEASE_DELETED_USER_ID = false; // DO NOT SUBMIT WITH TRUE
Amith Yamasani16389312012-10-17 21:20:14 -0700149
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700150 private static final String TAG_NAME = "name";
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800151 private static final String TAG_ACCOUNT = "account";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700152 private static final String ATTR_FLAGS = "flags";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700153 private static final String ATTR_ICON_PATH = "icon";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700154 private static final String ATTR_ID = "id";
Amith Yamasani920ace02012-09-20 22:15:37 -0700155 private static final String ATTR_CREATION_TIME = "created";
156 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -0600157 private static final String ATTR_LAST_LOGGED_IN_FINGERPRINT = "lastLoggedInFingerprint";
Amith Yamasani2a003292012-08-14 18:25:45 -0700158 private static final String ATTR_SERIAL_NO = "serialNumber";
159 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700160 private static final String ATTR_PARTIAL = "partial";
Felipe Leme7ad2f6b2019-09-11 09:23:26 -0700161 private static final String ATTR_PRE_CREATED = "preCreated";
Adam Lesinskieddeb492014-09-08 17:50:03 -0700162 private static final String ATTR_GUEST_TO_REMOVE = "guestToRemove";
Amith Yamasani6f34b412012-10-22 18:19:27 -0700163 private static final String ATTR_USER_VERSION = "version";
Kenny Guy2a764942014-04-02 13:29:20 +0100164 private static final String ATTR_PROFILE_GROUP_ID = "profileGroupId";
Kenny Guy02c89902016-11-15 19:36:38 +0000165 private static final String ATTR_PROFILE_BADGE = "profileBadge";
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700166 private static final String ATTR_RESTRICTED_PROFILE_PARENT_ID = "restrictedProfileParentId";
Amith Yamasani12747872015-12-07 14:19:49 -0800167 private static final String ATTR_SEED_ACCOUNT_NAME = "seedAccountName";
168 private static final String ATTR_SEED_ACCOUNT_TYPE = "seedAccountType";
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530169 private static final String TAG_GUEST_RESTRICTIONS = "guestRestrictions";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700170 private static final String TAG_USERS = "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700171 private static final String TAG_USER = "user";
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800172 private static final String TAG_RESTRICTIONS = "restrictions";
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800173 private static final String TAG_DEVICE_POLICY_RESTRICTIONS = "device_policy_restrictions";
Pavel Grafov6a40f092016-10-25 15:46:51 +0100174 private static final String TAG_DEVICE_POLICY_GLOBAL_RESTRICTIONS =
175 "device_policy_global_restrictions";
176 /** Legacy name for device owner id tag. */
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +0100177 private static final String TAG_GLOBAL_RESTRICTION_OWNER_ID = "globalRestrictionOwnerUserId";
Pavel Grafov6a40f092016-10-25 15:46:51 +0100178 private static final String TAG_DEVICE_OWNER_USER_ID = "deviceOwnerUserId";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800179 private static final String TAG_ENTRY = "entry";
180 private static final String TAG_VALUE = "value";
Amith Yamasani12747872015-12-07 14:19:49 -0800181 private static final String TAG_SEED_ACCOUNT_OPTIONS = "seedAccountOptions";
arangelov9b632d72018-12-07 23:21:22 +0000182 private static final String TAG_LAST_REQUEST_QUIET_MODE_ENABLED_CALL =
183 "lastRequestQuietModeEnabledCall";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800184 private static final String ATTR_KEY = "key";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700185 private static final String ATTR_VALUE_TYPE = "type";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800186 private static final String ATTR_MULTIPLE = "m";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700187
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700188 private static final String ATTR_TYPE_STRING_ARRAY = "sa";
189 private static final String ATTR_TYPE_STRING = "s";
190 private static final String ATTR_TYPE_BOOLEAN = "b";
Amith Yamasani5b5aa402014-06-01 20:10:14 -0700191 private static final String ATTR_TYPE_INTEGER = "i";
Fyodor Kupolov262f9952015-03-23 18:55:11 -0700192 private static final String ATTR_TYPE_BUNDLE = "B";
193 private static final String ATTR_TYPE_BUNDLE_ARRAY = "BA";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700194
Amith Yamasani0b285492011-04-14 17:35:23 -0700195 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700196 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700197 private static final String USER_PHOTO_FILENAME = "photo.png";
Adrian Roos1bdff912015-02-17 15:51:35 +0100198 private static final String USER_PHOTO_FILENAME_TMP = USER_PHOTO_FILENAME + ".tmp";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700199
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800200 private static final String RESTRICTIONS_FILE_PREFIX = "res_";
Amith Yamasanifc95e702013-09-26 13:20:17 -0700201 private static final String XML_SUFFIX = ".xml";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800202
Sudheer Shankaf5cea032016-06-08 17:13:24 -0700203 private static final int ALLOWED_FLAGS_FOR_CREATE_USERS_PERMISSION =
204 UserInfo.FLAG_MANAGED_PROFILE
205 | UserInfo.FLAG_EPHEMERAL
206 | UserInfo.FLAG_RESTRICTED
Sudheer Shanka234d1af2016-08-26 15:42:53 -0700207 | UserInfo.FLAG_GUEST
208 | UserInfo.FLAG_DEMO;
Sudheer Shankaf5cea032016-06-08 17:13:24 -0700209
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700210 @VisibleForTesting
211 static final int MIN_USER_ID = 10;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700212 // We need to keep process uid within Integer.MAX_VALUE.
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700213 @VisibleForTesting
214 static final int MAX_USER_ID = Integer.MAX_VALUE / UserHandle.PER_USER_RANGE;
215
216 // Max size of the queue of recently removed users
217 @VisibleForTesting
218 static final int MAX_RECENTLY_REMOVED_IDS_SIZE = 100;
Amith Yamasani634cf312012-10-04 17:34:21 -0700219
Pavel Grafov6a40f092016-10-25 15:46:51 +0100220 private static final int USER_VERSION = 7;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700221
Amith Yamasani920ace02012-09-20 22:15:37 -0700222 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
223
Nicolas Prevotb8186812015-08-06 15:00:03 +0100224 // Maximum number of managed profiles permitted per user is 1. This cannot be increased
Amith Yamasani95ab7842014-08-11 17:09:26 -0700225 // without first making sure that the rest of the framework is prepared for it.
Kenny Guy02c89902016-11-15 19:36:38 +0000226 @VisibleForTesting
227 static final int MAX_MANAGED_PROFILES = 1;
Amith Yamasani95ab7842014-08-11 17:09:26 -0700228
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800229 static final int WRITE_USER_MSG = 1;
230 static final int WRITE_USER_DELAY = 2*1000; // 2 seconds
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530231
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -0800232 // Tron counters
233 private static final String TRON_GUEST_CREATED = "users_guest_created";
234 private static final String TRON_USER_CREATED = "users_user_created";
Christine Franks88220562017-05-24 11:11:21 -0700235 private static final String TRON_DEMO_CREATED = "users_demo_created";
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -0800236
Dianne Hackborn4428e172012-08-24 17:43:05 -0700237 private final Context mContext;
238 private final PackageManagerService mPm;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700239 private final Object mPackagesLock;
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800240 private final UserDataPreparer mUserDataPreparer;
Fyodor Kupolov82402752015-10-28 14:54:51 -0700241 // Short-term lock for internal state, when interaction/sync with PM is not required
Jeff Sharkey5f3e9342017-03-13 14:53:11 -0600242 private final Object mUsersLock = LockGuard.installNewLock(LockGuard.INDEX_USER);
Fyodor Kupolov82402752015-10-28 14:54:51 -0700243 private final Object mRestrictionsLock = new Object();
Fyodor Kupolovd31cee92017-09-05 16:31:08 -0700244 // Used for serializing access to app restriction files
245 private final Object mAppRestrictionsLock = new Object();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700246
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800247 private final Handler mHandler;
248
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700249 private final File mUsersDir;
250 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700251
Svet Ganov9cea80cd2016-02-16 11:47:00 -0800252 private static final IBinder mUserRestriconToken = new Binder();
253
Makoto Onuki068c54a2015-10-13 14:34:03 -0700254 /**
Makoto Onuki73dded22017-12-20 13:14:48 +0900255 * Internal non-parcelable wrapper for UserInfo that is not exposed to other system apps.
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800256 */
Kenny Guy02c89902016-11-15 19:36:38 +0000257 @VisibleForTesting
258 static class UserData {
Amith Yamasani12747872015-12-07 14:19:49 -0800259 // Basic user information and properties
260 UserInfo info;
261 // Account name used when there is a strong association between a user and an account
262 String account;
263 // Account information for seeding into a newly created user. This could also be
264 // used for login validation for an existing user, for updating their credentials.
265 // In the latter case, data may not need to be persisted as it is only valid for the
266 // current login session.
267 String seedAccountName;
268 String seedAccountType;
269 PersistableBundle seedAccountOptions;
270 // Whether to perist the seed account information to be available after a boot
271 boolean persistSeedData;
272
Makoto Onuki73dded22017-12-20 13:14:48 +0900273 /** Elapsed realtime since boot when the user started. */
274 long startRealtime;
275
276 /** Elapsed realtime since boot when the user was unlocked. */
277 long unlockRealtime;
278
arangelov9b632d72018-12-07 23:21:22 +0000279 private long mLastRequestQuietModeEnabledMillis;
280
281 void setLastRequestQuietModeEnabledMillis(long millis) {
282 mLastRequestQuietModeEnabledMillis = millis;
283 }
284
285 long getLastRequestQuietModeEnabledMillis() {
286 return mLastRequestQuietModeEnabledMillis;
287 }
288
Amith Yamasani12747872015-12-07 14:19:49 -0800289 void clearSeedAccountData() {
290 seedAccountName = null;
291 seedAccountType = null;
292 seedAccountOptions = null;
293 persistSeedData = false;
294 }
295 }
296
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800297 @GuardedBy("mUsersLock")
Amith Yamasani12747872015-12-07 14:19:49 -0800298 private final SparseArray<UserData> mUsers = new SparseArray<>();
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800299
300 /**
Makoto Onuki068c54a2015-10-13 14:34:03 -0700301 * User restrictions set via UserManager. This doesn't include restrictions set by
Pavel Grafov6a40f092016-10-25 15:46:51 +0100302 * device owner / profile owners. Only non-empty restriction bundles are stored.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700303 *
304 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
305 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
306 * maybe shared between {@link #mBaseUserRestrictions} and
307 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
308 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700309 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700310 */
311 @GuardedBy("mRestrictionsLock")
312 private final SparseArray<Bundle> mBaseUserRestrictions = new SparseArray<>();
313
314 /**
315 * Cached user restrictions that are in effect -- i.e. {@link #mBaseUserRestrictions} combined
316 * with device / profile owner restrictions. We'll initialize it lazily; use
317 * {@link #getEffectiveUserRestrictions} to access it.
318 *
319 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
320 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
321 * maybe shared between {@link #mBaseUserRestrictions} and
322 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
323 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700324 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700325 */
326 @GuardedBy("mRestrictionsLock")
327 private final SparseArray<Bundle> mCachedEffectiveUserRestrictions = new SparseArray<>();
328
Makoto Onuki4f160732015-10-27 17:15:38 -0700329 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800330 * User restrictions that have already been applied in
331 * {@link #updateUserRestrictionsInternalLR(Bundle, int)}. We use it to detect restrictions
332 * that have changed since the last
333 * {@link #updateUserRestrictionsInternalLR(Bundle, int)} call.
Makoto Onuki4f160732015-10-27 17:15:38 -0700334 */
335 @GuardedBy("mRestrictionsLock")
336 private final SparseArray<Bundle> mAppliedUserRestrictions = new SparseArray<>();
337
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800338 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800339 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
Pavel Grafov6a40f092016-10-25 15:46:51 +0100340 * that should be applied to all users, including guests. Only non-empty restriction bundles are
341 * stored.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800342 */
343 @GuardedBy("mRestrictionsLock")
Pavel Grafov6a40f092016-10-25 15:46:51 +0100344 private final SparseArray<Bundle> mDevicePolicyGlobalUserRestrictions = new SparseArray<>();
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800345
346 /**
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +0100347 * Id of the user that set global restrictions.
348 */
349 @GuardedBy("mRestrictionsLock")
Pavel Grafov6a40f092016-10-25 15:46:51 +0100350 private int mDeviceOwnerUserId = UserHandle.USER_NULL;
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +0100351
352 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800353 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
Pavel Grafov6a40f092016-10-25 15:46:51 +0100354 * for each user. Only non-empty restriction bundles are stored.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800355 */
356 @GuardedBy("mRestrictionsLock")
357 private final SparseArray<Bundle> mDevicePolicyLocalUserRestrictions = new SparseArray<>();
358
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800359 @GuardedBy("mGuestRestrictions")
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530360 private final Bundle mGuestRestrictions = new Bundle();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800361
362 /**
363 * Set of user IDs being actively removed. Removed IDs linger in this set
364 * for several seconds to work around a VFS caching issue.
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700365 * Use {@link #addRemovingUserIdLocked(int)} to add elements to this array
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800366 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700367 @GuardedBy("mUsersLock")
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800368 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700369
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700370 /**
371 * Queue of recently removed userIds. Used for recycling of userIds
372 */
373 @GuardedBy("mUsersLock")
374 private final LinkedList<Integer> mRecentlyRemovedIds = new LinkedList<>();
375
Fyodor Kupolov82402752015-10-28 14:54:51 -0700376 @GuardedBy("mUsersLock")
Amith Yamasani0b285492011-04-14 17:35:23 -0700377 private int[] mUserIds;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800378 @GuardedBy("mPackagesLock")
Amith Yamasani2a003292012-08-14 18:25:45 -0700379 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700380 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700381
Jason Monk62062992014-05-06 09:55:28 -0400382 private IAppOpsService mAppOpsService;
383
Makoto Onuki068c54a2015-10-13 14:34:03 -0700384 private final LocalService mLocalService;
385
Makoto Onukie7927da2015-11-25 10:05:17 -0800386 @GuardedBy("mUsersLock")
387 private boolean mIsDeviceManaged;
388
389 @GuardedBy("mUsersLock")
390 private final SparseBooleanArray mIsUserManaged = new SparseBooleanArray();
391
Makoto Onukid45a4a22015-11-02 17:17:38 -0800392 @GuardedBy("mUserRestrictionsListeners")
393 private final ArrayList<UserRestrictionsListener> mUserRestrictionsListeners =
394 new ArrayList<>();
395
Clara Bayarria1771112015-12-18 16:29:18 +0000396 private final LockPatternUtils mLockPatternUtils;
397
Ricky Waib1dd80b2016-06-07 18:00:55 +0100398 private final String ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK =
399 "com.android.server.pm.DISABLE_QUIET_MODE_AFTER_UNLOCK";
400
401 private final BroadcastReceiver mDisableQuietModeCallback = new BroadcastReceiver() {
402 @Override
403 public void onReceive(Context context, Intent intent) {
Tony Mak64fd8c02017-12-01 19:11:59 +0000404 if (!ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK.equals(intent.getAction())) {
405 return;
Ricky Waib1dd80b2016-06-07 18:00:55 +0100406 }
Tony Mak64fd8c02017-12-01 19:11:59 +0000407 final IntentSender target = intent.getParcelableExtra(Intent.EXTRA_INTENT);
408 final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_ID, UserHandle.USER_NULL);
Fyodor Kupolova68a2862018-01-30 18:22:00 -0800409 // Call setQuietModeEnabled on bg thread to avoid ANR
arangelov9b632d72018-12-07 23:21:22 +0000410 BackgroundThread.getHandler().post(() ->
411 setQuietModeEnabled(userHandle, false, target, /* callingPackage */ null));
Ricky Waib1dd80b2016-06-07 18:00:55 +0100412 }
413 };
414
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +0100415 /**
Tony Mak64fd8c02017-12-01 19:11:59 +0000416 * Start an {@link IntentSender} when user is unlocked after disabling quiet mode.
417 *
Tony Makbece85d2018-01-12 12:10:17 +0000418 * @see {@link #requestQuietModeEnabled(String, boolean, int, IntentSender)}
Tony Mak64fd8c02017-12-01 19:11:59 +0000419 */
420 private class DisableQuietModeUserUnlockedCallback extends IProgressListener.Stub {
421 private final IntentSender mTarget;
422
423 public DisableQuietModeUserUnlockedCallback(IntentSender target) {
424 Preconditions.checkNotNull(target);
425 mTarget = target;
426 }
427
428 @Override
429 public void onStarted(int id, Bundle extras) {}
430
431 @Override
432 public void onProgress(int id, int progress, Bundle extras) {}
433
434 @Override
435 public void onFinished(int id, Bundle extras) {
436 try {
437 mContext.startIntentSender(mTarget, null, 0, 0, 0);
438 } catch (IntentSender.SendIntentException e) {
439 Slog.e(LOG_TAG, "Failed to start the target in the callback", e);
440 }
441 }
442 }
443
444 /**
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +0100445 * Whether all users should be created ephemeral.
446 */
447 @GuardedBy("mUsersLock")
448 private boolean mForceEphemeralUsers;
449
Amith Yamasaniea1b9d72016-05-27 15:57:38 +0000450 @GuardedBy("mUserStates")
451 private final SparseIntArray mUserStates = new SparseIntArray();
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -0700452
Amith Yamasani258848d2012-08-10 17:06:33 -0700453 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700454
Dianne Hackborn4428e172012-08-24 17:43:05 -0700455 public static UserManagerService getInstance() {
456 synchronized (UserManagerService.class) {
457 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700458 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700459 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700460
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700461 public static class LifeCycle extends SystemService {
462
463 private UserManagerService mUms;
464
465 /**
466 * @param context
467 */
468 public LifeCycle(Context context) {
469 super(context);
470 }
471
472 @Override
473 public void onStart() {
474 mUms = UserManagerService.getInstance();
475 publishBinderService(Context.USER_SERVICE, mUms);
476 }
477
478 @Override
479 public void onBootPhase(int phase) {
480 if (phase == SystemService.PHASE_ACTIVITY_MANAGER_READY) {
481 mUms.cleanupPartialUsers();
482 }
483 }
Makoto Onuki73dded22017-12-20 13:14:48 +0900484
485 @Override
486 public void onStartUser(int userHandle) {
487 synchronized (mUms.mUsersLock) {
488 final UserData user = mUms.getUserDataLU(userHandle);
489 if (user != null) {
490 user.startRealtime = SystemClock.elapsedRealtime();
491 }
492 }
493 }
494
495 @Override
496 public void onUnlockUser(int userHandle) {
497 synchronized (mUms.mUsersLock) {
498 final UserData user = mUms.getUserDataLU(userHandle);
499 if (user != null) {
500 user.unlockRealtime = SystemClock.elapsedRealtime();
501 }
502 }
503 }
504
505 @Override
506 public void onStopUser(int userHandle) {
507 synchronized (mUms.mUsersLock) {
508 final UserData user = mUms.getUserDataLU(userHandle);
509 if (user != null) {
510 user.startRealtime = 0;
511 user.unlockRealtime = 0;
512 }
513 }
514 }
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700515 }
516
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700517 // TODO b/28848102 Add support for test dependencies injection
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800518 @VisibleForTesting
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700519 UserManagerService(Context context) {
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800520 this(context, null, null, new Object(), context.getCacheDir());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700521 }
522
Dianne Hackborn4428e172012-08-24 17:43:05 -0700523 /**
524 * Called by package manager to create the service. This is closely
525 * associated with the package manager, and the given lock is the
526 * package manager's own lock.
527 */
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800528 UserManagerService(Context context, PackageManagerService pm, UserDataPreparer userDataPreparer,
529 Object packagesLock) {
530 this(context, pm, userDataPreparer, packagesLock, Environment.getDataDirectory());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700531 }
532
Dianne Hackborn4428e172012-08-24 17:43:05 -0700533 private UserManagerService(Context context, PackageManagerService pm,
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800534 UserDataPreparer userDataPreparer, Object packagesLock, File dataDir) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700535 mContext = context;
536 mPm = pm;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700537 mPackagesLock = packagesLock;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800538 mHandler = new MainHandler();
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800539 mUserDataPreparer = userDataPreparer;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800540 synchronized (mPackagesLock) {
541 mUsersDir = new File(dataDir, USER_INFO_DIR);
542 mUsersDir.mkdirs();
543 // Make zeroth user directory, for services to migrate their files to that location
544 File userZeroDir = new File(mUsersDir, String.valueOf(UserHandle.USER_SYSTEM));
545 userZeroDir.mkdirs();
546 FileUtils.setPermissions(mUsersDir.toString(),
547 FileUtils.S_IRWXU | FileUtils.S_IRWXG | FileUtils.S_IROTH | FileUtils.S_IXOTH,
548 -1, -1);
549 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
550 initDefaultGuestRestrictions();
551 readUserListLP();
552 sInstance = this;
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700553 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700554 mLocalService = new LocalService();
555 LocalServices.addService(UserManagerInternal.class, mLocalService);
Clara Bayarria1771112015-12-18 16:29:18 +0000556 mLockPatternUtils = new LockPatternUtils(mContext);
Amith Yamasaniea1b9d72016-05-27 15:57:38 +0000557 mUserStates.put(UserHandle.USER_SYSTEM, UserState.STATE_BOOTING);
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700558 }
559
560 void systemReady() {
Jason Monk62062992014-05-06 09:55:28 -0400561 mAppOpsService = IAppOpsService.Stub.asInterface(
562 ServiceManager.getService(Context.APP_OPS_SERVICE));
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800563
564 synchronized (mRestrictionsLock) {
565 applyUserRestrictionsLR(UserHandle.USER_SYSTEM);
Jason Monk62062992014-05-06 09:55:28 -0400566 }
Samuel Tand9453b82016-03-14 15:57:02 -0700567
568 UserInfo currentGuestUser = findCurrentGuestUser();
569 if (currentGuestUser != null && !hasUserRestriction(
570 UserManager.DISALLOW_CONFIG_WIFI, currentGuestUser.id)) {
571 // If a guest user currently exists, apply the DISALLOW_CONFIG_WIFI option
572 // to it, in case this guest was created in a previous version where this
573 // user restriction was not a default guest restriction.
574 setUserRestriction(UserManager.DISALLOW_CONFIG_WIFI, true, currentGuestUser.id);
575 }
Amith Yamasanieb437d42016-04-29 09:31:25 -0700576
Ricky Waib1dd80b2016-06-07 18:00:55 +0100577 mContext.registerReceiver(mDisableQuietModeCallback,
578 new IntentFilter(ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK),
579 null, mHandler);
Amith Yamasani258848d2012-08-10 17:06:33 -0700580 }
581
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700582 void cleanupPartialUsers() {
583 // Prune out any partially created, partially removed and ephemeral users.
584 ArrayList<UserInfo> partials = new ArrayList<>();
585 synchronized (mUsersLock) {
586 final int userSize = mUsers.size();
587 for (int i = 0; i < userSize; i++) {
588 UserInfo ui = mUsers.valueAt(i).info;
Felipe Leme7ad2f6b2019-09-11 09:23:26 -0700589 if ((ui.partial || ui.guestToRemove || (ui.isEphemeral() && !ui.preCreated))
590 && i != 0) {
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700591 partials.add(ui);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700592 addRemovingUserIdLocked(ui.id);
Amith Yamasaniae261892016-06-27 10:40:09 -0700593 ui.partial = true;
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700594 }
595 }
596 }
597 final int partialsSize = partials.size();
598 for (int i = 0; i < partialsSize; i++) {
599 UserInfo ui = partials.get(i);
600 Slog.w(LOG_TAG, "Removing partially created user " + ui.id
601 + " (name=" + ui.name + ")");
602 removeUserState(ui.id);
603 }
604 }
605
Amith Yamasani258848d2012-08-10 17:06:33 -0700606 @Override
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800607 public String getUserAccount(int userId) {
608 checkManageUserAndAcrossUsersFullPermission("get user account");
609 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800610 return mUsers.get(userId).account;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800611 }
612 }
613
614 @Override
615 public void setUserAccount(int userId, String accountName) {
616 checkManageUserAndAcrossUsersFullPermission("set user account");
Amith Yamasani12747872015-12-07 14:19:49 -0800617 UserData userToUpdate = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800618 synchronized (mPackagesLock) {
619 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800620 final UserData userData = mUsers.get(userId);
621 if (userData == null) {
622 Slog.e(LOG_TAG, "User not found for setting user account: u" + userId);
623 return;
624 }
625 String currentAccount = userData.account;
Narayan Kamath607223f2018-02-19 14:09:02 +0000626 if (!Objects.equals(currentAccount, accountName)) {
Amith Yamasani12747872015-12-07 14:19:49 -0800627 userData.account = accountName;
628 userToUpdate = userData;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800629 }
630 }
631
632 if (userToUpdate != null) {
633 writeUserLP(userToUpdate);
634 }
635 }
636 }
637
638 @Override
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700639 public UserInfo getPrimaryUser() {
640 checkManageUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700641 synchronized (mUsersLock) {
Amith Yamasani515d4062015-09-28 11:30:06 -0700642 final int userSize = mUsers.size();
643 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800644 UserInfo ui = mUsers.valueAt(i).info;
Xiaohui Chend3e9e182015-11-18 13:37:32 -0800645 if (ui.isPrimary() && !mRemovingUserIds.get(ui.id)) {
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700646 return ui;
647 }
648 }
649 }
650 return null;
651 }
652
Xiaohui Chen594f2082015-08-18 11:04:20 -0700653 public @NonNull List<UserInfo> getUsers(boolean excludeDying) {
Felipe Leme7ad2f6b2019-09-11 09:23:26 -0700654 return getUsers(/*excludePartial= */ true, excludeDying, /* excludePreCreated= */ true);
655 }
656
Felipe Leme0b3863f2019-10-02 16:27:46 -0700657 @Override
658 public @NonNull List<UserInfo> getUsers(boolean excludePartial, boolean excludeDying,
Felipe Leme7ad2f6b2019-09-11 09:23:26 -0700659 boolean excludePreCreated) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -0700660 checkManageOrCreateUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700661 synchronized (mUsersLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700662 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasani515d4062015-09-28 11:30:06 -0700663 final int userSize = mUsers.size();
664 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800665 UserInfo ui = mUsers.valueAt(i).info;
Felipe Leme7ad2f6b2019-09-11 09:23:26 -0700666 if ((excludePartial && ui.partial)
667 || (excludeDying && mRemovingUserIds.get(ui.id))
668 || (excludePreCreated && ui.preCreated)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700669 continue;
670 }
Felipe Leme7ad2f6b2019-09-11 09:23:26 -0700671 users.add(userWithName(ui));
Amith Yamasani13593602012-03-22 16:16:17 -0700672 }
673 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700674 }
Amith Yamasani13593602012-03-22 16:16:17 -0700675 }
676
Amith Yamasani258848d2012-08-10 17:06:33 -0700677 @Override
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100678 public List<UserInfo> getProfiles(int userId, boolean enabledOnly) {
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700679 boolean returnFullInfo = true;
Amith Yamasani4f582632014-02-19 14:31:52 -0800680 if (userId != UserHandle.getCallingUserId()) {
Sudheer Shanka74680912016-07-29 11:03:37 -0700681 checkManageOrCreateUsersPermission("getting profiles related to user " + userId);
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700682 } else {
683 returnFullInfo = hasManageUsersPermission();
Amith Yamasani4f582632014-02-19 14:31:52 -0800684 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700685 final long ident = Binder.clearCallingIdentity();
686 try {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700687 synchronized (mUsersLock) {
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700688 return getProfilesLU(userId, enabledOnly, returnFullInfo);
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100689 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700690 } finally {
691 Binder.restoreCallingIdentity(ident);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000692 }
693 }
694
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700695 @Override
696 public int[] getProfileIds(int userId, boolean enabledOnly) {
697 if (userId != UserHandle.getCallingUserId()) {
bohu12d23a12016-09-26 16:20:07 -0700698 checkManageOrCreateUsersPermission("getting profiles related to user " + userId);
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700699 }
700 final long ident = Binder.clearCallingIdentity();
701 try {
702 synchronized (mUsersLock) {
703 return getProfileIdsLU(userId, enabledOnly).toArray();
704 }
705 } finally {
706 Binder.restoreCallingIdentity(ident);
707 }
708 }
709
Amith Yamasanibe465322014-04-24 13:45:17 -0700710 /** Assume permissions already checked and caller's identity cleared */
Andreas Gampe2e8c7672018-07-20 13:01:08 -0700711 @GuardedBy("mUsersLock")
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700712 private List<UserInfo> getProfilesLU(int userId, boolean enabledOnly, boolean fullInfo) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700713 IntArray profileIds = getProfileIdsLU(userId, enabledOnly);
714 ArrayList<UserInfo> users = new ArrayList<>(profileIds.size());
715 for (int i = 0; i < profileIds.size(); i++) {
716 int profileId = profileIds.get(i);
717 UserInfo userInfo = mUsers.get(profileId).info;
718 // If full info is not required - clear PII data to prevent 3P apps from reading it
719 if (!fullInfo) {
720 userInfo = new UserInfo(userInfo);
721 userInfo.name = null;
722 userInfo.iconPath = null;
723 } else {
724 userInfo = userWithName(userInfo);
725 }
726 users.add(userInfo);
727 }
728 return users;
729 }
730
731 /**
732 * Assume permissions already checked and caller's identity cleared
733 */
Andreas Gampe2e8c7672018-07-20 13:01:08 -0700734 @GuardedBy("mUsersLock")
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700735 private IntArray getProfileIdsLU(int userId, boolean enabledOnly) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700736 UserInfo user = getUserInfoLU(userId);
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700737 IntArray result = new IntArray(mUsers.size());
Amith Yamasanidda003f2014-08-28 18:06:51 -0700738 if (user == null) {
739 // Probably a dying user
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700740 return result;
Amith Yamasanidda003f2014-08-28 18:06:51 -0700741 }
Amith Yamasani515d4062015-09-28 11:30:06 -0700742 final int userSize = mUsers.size();
743 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800744 UserInfo profile = mUsers.valueAt(i).info;
Amith Yamasanibe465322014-04-24 13:45:17 -0700745 if (!isProfileOf(user, profile)) {
746 continue;
747 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100748 if (enabledOnly && !profile.isEnabled()) {
749 continue;
Amith Yamasanibe465322014-04-24 13:45:17 -0700750 }
Amith Yamasani70fcf0c2014-07-11 08:40:19 -0700751 if (mRemovingUserIds.get(profile.id)) {
752 continue;
753 }
Tony Mak80189cd2016-04-05 17:21:42 +0100754 if (profile.partial) {
755 continue;
756 }
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700757 result.add(profile.id);
Amith Yamasanibe465322014-04-24 13:45:17 -0700758 }
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700759 return result;
Amith Yamasanibe465322014-04-24 13:45:17 -0700760 }
761
Jessica Hummelbe81c802014-04-22 15:49:22 +0100762 @Override
Andres Moralesc5548c02015-08-05 10:23:12 -0700763 public int getCredentialOwnerProfile(int userHandle) {
764 checkManageUsersPermission("get the credential owner");
Clara Bayarria1771112015-12-18 16:29:18 +0000765 if (!mLockPatternUtils.isSeparateProfileChallengeEnabled(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700766 synchronized (mUsersLock) {
767 UserInfo profileParent = getProfileParentLU(userHandle);
Andres Moralesc5548c02015-08-05 10:23:12 -0700768 if (profileParent != null) {
769 return profileParent.id;
770 }
771 }
772 }
773
774 return userHandle;
775 }
776
777 @Override
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700778 public boolean isSameProfileGroup(int userId, int otherUserId) {
779 if (userId == otherUserId) return true;
780 checkManageUsersPermission("check if in the same profile group");
Fyodor Kupolov0fb772e2016-10-13 16:27:34 -0700781 return isSameProfileGroupNoChecks(userId, otherUserId);
782 }
783
784 private boolean isSameProfileGroupNoChecks(int userId, int otherUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700785 synchronized (mUsersLock) {
786 UserInfo userInfo = getUserInfoLU(userId);
787 if (userInfo == null || userInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
788 return false;
789 }
790 UserInfo otherUserInfo = getUserInfoLU(otherUserId);
791 if (otherUserInfo == null
792 || otherUserInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
793 return false;
794 }
795 return userInfo.profileGroupId == otherUserInfo.profileGroupId;
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700796 }
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700797 }
798
799 @Override
Jessica Hummelbe81c802014-04-22 15:49:22 +0100800 public UserInfo getProfileParent(int userHandle) {
801 checkManageUsersPermission("get the profile parent");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700802 synchronized (mUsersLock) {
803 return getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700804 }
805 }
806
Jakub Pawlowski0f1f5b72017-11-15 14:50:43 -0800807 @Override
808 public int getProfileParentId(int userHandle) {
809 checkManageUsersPermission("get the profile parent");
Sunny Goyal145c8f82018-02-15 14:27:09 -0800810 return mLocalService.getProfileParentId(userHandle);
Jakub Pawlowski0f1f5b72017-11-15 14:50:43 -0800811 }
812
Andreas Gampe2e8c7672018-07-20 13:01:08 -0700813 @GuardedBy("mUsersLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -0700814 private UserInfo getProfileParentLU(int userHandle) {
815 UserInfo profile = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700816 if (profile == null) {
817 return null;
818 }
819 int parentUserId = profile.profileGroupId;
Amith Yamasani801e3422017-01-25 11:35:44 -0800820 if (parentUserId == userHandle || parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700821 return null;
822 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700823 return getUserInfoLU(parentUserId);
Jessica Hummelbe81c802014-04-22 15:49:22 +0100824 }
825 }
826
Fyodor Kupolov82402752015-10-28 14:54:51 -0700827 private static boolean isProfileOf(UserInfo user, UserInfo profile) {
Kenny Guy2a764942014-04-02 13:29:20 +0100828 return user.id == profile.id ||
829 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
830 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000831 }
832
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000833 private void broadcastProfileAvailabilityChanges(UserHandle profileHandle,
Rubin Xuf13c9802016-01-21 18:06:00 +0000834 UserHandle parentHandle, boolean inQuietMode) {
Rubin Xue95057a2016-04-01 16:49:25 +0100835 Intent intent = new Intent();
836 if (inQuietMode) {
837 intent.setAction(Intent.ACTION_MANAGED_PROFILE_UNAVAILABLE);
838 } else {
839 intent.setAction(Intent.ACTION_MANAGED_PROFILE_AVAILABLE);
840 }
Rubin Xuf13c9802016-01-21 18:06:00 +0000841 intent.putExtra(Intent.EXTRA_QUIET_MODE, inQuietMode);
842 intent.putExtra(Intent.EXTRA_USER, profileHandle);
843 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileHandle.getIdentifier());
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000844 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Rubin Xuf13c9802016-01-21 18:06:00 +0000845 mContext.sendBroadcastAsUser(intent, parentHandle);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000846 }
847
848 @Override
Tony Makbece85d2018-01-12 12:10:17 +0000849 public boolean requestQuietModeEnabled(@NonNull String callingPackage, boolean enableQuietMode,
Tony Make3d1f652017-12-12 11:00:37 +0000850 int userHandle, @Nullable IntentSender target) {
851 Preconditions.checkNotNull(callingPackage);
852
Tony Makb7e6fd42017-12-05 19:40:28 +0000853 if (enableQuietMode && target != null) {
854 throw new IllegalArgumentException(
855 "target should only be specified when we are disabling quiet mode.");
856 }
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000857
Tony Makd390ae92017-12-28 13:23:10 +0000858 ensureCanModifyQuietMode(callingPackage, Binder.getCallingUid(), target != null);
Tony Makb7e6fd42017-12-05 19:40:28 +0000859 final long identity = Binder.clearCallingIdentity();
860 try {
arangelov9b632d72018-12-07 23:21:22 +0000861 boolean result = false;
Tony Makb7e6fd42017-12-05 19:40:28 +0000862 if (enableQuietMode) {
arangelov9b632d72018-12-07 23:21:22 +0000863 setQuietModeEnabled(
864 userHandle, true /* enableQuietMode */, target, callingPackage);
865 result = true;
Tony Makb7e6fd42017-12-05 19:40:28 +0000866 } else {
867 boolean needToShowConfirmCredential =
868 mLockPatternUtils.isSecure(userHandle)
869 && !StorageManager.isUserKeyUnlocked(userHandle);
870 if (needToShowConfirmCredential) {
871 showConfirmCredentialToDisableQuietMode(userHandle, target);
Tony Makb7e6fd42017-12-05 19:40:28 +0000872 } else {
arangelov9b632d72018-12-07 23:21:22 +0000873 setQuietModeEnabled(
874 userHandle, false /* enableQuietMode */, target, callingPackage);
875 result = true;
Tony Makb7e6fd42017-12-05 19:40:28 +0000876 }
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000877 }
arangelov9b632d72018-12-07 23:21:22 +0000878 return result;
Tony Makb7e6fd42017-12-05 19:40:28 +0000879 } finally {
880 Binder.restoreCallingIdentity(identity);
881 }
882 }
883
Tony Make3d1f652017-12-12 11:00:37 +0000884 /**
Tony Makd390ae92017-12-28 13:23:10 +0000885 * The caller can modify quiet mode if it meets one of these conditions:
Tony Make3d1f652017-12-12 11:00:37 +0000886 * <ul>
887 * <li>Has system UID or root UID</li>
888 * <li>Has {@link Manifest.permission#MODIFY_QUIET_MODE}</li>
889 * <li>Has {@link Manifest.permission#MANAGE_USERS}</li>
890 * </ul>
Tony Makd390ae92017-12-28 13:23:10 +0000891 * <p>
892 * If caller wants to start an intent after disabling the quiet mode, it must has
893 * {@link Manifest.permission#MANAGE_USERS}.
Tony Make3d1f652017-12-12 11:00:37 +0000894 */
Tony Makd390ae92017-12-28 13:23:10 +0000895 private void ensureCanModifyQuietMode(String callingPackage, int callingUid,
896 boolean startIntent) {
Tony Make3d1f652017-12-12 11:00:37 +0000897 if (hasManageUsersPermission()) {
Tony Makd390ae92017-12-28 13:23:10 +0000898 return;
Tony Make3d1f652017-12-12 11:00:37 +0000899 }
Tony Makd390ae92017-12-28 13:23:10 +0000900 if (startIntent) {
901 throw new SecurityException("MANAGE_USERS permission is required to start intent "
902 + "after disabling quiet mode.");
903 }
jovanakf24ad492018-05-18 12:15:59 -0700904 final boolean hasModifyQuietModePermission = hasPermissionGranted(
905 Manifest.permission.MODIFY_QUIET_MODE, callingUid);
Tony Make3d1f652017-12-12 11:00:37 +0000906 if (hasModifyQuietModePermission) {
Tony Makd390ae92017-12-28 13:23:10 +0000907 return;
Tony Make3d1f652017-12-12 11:00:37 +0000908 }
909
Tony Makd390ae92017-12-28 13:23:10 +0000910 verifyCallingPackage(callingPackage, callingUid);
Tony Make3d1f652017-12-12 11:00:37 +0000911 final ShortcutServiceInternal shortcutInternal =
912 LocalServices.getService(ShortcutServiceInternal.class);
913 if (shortcutInternal != null) {
914 boolean isForegroundLauncher =
915 shortcutInternal.isForegroundDefaultLauncher(callingPackage, callingUid);
916 if (isForegroundLauncher) {
Tony Makd390ae92017-12-28 13:23:10 +0000917 return;
Tony Make3d1f652017-12-12 11:00:37 +0000918 }
919 }
Tony Makd390ae92017-12-28 13:23:10 +0000920 throw new SecurityException("Can't modify quiet mode, caller is neither foreground "
921 + "default launcher nor has MANAGE_USERS/MODIFY_QUIET_MODE permission");
Tony Make3d1f652017-12-12 11:00:37 +0000922 }
923
arangelov9b632d72018-12-07 23:21:22 +0000924 private void setQuietModeEnabled(int userHandle, boolean enableQuietMode,
925 IntentSender target, @Nullable String callingPackage) {
Tony Makb7e6fd42017-12-05 19:40:28 +0000926 final UserInfo profile, parent;
927 final UserData profileUserData;
928 synchronized (mUsersLock) {
929 profile = getUserInfoLU(userHandle);
930 parent = getProfileParentLU(userHandle);
931
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000932 if (profile == null || !profile.isManagedProfile()) {
933 throw new IllegalArgumentException("User " + userHandle + " is not a profile");
934 }
Tony Makb7e6fd42017-12-05 19:40:28 +0000935 if (profile.isQuietModeEnabled() == enableQuietMode) {
936 Slog.i(LOG_TAG, "Quiet mode is already " + enableQuietMode);
937 return;
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000938 }
Tony Makb7e6fd42017-12-05 19:40:28 +0000939 profile.flags ^= UserInfo.FLAG_QUIET_MODE;
940 profileUserData = getUserDataLU(profile.id);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000941 }
Tony Makb7e6fd42017-12-05 19:40:28 +0000942 synchronized (mPackagesLock) {
943 writeUserLP(profileUserData);
944 }
945 try {
946 if (enableQuietMode) {
947 ActivityManager.getService().stopUser(userHandle, /* force */true, null);
948 LocalServices.getService(ActivityManagerInternal.class)
949 .killForegroundAppsForUser(userHandle);
950 } else {
951 IProgressListener callback = target != null
952 ? new DisableQuietModeUserUnlockedCallback(target)
953 : null;
954 ActivityManager.getService().startUserInBackgroundWithListener(
955 userHandle, callback);
Rubin Xuf13c9802016-01-21 18:06:00 +0000956 }
arangelov9b632d72018-12-07 23:21:22 +0000957 logQuietModeEnabled(userHandle, enableQuietMode, callingPackage);
Tony Makb7e6fd42017-12-05 19:40:28 +0000958 } catch (RemoteException e) {
959 // Should not happen, same process.
960 e.rethrowAsRuntimeException();
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000961 }
Tony Makb7e6fd42017-12-05 19:40:28 +0000962 broadcastProfileAvailabilityChanges(profile.getUserHandle(), parent.getUserHandle(),
963 enableQuietMode);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000964 }
965
arangelov9b632d72018-12-07 23:21:22 +0000966 private void logQuietModeEnabled(int userHandle, boolean enableQuietMode,
967 @Nullable String callingPackage) {
968 UserData userData;
969 synchronized (mUsersLock) {
970 userData = getUserDataLU(userHandle);
971 }
972 if (userData == null) {
973 return;
974 }
975 final long now = System.currentTimeMillis();
976 final long period = (userData.getLastRequestQuietModeEnabledMillis() != 0L
977 ? now - userData.getLastRequestQuietModeEnabledMillis()
978 : now - userData.info.creationTime);
979 DevicePolicyEventLogger
980 .createEvent(DevicePolicyEnums.REQUEST_QUIET_MODE_ENABLED)
981 .setStrings(callingPackage)
982 .setBoolean(enableQuietMode)
983 .setTimePeriod(period)
984 .write();
985 userData.setLastRequestQuietModeEnabledMillis(now);
986 }
987
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000988 @Override
989 public boolean isQuietModeEnabled(int userHandle) {
990 synchronized (mPackagesLock) {
991 UserInfo info;
992 synchronized (mUsersLock) {
993 info = getUserInfoLU(userHandle);
994 }
995 if (info == null || !info.isManagedProfile()) {
Rubin Xuf13c9802016-01-21 18:06:00 +0000996 return false;
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000997 }
998 return info.isQuietModeEnabled();
999 }
1000 }
1001
Tony Makb7e6fd42017-12-05 19:40:28 +00001002 /**
1003 * Show confirm credential screen to unlock user in order to turn off quiet mode.
1004 */
1005 private void showConfirmCredentialToDisableQuietMode(
Tony Mak64fd8c02017-12-01 19:11:59 +00001006 @UserIdInt int userHandle, @Nullable IntentSender target) {
Tony Makb7e6fd42017-12-05 19:40:28 +00001007 // otherwise, we show a profile challenge to trigger decryption of the user
1008 final KeyguardManager km = (KeyguardManager) mContext.getSystemService(
1009 Context.KEYGUARD_SERVICE);
1010 // We should use userHandle not credentialOwnerUserId here, as even if it is unified
1011 // lock, confirm screenlock page will know and show personal challenge, and unlock
1012 // work profile when personal challenge is correct
1013 final Intent unlockIntent = km.createConfirmDeviceCredentialIntent(null, null,
1014 userHandle);
1015 if (unlockIntent == null) {
1016 return;
Benjamin Franzf02420c2016-04-04 18:52:21 +01001017 }
Tony Makb7e6fd42017-12-05 19:40:28 +00001018 final Intent callBackIntent = new Intent(
1019 ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK);
1020 if (target != null) {
1021 callBackIntent.putExtra(Intent.EXTRA_INTENT, target);
Benjamin Franzf02420c2016-04-04 18:52:21 +01001022 }
Tony Makb7e6fd42017-12-05 19:40:28 +00001023 callBackIntent.putExtra(Intent.EXTRA_USER_ID, userHandle);
1024 callBackIntent.setPackage(mContext.getPackageName());
1025 callBackIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1026 final PendingIntent pendingIntent = PendingIntent.getBroadcast(
1027 mContext,
1028 0,
1029 callBackIntent,
1030 PendingIntent.FLAG_CANCEL_CURRENT |
1031 PendingIntent.FLAG_ONE_SHOT |
1032 PendingIntent.FLAG_IMMUTABLE);
1033 // After unlocking the challenge, it will disable quiet mode and run the original
1034 // intentSender
1035 unlockIntent.putExtra(Intent.EXTRA_INTENT, pendingIntent.getIntentSender());
1036 unlockIntent.setFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
1037 mContext.startActivity(unlockIntent);
Benjamin Franzf02420c2016-04-04 18:52:21 +01001038 }
1039
1040 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +01001041 public void setUserEnabled(int userId) {
1042 checkManageUsersPermission("enable user");
1043 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001044 UserInfo info;
1045 synchronized (mUsersLock) {
1046 info = getUserInfoLU(userId);
1047 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +01001048 if (info != null && !info.isEnabled()) {
1049 info.flags ^= UserInfo.FLAG_DISABLED;
Amith Yamasani12747872015-12-07 14:19:49 -08001050 writeUserLP(getUserDataLU(info.id));
Alexandra Gherghinadf35d572014-04-09 13:54:39 +01001051 }
1052 }
1053 }
1054
jovanakf24ad492018-05-18 12:15:59 -07001055 @Override
1056 public void setUserAdmin(int userId) {
1057 checkManageUserAndAcrossUsersFullPermission("set user admin");
1058
1059 synchronized (mPackagesLock) {
1060 UserInfo info;
1061 synchronized (mUsersLock) {
1062 info = getUserInfoLU(userId);
1063 }
1064 if (info == null || info.isAdmin()) {
1065 // Exit if no user found with that id, or the user is already an Admin.
1066 return;
1067 }
1068
1069 info.flags ^= UserInfo.FLAG_ADMIN;
1070 writeUserLP(getUserDataLU(info.id));
1071 }
1072
1073 // Remove non-admin restrictions.
1074 // Keep synchronized with createUserEvenWhenDisallowed.
1075 setUserRestriction(UserManager.DISALLOW_SMS, false, userId);
1076 setUserRestriction(UserManager.DISALLOW_OUTGOING_CALLS, false, userId);
1077 }
1078
Andrew Scull85a63bc2016-10-24 13:47:47 +01001079 /**
1080 * Evicts a user's CE key by stopping and restarting the user.
1081 *
1082 * The key is evicted automatically by the user controller when the user has stopped.
1083 */
1084 @Override
1085 public void evictCredentialEncryptionKey(@UserIdInt int userId) {
1086 checkManageUsersPermission("evict CE key");
1087 final IActivityManager am = ActivityManagerNative.getDefault();
1088 final long identity = Binder.clearCallingIdentity();
1089 try {
1090 am.restartUserInBackground(userId);
1091 } catch (RemoteException re) {
1092 throw re.rethrowAsRuntimeException();
1093 } finally {
1094 Binder.restoreCallingIdentity(identity);
1095 }
1096 }
1097
Alexandra Gherghinadf35d572014-04-09 13:54:39 +01001098 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -07001099 public UserInfo getUserInfo(int userId) {
Sudheer Shankaaccaa082016-06-14 16:22:57 -07001100 checkManageOrCreateUsersPermission("query user");
Tony Mak8673b282016-03-21 21:10:59 +00001101 synchronized (mUsersLock) {
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001102 return userWithName(getUserInfoLU(userId));
1103 }
1104 }
1105
1106 /**
1107 * Returns a UserInfo object with the name filled in, for Owner, or the original
1108 * if the name is already set.
1109 */
1110 private UserInfo userWithName(UserInfo orig) {
1111 if (orig != null && orig.name == null && orig.id == UserHandle.USER_SYSTEM) {
1112 UserInfo withName = new UserInfo(orig);
1113 withName.name = getOwnerName();
1114 return withName;
1115 } else {
1116 return orig;
Tony Mak8673b282016-03-21 21:10:59 +00001117 }
1118 }
1119
1120 @Override
Kenny Guy02c89902016-11-15 19:36:38 +00001121 public int getManagedProfileBadge(@UserIdInt int userId) {
Jon Miranda2b340a22019-01-25 14:03:49 -08001122 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "getManagedProfileBadge");
Kenny Guy02c89902016-11-15 19:36:38 +00001123 synchronized (mUsersLock) {
1124 UserInfo userInfo = getUserInfoLU(userId);
1125 return userInfo != null ? userInfo.profileBadge : 0;
1126 }
1127 }
1128
1129 @Override
Tony Mak8673b282016-03-21 21:10:59 +00001130 public boolean isManagedProfile(int userId) {
Jon Miranda2b340a22019-01-25 14:03:49 -08001131 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isManagedProfile");
Fyodor Kupolov82402752015-10-28 14:54:51 -07001132 synchronized (mUsersLock) {
Amith Yamasani1c41dc82016-06-28 16:13:15 -07001133 UserInfo userInfo = getUserInfoLU(userId);
Tony Mak8673b282016-03-21 21:10:59 +00001134 return userInfo != null && userInfo.isManagedProfile();
Amith Yamasani13593602012-03-22 16:16:17 -07001135 }
1136 }
1137
Amith Yamasani71e6c692013-03-24 17:39:28 -07001138 @Override
Fyodor Kupolovc413f702016-10-06 17:11:14 -07001139 public boolean isUserUnlockingOrUnlocked(int userId) {
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08001140 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isUserUnlockingOrUnlocked");
Fyodor Kupolovc413f702016-10-06 17:11:14 -07001141 return mLocalService.isUserUnlockingOrUnlocked(userId);
1142 }
1143
1144 @Override
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08001145 public boolean isUserUnlocked(int userId) {
1146 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isUserUnlocked");
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07001147 return mLocalService.isUserUnlocked(userId);
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08001148 }
1149
1150 @Override
1151 public boolean isUserRunning(int userId) {
1152 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isUserRunning");
1153 return mLocalService.isUserRunning(userId);
1154 }
1155
Makoto Onuki73dded22017-12-20 13:14:48 +09001156 @Override
Bookatzcde3d922019-03-08 14:30:00 -08001157 public String getUserName() {
1158 if (!hasManageUsersOrPermission(android.Manifest.permission.GET_ACCOUNTS_PRIVILEGED)) {
1159 throw new SecurityException("You need MANAGE_USERS or GET_ACCOUNTS_PRIVILEGED "
1160 + "permissions to: get user name");
1161 }
1162 final int userId = UserHandle.getUserId(Binder.getCallingUid());
1163 synchronized (mUsersLock) {
1164 UserInfo userInfo = userWithName(getUserInfoLU(userId));
1165 return userInfo == null ? "" : userInfo.name;
1166 }
1167 }
1168
1169 @Override
Makoto Onuki73dded22017-12-20 13:14:48 +09001170 public long getUserStartRealtime() {
1171 final int userId = UserHandle.getUserId(Binder.getCallingUid());
1172 synchronized (mUsersLock) {
1173 final UserData user = getUserDataLU(userId);
1174 if (user != null) {
1175 return user.startRealtime;
1176 }
1177 return 0;
1178 }
1179 }
1180
1181 @Override
1182 public long getUserUnlockRealtime() {
1183 synchronized (mUsersLock) {
1184 final UserData user = getUserDataLU(UserHandle.getUserId(Binder.getCallingUid()));
1185 if (user != null) {
1186 return user.unlockRealtime;
1187 }
1188 return 0;
1189 }
1190 }
1191
Felipe Leme7ad2f6b2019-09-11 09:23:26 -07001192 private void checkManageOrInteractPermIfCallerInOtherProfileGroup(@UserIdInt int userId,
1193 String name) {
1194 final int callingUserId = UserHandle.getCallingUserId();
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08001195 if (callingUserId == userId || isSameProfileGroupNoChecks(callingUserId, userId) ||
1196 hasManageUsersPermission()) {
1197 return;
1198 }
jovanakf24ad492018-05-18 12:15:59 -07001199 if (!hasPermissionGranted(Manifest.permission.INTERACT_ACROSS_USERS,
1200 Binder.getCallingUid())) {
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08001201 throw new SecurityException("You need INTERACT_ACROSS_USERS or MANAGE_USERS permission "
1202 + "to: check " + name);
1203 }
1204 }
1205
1206 @Override
Felipe Leme7ad2f6b2019-09-11 09:23:26 -07001207 public boolean isDemoUser(@UserIdInt int userId) {
1208 final int callingUserId = UserHandle.getCallingUserId();
Amith Yamasani1c41dc82016-06-28 16:13:15 -07001209 if (callingUserId != userId && !hasManageUsersPermission()) {
1210 throw new SecurityException("You need MANAGE_USERS permission to query if u=" + userId
1211 + " is a demo user");
1212 }
1213 synchronized (mUsersLock) {
1214 UserInfo userInfo = getUserInfoLU(userId);
1215 return userInfo != null && userInfo.isDemo();
1216 }
1217 }
1218
1219 @Override
Felipe Leme7ad2f6b2019-09-11 09:23:26 -07001220 public boolean isPreCreated(@UserIdInt int userId) {
1221 final int callingUserId = UserHandle.getCallingUserId();
1222 if (callingUserId != userId && !hasManageUsersPermission()) {
1223 throw new SecurityException("You need MANAGE_USERS permission to query if u=" + userId
1224 + " is pre-created");
1225 }
1226 synchronized (mUsersLock) {
1227 UserInfo userInfo = getUserInfoLU(userId);
1228 return userInfo != null && userInfo.preCreated;
1229 }
1230 }
1231
1232 @Override
Amith Yamasani71e6c692013-03-24 17:39:28 -07001233 public boolean isRestricted() {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001234 synchronized (mUsersLock) {
1235 return getUserInfoLU(UserHandle.getCallingUserId()).isRestricted();
Amith Yamasani71e6c692013-03-24 17:39:28 -07001236 }
1237 }
1238
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001239 @Override
1240 public boolean canHaveRestrictedProfile(int userId) {
1241 checkManageUsersPermission("canHaveRestrictedProfile");
Fyodor Kupolov82402752015-10-28 14:54:51 -07001242 synchronized (mUsersLock) {
1243 final UserInfo userInfo = getUserInfoLU(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001244 if (userInfo == null || !userInfo.canHaveProfile()) {
1245 return false;
1246 }
1247 if (!userInfo.isAdmin()) {
1248 return false;
1249 }
Makoto Onukie7927da2015-11-25 10:05:17 -08001250 // restricted profile can be created if there is no DO set and the admin user has no PO;
1251 return !mIsDeviceManaged && !mIsUserManaged.get(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001252 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001253 }
1254
Fyodor Kupolovca177562017-11-09 17:43:01 -08001255 @Override
1256 public boolean hasRestrictedProfiles() {
1257 checkManageUsersPermission("hasRestrictedProfiles");
1258 final int callingUserId = UserHandle.getCallingUserId();
1259 synchronized (mUsersLock) {
1260 final int userSize = mUsers.size();
1261 for (int i = 0; i < userSize; i++) {
1262 UserInfo profile = mUsers.valueAt(i).info;
1263 if (callingUserId != profile.id
1264 && profile.restrictedProfileParentId == callingUserId) {
1265 return true;
1266 }
1267 }
1268 return false;
1269 }
1270 }
1271
Amith Yamasani195263742012-08-21 15:40:12 -07001272 /*
1273 * Should be locked on mUsers before calling this.
1274 */
Andreas Gampe2e8c7672018-07-20 13:01:08 -07001275 @GuardedBy("mUsersLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001276 private UserInfo getUserInfoLU(int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -08001277 final UserData userData = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -07001278 // If it is partial and not in the process of being removed, return as unknown user.
Amith Yamasani12747872015-12-07 14:19:49 -08001279 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001280 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
1281 return null;
1282 }
Amith Yamasani12747872015-12-07 14:19:49 -08001283 return userData != null ? userData.info : null;
1284 }
1285
Andreas Gampe2e8c7672018-07-20 13:01:08 -07001286 @GuardedBy("mUsersLock")
Amith Yamasani12747872015-12-07 14:19:49 -08001287 private UserData getUserDataLU(int userId) {
1288 final UserData userData = mUsers.get(userId);
1289 // If it is partial and not in the process of being removed, return as unknown user.
1290 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
1291 return null;
1292 }
1293 return userData;
Amith Yamasani195263742012-08-21 15:40:12 -07001294 }
1295
Fyodor Kupolov82402752015-10-28 14:54:51 -07001296 /**
1297 * Obtains {@link #mUsersLock} and return UserInfo from mUsers.
1298 * <p>No permissions checking or any addition checks are made</p>
1299 */
1300 private UserInfo getUserInfoNoChecks(int userId) {
1301 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001302 final UserData userData = mUsers.get(userId);
1303 return userData != null ? userData.info : null;
1304 }
1305 }
1306
1307 /**
1308 * Obtains {@link #mUsersLock} and return UserData from mUsers.
1309 * <p>No permissions checking or any addition checks are made</p>
1310 */
1311 private UserData getUserDataNoChecks(int userId) {
1312 synchronized (mUsersLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001313 return mUsers.get(userId);
1314 }
1315 }
1316
Amith Yamasani236b2b52015-08-18 14:32:14 -07001317 /** Called by PackageManagerService */
Amith Yamasani13593602012-03-22 16:16:17 -07001318 public boolean exists(int userId) {
Todd Kennedy0eb97382017-10-03 16:57:22 -07001319 return mLocalService.exists(userId);
Amith Yamasani13593602012-03-22 16:16:17 -07001320 }
1321
Amith Yamasani258848d2012-08-10 17:06:33 -07001322 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001323 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001324 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001325 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -07001326 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001327 UserData userData = getUserDataNoChecks(userId);
1328 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001329 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
1330 return;
1331 }
Amith Yamasani12747872015-12-07 14:19:49 -08001332 if (name != null && !name.equals(userData.info.name)) {
1333 userData.info.name = name;
1334 writeUserLP(userData);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001335 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -07001336 }
1337 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001338 if (changed) {
Bookatzf9368552019-03-14 11:57:09 -07001339 long ident = Binder.clearCallingIdentity();
1340 try {
1341 sendUserInfoChangedBroadcast(userId);
1342 } finally {
1343 Binder.restoreCallingIdentity(ident);
1344 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001345 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001346 }
1347
Amith Yamasani258848d2012-08-10 17:06:33 -07001348 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001349 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001350 checkManageUsersPermission("update users");
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01001351 if (hasUserRestriction(UserManager.DISALLOW_SET_USER_ICON, userId)) {
1352 Log.w(LOG_TAG, "Cannot set user icon. DISALLOW_SET_USER_ICON is enabled.");
1353 return;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001354 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01001355 mLocalService.setUserIcon(userId, bitmap);
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001356 }
1357
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01001358
1359
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001360 private void sendUserInfoChangedBroadcast(int userId) {
1361 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
1362 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
1363 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -07001364 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001365 }
1366
Amith Yamasani258848d2012-08-10 17:06:33 -07001367 @Override
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001368 public ParcelFileDescriptor getUserIcon(int targetUserId) {
Bookatzcde3d922019-03-08 14:30:00 -08001369 if (!hasManageUsersOrPermission(android.Manifest.permission.GET_ACCOUNTS_PRIVILEGED)) {
1370 throw new SecurityException("You need MANAGE_USERS or GET_ACCOUNTS_PRIVILEGED "
1371 + "permissions to: get user icon");
1372 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001373 String iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001374 synchronized (mPackagesLock) {
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001375 UserInfo targetUserInfo = getUserInfoNoChecks(targetUserId);
1376 if (targetUserInfo == null || targetUserInfo.partial) {
1377 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + targetUserId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001378 return null;
1379 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001380
1381 final int callingUserId = UserHandle.getCallingUserId();
1382 final int callingGroupId = getUserInfoNoChecks(callingUserId).profileGroupId;
1383 final int targetGroupId = targetUserInfo.profileGroupId;
1384 final boolean sameGroup = (callingGroupId != UserInfo.NO_PROFILE_GROUP_ID
1385 && callingGroupId == targetGroupId);
1386 if ((callingUserId != targetUserId) && !sameGroup) {
Nicolas Prevot88cc3462014-05-14 14:51:48 +01001387 checkManageUsersPermission("get the icon of a user who is not related");
1388 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001389
1390 if (targetUserInfo.iconPath == null) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001391 return null;
1392 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001393 iconPath = targetUserInfo.iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001394 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001395
1396 try {
1397 return ParcelFileDescriptor.open(
1398 new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
1399 } catch (FileNotFoundException e) {
1400 Log.e(LOG_TAG, "Couldn't find icon file", e);
1401 }
1402 return null;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001403 }
1404
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001405 public void makeInitialized(int userId) {
1406 checkManageUsersPermission("makeInitialized");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001407 boolean scheduleWriteUser = false;
Amith Yamasani12747872015-12-07 14:19:49 -08001408 UserData userData;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001409 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001410 userData = mUsers.get(userId);
1411 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001412 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001413 return;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001414 }
Amith Yamasani12747872015-12-07 14:19:49 -08001415 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1416 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001417 scheduleWriteUser = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001418 }
1419 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001420 if (scheduleWriteUser) {
Amith Yamasani12747872015-12-07 14:19:49 -08001421 scheduleWriteUser(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001422 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001423 }
1424
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001425 /**
1426 * If default guest restrictions haven't been initialized yet, add the basic
1427 * restrictions.
1428 */
1429 private void initDefaultGuestRestrictions() {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001430 synchronized (mGuestRestrictions) {
1431 if (mGuestRestrictions.isEmpty()) {
Samuel Tand9453b82016-03-14 15:57:02 -07001432 mGuestRestrictions.putBoolean(UserManager.DISALLOW_CONFIG_WIFI, true);
Fyodor Kupolove04462c2015-11-30 15:02:53 -08001433 mGuestRestrictions.putBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, true);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001434 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
1435 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
1436 }
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001437 }
1438 }
1439
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001440 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301441 public Bundle getDefaultGuestRestrictions() {
1442 checkManageUsersPermission("getDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001443 synchronized (mGuestRestrictions) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301444 return new Bundle(mGuestRestrictions);
1445 }
1446 }
1447
1448 @Override
1449 public void setDefaultGuestRestrictions(Bundle restrictions) {
1450 checkManageUsersPermission("setDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001451 synchronized (mGuestRestrictions) {
1452 mGuestRestrictions.clear();
1453 mGuestRestrictions.putAll(restrictions);
1454 }
1455 synchronized (mPackagesLock) {
1456 writeUserListLP();
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301457 }
1458 }
1459
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001460 /**
Pavel Grafov6a40f092016-10-25 15:46:51 +01001461 * See {@link UserManagerInternal#setDevicePolicyUserRestrictions}
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001462 */
Pavel Grafov6a40f092016-10-25 15:46:51 +01001463 private void setDevicePolicyUserRestrictionsInner(int userId, @Nullable Bundle restrictions,
1464 boolean isDeviceOwner, int cameraRestrictionScope) {
1465 final Bundle global = new Bundle();
1466 final Bundle local = new Bundle();
1467
1468 // Sort restrictions into local and global ensuring they don't overlap.
1469 UserRestrictionsUtils.sortToGlobalAndLocal(restrictions, isDeviceOwner,
1470 cameraRestrictionScope, global, local);
1471
1472 boolean globalChanged, localChanged;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001473 synchronized (mRestrictionsLock) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001474 // Update global and local restrictions if they were changed.
1475 globalChanged = updateRestrictionsIfNeededLR(
1476 userId, global, mDevicePolicyGlobalUserRestrictions);
1477 localChanged = updateRestrictionsIfNeededLR(
1478 userId, local, mDevicePolicyLocalUserRestrictions);
1479
1480 if (isDeviceOwner) {
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001481 // Remember the global restriction owner userId to be able to make a distinction
1482 // in getUserRestrictionSource on who set local policies.
Pavel Grafov6a40f092016-10-25 15:46:51 +01001483 mDeviceOwnerUserId = userId;
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001484 } else {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001485 if (mDeviceOwnerUserId == userId) {
Zoltan Szatmary-Ban8a5536d2016-05-27 17:56:44 +01001486 // When profile owner sets restrictions it passes null global bundle and we
1487 // reset global restriction owner userId.
1488 // This means this user used to have DO, but now the DO is gone and the user
1489 // instead has PO.
Pavel Grafov6a40f092016-10-25 15:46:51 +01001490 mDeviceOwnerUserId = UserHandle.USER_NULL;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001491 }
1492 }
1493 }
1494 if (DBG) {
1495 Log.d(LOG_TAG, "setDevicePolicyUserRestrictions: userId=" + userId
1496 + " global=" + global + (globalChanged ? " (changed)" : "")
1497 + " local=" + local + (localChanged ? " (changed)" : "")
1498 );
1499 }
1500 // Don't call them within the mRestrictionsLock.
1501 synchronized (mPackagesLock) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001502 if (localChanged || globalChanged) {
Amith Yamasani12747872015-12-07 14:19:49 -08001503 writeUserLP(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001504 }
1505 }
1506
1507 synchronized (mRestrictionsLock) {
1508 if (globalChanged) {
1509 applyUserRestrictionsForAllUsersLR();
1510 } else if (localChanged) {
1511 applyUserRestrictionsLR(userId);
1512 }
1513 }
1514 }
1515
Pavel Grafov6a40f092016-10-25 15:46:51 +01001516 /**
1517 * Updates restriction bundle for a given user in a given restriction array. If new bundle is
1518 * empty, record is removed from the array.
1519 * @return whether restrictions bundle is different from the old one.
1520 */
1521 private boolean updateRestrictionsIfNeededLR(int userId, @Nullable Bundle restrictions,
1522 SparseArray<Bundle> restrictionsArray) {
1523 final boolean changed =
1524 !UserRestrictionsUtils.areEqual(restrictionsArray.get(userId), restrictions);
1525 if (changed) {
1526 if (!UserRestrictionsUtils.isEmpty(restrictions)) {
1527 restrictionsArray.put(userId, restrictions);
1528 } else {
1529 restrictionsArray.delete(userId);
1530 }
1531 }
1532 return changed;
1533 }
1534
Makoto Onuki068c54a2015-10-13 14:34:03 -07001535 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001536 private Bundle computeEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001537 final Bundle baseRestrictions =
1538 UserRestrictionsUtils.nonNull(mBaseUserRestrictions.get(userId));
Pavel Grafov6a40f092016-10-25 15:46:51 +01001539 final Bundle global = UserRestrictionsUtils.mergeAll(mDevicePolicyGlobalUserRestrictions);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001540 final Bundle local = mDevicePolicyLocalUserRestrictions.get(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001541
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001542 if (UserRestrictionsUtils.isEmpty(global) && UserRestrictionsUtils.isEmpty(local)) {
1543 // Common case first.
1544 return baseRestrictions;
Makoto Onuki068c54a2015-10-13 14:34:03 -07001545 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001546 final Bundle effective = UserRestrictionsUtils.clone(baseRestrictions);
1547 UserRestrictionsUtils.merge(effective, global);
1548 UserRestrictionsUtils.merge(effective, local);
1549
Makoto Onuki068c54a2015-10-13 14:34:03 -07001550 return effective;
1551 }
1552
1553 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001554 private void invalidateEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki068c54a2015-10-13 14:34:03 -07001555 if (DBG) {
1556 Log.d(LOG_TAG, "invalidateEffectiveUserRestrictions userId=" + userId);
1557 }
1558 mCachedEffectiveUserRestrictions.remove(userId);
1559 }
1560
1561 private Bundle getEffectiveUserRestrictions(int userId) {
1562 synchronized (mRestrictionsLock) {
1563 Bundle restrictions = mCachedEffectiveUserRestrictions.get(userId);
1564 if (restrictions == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001565 restrictions = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001566 mCachedEffectiveUserRestrictions.put(userId, restrictions);
1567 }
1568 return restrictions;
Amith Yamasani8cd28b52014-06-08 17:54:27 -07001569 }
1570 }
1571
Makoto Onuki068c54a2015-10-13 14:34:03 -07001572 /** @return a specific user restriction that's in effect currently. */
1573 @Override
1574 public boolean hasUserRestriction(String restrictionKey, int userId) {
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001575 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1576 return false;
1577 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001578 Bundle restrictions = getEffectiveUserRestrictions(userId);
1579 return restrictions != null && restrictions.getBoolean(restrictionKey);
1580 }
1581
Makoto Onukiacc50462018-02-14 14:13:49 -08001582 /** @return if any user has the given restriction. */
1583 @Override
1584 public boolean hasUserRestrictionOnAnyUser(String restrictionKey) {
1585 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1586 return false;
1587 }
1588 final List<UserInfo> users = getUsers(/* excludeDying= */ true);
1589 for (int i = 0; i < users.size(); i++) {
1590 final int userId = users.get(i).id;
1591 Bundle restrictions = getEffectiveUserRestrictions(userId);
1592 if (restrictions != null && restrictions.getBoolean(restrictionKey)) {
1593 return true;
1594 }
1595 }
1596 return false;
1597 }
1598
Makoto Onuki068c54a2015-10-13 14:34:03 -07001599 /**
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001600 * @hide
1601 *
1602 * Returns who set a user restriction on a user.
1603 * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
1604 * @param restrictionKey the string key representing the restriction
1605 * @param userId the id of the user for whom to retrieve the restrictions.
1606 * @return The source of user restriction. Any combination of
1607 * {@link UserManager#RESTRICTION_NOT_SET},
1608 * {@link UserManager#RESTRICTION_SOURCE_SYSTEM},
1609 * {@link UserManager#RESTRICTION_SOURCE_DEVICE_OWNER}
1610 * and {@link UserManager#RESTRICTION_SOURCE_PROFILE_OWNER}
1611 */
1612 @Override
1613 public int getUserRestrictionSource(String restrictionKey, int userId) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001614 List<EnforcingUser> enforcingUsers = getUserRestrictionSources(restrictionKey, userId);
1615 // Get "bitwise or" of restriction sources for all enforcing users.
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001616 int result = UserManager.RESTRICTION_NOT_SET;
Pavel Grafov6a40f092016-10-25 15:46:51 +01001617 for (int i = enforcingUsers.size() - 1; i >= 0; i--) {
1618 result |= enforcingUsers.get(i).getUserRestrictionSource();
1619 }
1620 return result;
1621 }
1622
1623 @Override
1624 public List<EnforcingUser> getUserRestrictionSources(
1625 String restrictionKey, @UserIdInt int userId) {
1626 checkManageUsersPermission("getUserRestrictionSource");
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001627
1628 // Shortcut for the most common case
1629 if (!hasUserRestriction(restrictionKey, userId)) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001630 return Collections.emptyList();
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001631 }
1632
Pavel Grafov6a40f092016-10-25 15:46:51 +01001633 final List<EnforcingUser> result = new ArrayList<>();
1634
1635 // Check if it is base restriction.
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001636 if (hasBaseUserRestriction(restrictionKey, userId)) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001637 result.add(new EnforcingUser(
1638 UserHandle.USER_NULL, UserManager.RESTRICTION_SOURCE_SYSTEM));
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001639 }
1640
Pavel Grafov6a40f092016-10-25 15:46:51 +01001641 synchronized (mRestrictionsLock) {
1642 // Check if it is set by profile owner.
1643 Bundle profileOwnerRestrictions = mDevicePolicyLocalUserRestrictions.get(userId);
1644 if (UserRestrictionsUtils.contains(profileOwnerRestrictions, restrictionKey)) {
1645 result.add(getEnforcingUserLocked(userId));
1646 }
1647
1648 // Iterate over all users who enforce global restrictions.
1649 for (int i = mDevicePolicyGlobalUserRestrictions.size() - 1; i >= 0; i--) {
1650 Bundle globalRestrictions = mDevicePolicyGlobalUserRestrictions.valueAt(i);
1651 int profileUserId = mDevicePolicyGlobalUserRestrictions.keyAt(i);
1652 if (UserRestrictionsUtils.contains(globalRestrictions, restrictionKey)) {
1653 result.add(getEnforcingUserLocked(profileUserId));
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001654 }
1655 }
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001656 }
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001657 return result;
1658 }
1659
Andreas Gampea36dc622018-02-05 17:19:22 -08001660 @GuardedBy("mRestrictionsLock")
Pavel Grafov6a40f092016-10-25 15:46:51 +01001661 private EnforcingUser getEnforcingUserLocked(@UserIdInt int userId) {
1662 int source = mDeviceOwnerUserId == userId ? UserManager.RESTRICTION_SOURCE_DEVICE_OWNER
1663 : UserManager.RESTRICTION_SOURCE_PROFILE_OWNER;
1664 return new EnforcingUser(userId, source);
1665 }
1666
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001667 /**
Makoto Onuki068c54a2015-10-13 14:34:03 -07001668 * @return UserRestrictions that are in effect currently. This always returns a new
1669 * {@link Bundle}.
1670 */
Amith Yamasani8cd28b52014-06-08 17:54:27 -07001671 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001672 public Bundle getUserRestrictions(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001673 return UserRestrictionsUtils.clone(getEffectiveUserRestrictions(userId));
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001674 }
1675
1676 @Override
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +00001677 public boolean hasBaseUserRestriction(String restrictionKey, int userId) {
1678 checkManageUsersPermission("hasBaseUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001679 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1680 return false;
1681 }
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +00001682 synchronized (mRestrictionsLock) {
1683 Bundle bundle = mBaseUserRestrictions.get(userId);
1684 return (bundle != null && bundle.getBoolean(restrictionKey, false));
1685 }
1686 }
1687
1688 @Override
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001689 public void setUserRestriction(String key, boolean value, int userId) {
Fyodor Kupolovd4b26042015-07-27 14:30:59 -07001690 checkManageUsersPermission("setUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001691 if (!UserRestrictionsUtils.isValidRestriction(key)) {
1692 return;
1693 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001694 synchronized (mRestrictionsLock) {
1695 // Note we can't modify Bundles stored in mBaseUserRestrictions directly, so create
1696 // a copy.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001697 final Bundle newRestrictions = UserRestrictionsUtils.clone(
1698 mBaseUserRestrictions.get(userId));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001699 newRestrictions.putBoolean(key, value);
1700
Fyodor Kupolov82402752015-10-28 14:54:51 -07001701 updateUserRestrictionsInternalLR(newRestrictions, userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001702 }
1703 }
1704
Makoto Onuki068c54a2015-10-13 14:34:03 -07001705 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001706 * Optionally updating user restrictions, calculate the effective user restrictions and also
1707 * propagate to other services and system settings.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001708 *
Pavel Grafov6a40f092016-10-25 15:46:51 +01001709 * @param newBaseRestrictions User restrictions to set.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001710 * If null, will not update user restrictions and only does the propagation.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001711 * @param userId target user ID.
1712 */
1713 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001714 private void updateUserRestrictionsInternalLR(
Pavel Grafov6a40f092016-10-25 15:46:51 +01001715 @Nullable Bundle newBaseRestrictions, int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001716 final Bundle prevAppliedRestrictions = UserRestrictionsUtils.nonNull(
1717 mAppliedUserRestrictions.get(userId));
1718
1719 // Update base restrictions.
Pavel Grafov6a40f092016-10-25 15:46:51 +01001720 if (newBaseRestrictions != null) {
1721 // If newBaseRestrictions == the current one, it's probably a bug.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001722 final Bundle prevBaseRestrictions = mBaseUserRestrictions.get(userId);
1723
Pavel Grafov6a40f092016-10-25 15:46:51 +01001724 Preconditions.checkState(prevBaseRestrictions != newBaseRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001725 Preconditions.checkState(mCachedEffectiveUserRestrictions.get(userId)
Pavel Grafov6a40f092016-10-25 15:46:51 +01001726 != newBaseRestrictions);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001727
Pavel Grafov6a40f092016-10-25 15:46:51 +01001728 if (updateRestrictionsIfNeededLR(userId, newBaseRestrictions, mBaseUserRestrictions)) {
Amith Yamasani12747872015-12-07 14:19:49 -08001729 scheduleWriteUser(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001730 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001731 }
1732
Fyodor Kupolov82402752015-10-28 14:54:51 -07001733 final Bundle effective = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001734
Makoto Onuki759a7632015-10-28 16:43:10 -07001735 mCachedEffectiveUserRestrictions.put(userId, effective);
1736
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001737 // Apply the new restrictions.
Makoto Onuki4f160732015-10-27 17:15:38 -07001738 if (DBG) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001739 debug("Applying user restrictions: userId=" + userId
1740 + " new=" + effective + " prev=" + prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001741 }
1742
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001743 if (mAppOpsService != null) { // We skip it until system-ready.
Fyodor Kupolovec30ca32016-06-16 15:09:29 -07001744 mHandler.post(new Runnable() {
1745 @Override
1746 public void run() {
1747 try {
1748 mAppOpsService.setUserRestrictions(effective, mUserRestriconToken, userId);
1749 } catch (RemoteException e) {
1750 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
1751 }
1752 }
1753 });
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001754 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001755
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001756 propagateUserRestrictionsLR(userId, effective, prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001757
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001758 mAppliedUserRestrictions.put(userId, new Bundle(effective));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001759 }
1760
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001761 private void propagateUserRestrictionsLR(final int userId,
Makoto Onukid45a4a22015-11-02 17:17:38 -08001762 Bundle newRestrictions, Bundle prevRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001763 // Note this method doesn't touch any state, meaning it doesn't require mRestrictionsLock
1764 // actually, but we still need some kind of synchronization otherwise we might end up
1765 // calling listeners out-of-order, thus "LR".
1766
1767 if (UserRestrictionsUtils.areEqual(newRestrictions, prevRestrictions)) {
1768 return;
1769 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08001770
1771 final Bundle newRestrictionsFinal = new Bundle(newRestrictions);
1772 final Bundle prevRestrictionsFinal = new Bundle(prevRestrictions);
1773
1774 mHandler.post(new Runnable() {
1775 @Override
1776 public void run() {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07001777 UserRestrictionsUtils.applyUserRestrictions(
1778 mContext, userId, newRestrictionsFinal, prevRestrictionsFinal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001779
Makoto Onukid45a4a22015-11-02 17:17:38 -08001780 final UserRestrictionsListener[] listeners;
1781 synchronized (mUserRestrictionsListeners) {
1782 listeners = new UserRestrictionsListener[mUserRestrictionsListeners.size()];
1783 mUserRestrictionsListeners.toArray(listeners);
1784 }
1785 for (int i = 0; i < listeners.length; i++) {
1786 listeners[i].onUserRestrictionsChanged(userId,
1787 newRestrictionsFinal, prevRestrictionsFinal);
1788 }
Makoto Onukie72f81b2017-03-16 14:08:19 -07001789
1790 final Intent broadcast = new Intent(UserManager.ACTION_USER_RESTRICTIONS_CHANGED)
1791 .setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
1792 mContext.sendBroadcastAsUser(broadcast, UserHandle.of(userId));
Makoto Onukid45a4a22015-11-02 17:17:38 -08001793 }
1794 });
1795 }
1796
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001797 // Package private for the inner class.
Andreas Gampe2e8c7672018-07-20 13:01:08 -07001798 @GuardedBy("mRestrictionsLock")
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001799 void applyUserRestrictionsLR(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001800 updateUserRestrictionsInternalLR(null, userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001801 }
1802
1803 @GuardedBy("mRestrictionsLock")
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001804 // Package private for the inner class.
1805 void applyUserRestrictionsForAllUsersLR() {
1806 if (DBG) {
1807 debug("applyUserRestrictionsForAllUsersLR");
1808 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001809 // First, invalidate all cached values.
Makoto Onuki4f160732015-10-27 17:15:38 -07001810 mCachedEffectiveUserRestrictions.clear();
1811
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001812 // We don't want to call into ActivityManagerService while taking a lock, so we'll call
Makoto Onuki068c54a2015-10-13 14:34:03 -07001813 // it on a handler.
1814 final Runnable r = new Runnable() {
1815 @Override
1816 public void run() {
1817 // Then get the list of running users.
1818 final int[] runningUsers;
1819 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001820 runningUsers = ActivityManager.getService().getRunningUserIds();
Makoto Onuki068c54a2015-10-13 14:34:03 -07001821 } catch (RemoteException e) {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001822 Log.w(LOG_TAG, "Unable to access ActivityManagerService");
Makoto Onuki068c54a2015-10-13 14:34:03 -07001823 return;
1824 }
1825 // Then re-calculate the effective restrictions and apply, only for running users.
1826 // It's okay if a new user has started after the getRunningUserIds() call,
1827 // because we'll do the same thing (re-calculate the restrictions and apply)
1828 // when we start a user.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001829 synchronized (mRestrictionsLock) {
1830 for (int i = 0; i < runningUsers.length; i++) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001831 applyUserRestrictionsLR(runningUsers[i]);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001832 }
1833 }
1834 }
1835 };
1836 mHandler.post(r);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001837 }
1838
Amith Yamasani258848d2012-08-10 17:06:33 -07001839 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001840 * Check if we've hit the limit of how many users can be created.
1841 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001842 private boolean isUserLimitReached() {
1843 int count;
1844 synchronized (mUsersLock) {
1845 count = getAliveUsersExcludingGuestsCountLU();
1846 }
1847 return count >= UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001848 }
1849
1850 @Override
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001851 public boolean canAddMoreManagedProfiles(int userId, boolean allowedToRemoveOne) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001852 checkManageUsersPermission("check if more managed profiles can be added.");
1853 if (ActivityManager.isLowRamDeviceStatic()) {
1854 return false;
1855 }
Fyodor Kupolovb6157992015-06-05 15:32:28 -07001856 if (!mContext.getPackageManager().hasSystemFeature(
1857 PackageManager.FEATURE_MANAGED_USERS)) {
1858 return false;
1859 }
Nicolas Prevotb8186812015-08-06 15:00:03 +01001860 // Limit number of managed profiles that can be created
Benjamin Franzc8776152017-01-06 14:16:41 +00001861 final int managedProfilesCount = getProfiles(userId, false).size() - 1;
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001862 final int profilesRemovedCount = managedProfilesCount > 0 && allowedToRemoveOne ? 1 : 0;
Kenny Guy02c89902016-11-15 19:36:38 +00001863 if (managedProfilesCount - profilesRemovedCount >= getMaxManagedProfiles()) {
Nicolas Prevotb8186812015-08-06 15:00:03 +01001864 return false;
1865 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001866 synchronized(mUsersLock) {
1867 UserInfo userInfo = getUserInfoLU(userId);
yuanhao47f9f7c2017-01-18 09:54:45 +08001868 if (userInfo == null || !userInfo.canHaveProfile()) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001869 return false;
1870 }
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001871 int usersCountAfterRemoving = getAliveUsersExcludingGuestsCountLU()
1872 - profilesRemovedCount;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001873 // We allow creating a managed profile in the special case where there is only one user.
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001874 return usersCountAfterRemoving == 1
1875 || usersCountAfterRemoving < UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001876 }
1877 }
1878
Andreas Gampe2e8c7672018-07-20 13:01:08 -07001879 @GuardedBy("mUsersLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001880 private int getAliveUsersExcludingGuestsCountLU() {
Amith Yamasanif584f012014-05-19 17:57:25 -07001881 int aliveUserCount = 0;
1882 final int totalUserCount = mUsers.size();
1883 // Skip over users being removed
1884 for (int i = 0; i < totalUserCount; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001885 UserInfo user = mUsers.valueAt(i).info;
Felipe Leme7ad2f6b2019-09-11 09:23:26 -07001886 if (!mRemovingUserIds.get(user.id) && !user.isGuest() && !user.preCreated) {
Amith Yamasanif584f012014-05-19 17:57:25 -07001887 aliveUserCount++;
1888 }
1889 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001890 return aliveUserCount;
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001891 }
1892
1893 /**
Amith Yamasani195263742012-08-21 15:40:12 -07001894 * Enforces that only the system UID or root's UID or apps that have the
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001895 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} and
1896 * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL INTERACT_ACROSS_USERS_FULL}
1897 * permissions can make certain calls to the UserManager.
1898 *
1899 * @param message used as message if SecurityException is thrown
1900 * @throws SecurityException if the caller does not have enough privilege.
1901 */
1902 private static final void checkManageUserAndAcrossUsersFullPermission(String message) {
1903 final int uid = Binder.getCallingUid();
jovanakf24ad492018-05-18 12:15:59 -07001904
1905 if (uid == Process.SYSTEM_UID || uid == 0) {
1906 // System UID or root's UID are granted privilege.
1907 return;
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001908 }
jovanakf24ad492018-05-18 12:15:59 -07001909
1910 if (hasPermissionGranted(Manifest.permission.MANAGE_USERS, uid)
1911 && hasPermissionGranted(Manifest.permission.INTERACT_ACROSS_USERS_FULL, uid)) {
1912 // Apps with both permissions are granted privilege.
1913 return;
1914 }
1915
1916 throw new SecurityException(
1917 "You need MANAGE_USERS and INTERACT_ACROSS_USERS_FULL permission to: " + message);
1918 }
1919
1920 private static boolean hasPermissionGranted(String permission, int uid) {
1921 return ActivityManager.checkComponentPermission(
1922 permission, uid, /* owningUid = */-1, /* exported = */ true) ==
1923 PackageManager.PERMISSION_GRANTED;
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001924 }
1925
1926 /**
1927 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001928 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -07001929 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -07001930 *
1931 * @param message used as message if SecurityException is thrown
1932 * @throws SecurityException if the caller is not system or root
Tony Mak4dc008c2016-03-16 10:46:49 +00001933 * @see #hasManageUsersPermission()
Amith Yamasani258848d2012-08-10 17:06:33 -07001934 */
Amith Yamasanibe465322014-04-24 13:45:17 -07001935 private static final void checkManageUsersPermission(String message) {
Tony Mak4dc008c2016-03-16 10:46:49 +00001936 if (!hasManageUsersPermission()) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001937 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
1938 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -04001939 }
1940
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001941 /**
Sudheer Shankaf5cea032016-06-08 17:13:24 -07001942 * Enforces that only the system UID or root's UID or apps that have the
1943 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or
1944 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS}
1945 * can make certain calls to the UserManager.
1946 *
1947 * @param message used as message if SecurityException is thrown
1948 * @throws SecurityException if the caller is not system or root
1949 * @see #hasManageOrCreateUsersPermission()
1950 */
1951 private static final void checkManageOrCreateUsersPermission(String message) {
1952 if (!hasManageOrCreateUsersPermission()) {
1953 throw new SecurityException(
1954 "You either need MANAGE_USERS or CREATE_USERS permission to: " + message);
1955 }
1956 }
1957
1958 /**
1959 * Similar to {@link #checkManageOrCreateUsersPermission(String)} but when the caller is tries
1960 * to create user/profiles other than what is allowed for
1961 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS} permission, then it will only
1962 * allow callers with {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} permission.
1963 */
1964 private static final void checkManageOrCreateUsersPermission(int creationFlags) {
1965 if ((creationFlags & ~ALLOWED_FLAGS_FOR_CREATE_USERS_PERMISSION) == 0) {
1966 if (!hasManageOrCreateUsersPermission()) {
1967 throw new SecurityException("You either need MANAGE_USERS or CREATE_USERS "
1968 + "permission to create an user with flags: " + creationFlags);
1969 }
1970 } else if (!hasManageUsersPermission()) {
1971 throw new SecurityException("You need MANAGE_USERS permission to create an user "
1972 + " with flags: " + creationFlags);
1973 }
1974 }
1975
1976 /**
Tony Mak4dc008c2016-03-16 10:46:49 +00001977 * @return whether the calling UID is system UID or root's UID or the calling app has the
1978 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}.
1979 */
1980 private static final boolean hasManageUsersPermission() {
1981 final int callingUid = Binder.getCallingUid();
1982 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
1983 || callingUid == Process.ROOT_UID
jovanakf24ad492018-05-18 12:15:59 -07001984 || hasPermissionGranted(android.Manifest.permission.MANAGE_USERS, callingUid);
Tony Mak4dc008c2016-03-16 10:46:49 +00001985 }
1986
1987 /**
Sudheer Shankaf5cea032016-06-08 17:13:24 -07001988 * @return whether the calling UID is system UID or root's UID or the calling app has the
Bookatzcde3d922019-03-08 14:30:00 -08001989 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or the provided permission.
Sudheer Shankaf5cea032016-06-08 17:13:24 -07001990 */
Bookatzcde3d922019-03-08 14:30:00 -08001991 private static final boolean hasManageUsersOrPermission(String alternativePermission) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07001992 final int callingUid = Binder.getCallingUid();
1993 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
1994 || callingUid == Process.ROOT_UID
jovanakf24ad492018-05-18 12:15:59 -07001995 || hasPermissionGranted(android.Manifest.permission.MANAGE_USERS, callingUid)
Bookatzcde3d922019-03-08 14:30:00 -08001996 || hasPermissionGranted(alternativePermission, callingUid);
1997 }
1998
1999 /**
2000 * @return whether the calling UID is system UID or root's UID or the calling app has the
2001 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or
2002 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS}.
2003 */
2004 private static final boolean hasManageOrCreateUsersPermission() {
2005 return hasManageUsersOrPermission(android.Manifest.permission.CREATE_USERS);
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002006 }
2007
2008 /**
Esteban Talavera5b9f1672015-12-11 15:22:34 +00002009 * Enforces that only the system UID or root's UID (on any user) can make certain calls to the
2010 * UserManager.
2011 *
2012 * @param message used as message if SecurityException is thrown
2013 * @throws SecurityException if the caller is not system or root
2014 */
2015 private static void checkSystemOrRoot(String message) {
2016 final int uid = Binder.getCallingUid();
2017 if (!UserHandle.isSameApp(uid, Process.SYSTEM_UID) && uid != Process.ROOT_UID) {
2018 throw new SecurityException("Only system may: " + message);
2019 }
2020 }
2021
Fyodor Kupolov82402752015-10-28 14:54:51 -07002022 private void writeBitmapLP(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002023 try {
2024 File dir = new File(mUsersDir, Integer.toString(info.id));
2025 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +01002026 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002027 if (!dir.exists()) {
2028 dir.mkdir();
2029 FileUtils.setPermissions(
2030 dir.getPath(),
2031 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
2032 -1, -1);
2033 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07002034 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +01002035 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01002036 && tmp.renameTo(file) && SELinux.restorecon(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -07002037 info.iconPath = file.getAbsolutePath();
2038 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07002039 try {
2040 os.close();
2041 } catch (IOException ioe) {
2042 // What the ... !
2043 }
Adrian Roos1bdff912015-02-17 15:51:35 +01002044 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002045 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002046 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002047 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002048 }
2049
Amith Yamasani0b285492011-04-14 17:35:23 -07002050 /**
2051 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
2052 * cache it elsewhere.
2053 * @return the array of user ids.
2054 */
Dianne Hackborn1676c852012-09-10 14:52:30 -07002055 public int[] getUserIds() {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002056 synchronized (mUsersLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07002057 return mUserIds;
2058 }
Amith Yamasani0b285492011-04-14 17:35:23 -07002059 }
2060
Andreas Gampe2e8c7672018-07-20 13:01:08 -07002061 @GuardedBy({"mRestrictionsLock", "mPackagesLock"})
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002062 private void readUserListLP() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002063 if (!mUserListFile.exists()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002064 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002065 return;
2066 }
2067 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07002068 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002069 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07002070 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002071 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002072 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002073 int type;
2074 while ((type = parser.next()) != XmlPullParser.START_TAG
2075 && type != XmlPullParser.END_DOCUMENT) {
Amith Yamasani12747872015-12-07 14:19:49 -08002076 // Skip
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002077 }
2078
2079 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07002080 Slog.e(LOG_TAG, "Unable to read user list");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002081 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002082 return;
2083 }
2084
Amith Yamasani2a003292012-08-14 18:25:45 -07002085 mNextSerialNumber = -1;
2086 if (parser.getName().equals(TAG_USERS)) {
2087 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
2088 if (lastSerialNumber != null) {
2089 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
2090 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07002091 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
2092 if (versionNumber != null) {
2093 mUserVersion = Integer.parseInt(versionNumber);
2094 }
Amith Yamasani2a003292012-08-14 18:25:45 -07002095 }
2096
Pavel Grafov6a40f092016-10-25 15:46:51 +01002097 // Pre-O global user restriction were stored as a single bundle (as opposed to per-user
2098 // currently), take care of it in case of upgrade.
2099 Bundle oldDevicePolicyGlobalUserRestrictions = null;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002100
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002101 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05302102 if (type == XmlPullParser.START_TAG) {
2103 final String name = parser.getName();
2104 if (name.equals(TAG_USER)) {
2105 String id = parser.getAttributeValue(null, ATTR_ID);
Amith Yamasani6f34b412012-10-22 18:19:27 -07002106
Amith Yamasani12747872015-12-07 14:19:49 -08002107 UserData userData = readUserLP(Integer.parseInt(id));
2108
2109 if (userData != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002110 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002111 mUsers.put(userData.info.id, userData);
2112 if (mNextSerialNumber < 0
2113 || mNextSerialNumber <= userData.info.id) {
2114 mNextSerialNumber = userData.info.id + 1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002115 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05302116 }
Amith Yamasani2a003292012-08-14 18:25:45 -07002117 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05302118 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -08002119 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2120 && type != XmlPullParser.END_TAG) {
2121 if (type == XmlPullParser.START_TAG) {
2122 if (parser.getName().equals(TAG_RESTRICTIONS)) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002123 synchronized (mGuestRestrictions) {
Fyodor Kupoloveafee022017-03-15 17:09:04 -07002124 UserRestrictionsUtils
2125 .readRestrictions(parser, mGuestRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002126 }
Amith Yamasanida0b1682014-11-21 12:58:17 -08002127 }
2128 break;
2129 }
2130 }
Pavel Grafov6a40f092016-10-25 15:46:51 +01002131 } else if (name.equals(TAG_DEVICE_OWNER_USER_ID)
2132 // Legacy name, should only be encountered when upgrading from pre-O.
2133 || name.equals(TAG_GLOBAL_RESTRICTION_OWNER_ID)) {
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01002134 String ownerUserId = parser.getAttributeValue(null, ATTR_ID);
2135 if (ownerUserId != null) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01002136 mDeviceOwnerUserId = Integer.parseInt(ownerUserId);
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01002137 }
Pavel Grafov6a40f092016-10-25 15:46:51 +01002138 } else if (name.equals(TAG_DEVICE_POLICY_RESTRICTIONS)) {
2139 // Should only happen when upgrading from pre-O (version < 7).
2140 oldDevicePolicyGlobalUserRestrictions =
2141 UserRestrictionsUtils.readRestrictions(parser);
Amith Yamasani258848d2012-08-10 17:06:33 -07002142 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002143 }
2144 }
Pavel Grafov6a40f092016-10-25 15:46:51 +01002145
Fyodor Kupolov82402752015-10-28 14:54:51 -07002146 updateUserIds();
Pavel Grafov6a40f092016-10-25 15:46:51 +01002147 upgradeIfNecessaryLP(oldDevicePolicyGlobalUserRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002148 } catch (IOException | XmlPullParserException e) {
2149 fallbackToSingleUserLP();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08002150 } finally {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002151 IoUtils.closeQuietly(fis);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002152 }
2153 }
2154
Amith Yamasani6f34b412012-10-22 18:19:27 -07002155 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -08002156 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Pavel Grafov6a40f092016-10-25 15:46:51 +01002157 * @param oldGlobalUserRestrictions Pre-O global device policy restrictions.
Amith Yamasani6f34b412012-10-22 18:19:27 -07002158 */
Andreas Gampe2e8c7672018-07-20 13:01:08 -07002159 @GuardedBy({"mRestrictionsLock", "mPackagesLock"})
Pavel Grafov6a40f092016-10-25 15:46:51 +01002160 private void upgradeIfNecessaryLP(Bundle oldGlobalUserRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002161 final int originalVersion = mUserVersion;
Amith Yamasani6f34b412012-10-22 18:19:27 -07002162 int userVersion = mUserVersion;
2163 if (userVersion < 1) {
2164 // Assign a proper name for the owner, if not initialized correctly before
Amith Yamasani12747872015-12-07 14:19:49 -08002165 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
2166 if ("Primary".equals(userData.info.name)) {
2167 userData.info.name =
2168 mContext.getResources().getString(com.android.internal.R.string.owner_name);
2169 scheduleWriteUser(userData);
Amith Yamasani6f34b412012-10-22 18:19:27 -07002170 }
2171 userVersion = 1;
2172 }
2173
Amith Yamasanibc9625052012-11-15 14:39:18 -08002174 if (userVersion < 2) {
2175 // Owner should be marked as initialized
Amith Yamasani12747872015-12-07 14:19:49 -08002176 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
2177 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
2178 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
2179 scheduleWriteUser(userData);
Amith Yamasanibc9625052012-11-15 14:39:18 -08002180 }
2181 userVersion = 2;
2182 }
2183
Amith Yamasani350962c2013-08-06 11:18:53 -07002184
Amith Yamasani5e486f52013-08-07 11:06:44 -07002185 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -07002186 userVersion = 4;
2187 }
2188
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07002189 if (userVersion < 5) {
2190 initDefaultGuestRestrictions();
2191 userVersion = 5;
2192 }
2193
Fyodor Kupolov1c363152015-09-02 13:27:21 -07002194 if (userVersion < 6) {
2195 final boolean splitSystemUser = UserManager.isSplitSystemUser();
Fyodor Kupolov82402752015-10-28 14:54:51 -07002196 synchronized (mUsersLock) {
2197 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002198 UserData userData = mUsers.valueAt(i);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002199 // In non-split mode, only user 0 can have restricted profiles
Amith Yamasani12747872015-12-07 14:19:49 -08002200 if (!splitSystemUser && userData.info.isRestricted()
2201 && (userData.info.restrictedProfileParentId
2202 == UserInfo.NO_PROFILE_GROUP_ID)) {
2203 userData.info.restrictedProfileParentId = UserHandle.USER_SYSTEM;
2204 scheduleWriteUser(userData);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002205 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07002206 }
2207 }
2208 userVersion = 6;
2209 }
2210
Pavel Grafov6a40f092016-10-25 15:46:51 +01002211 if (userVersion < 7) {
2212 // Previously only one user could enforce global restrictions, now it is per-user.
2213 synchronized (mRestrictionsLock) {
2214 if (!UserRestrictionsUtils.isEmpty(oldGlobalUserRestrictions)
2215 && mDeviceOwnerUserId != UserHandle.USER_NULL) {
2216 mDevicePolicyGlobalUserRestrictions.put(
2217 mDeviceOwnerUserId, oldGlobalUserRestrictions);
2218 }
2219 // ENSURE_VERIFY_APPS is now enforced globally even if put by profile owner, so move
2220 // it from local to global bundle for all users who set it.
2221 UserRestrictionsUtils.moveRestriction(UserManager.ENSURE_VERIFY_APPS,
2222 mDevicePolicyLocalUserRestrictions, mDevicePolicyGlobalUserRestrictions
2223 );
2224 }
2225 userVersion = 7;
2226 }
2227
Amith Yamasani6f34b412012-10-22 18:19:27 -07002228 if (userVersion < USER_VERSION) {
2229 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
2230 + USER_VERSION);
2231 } else {
2232 mUserVersion = userVersion;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002233
2234 if (originalVersion < mUserVersion) {
2235 writeUserListLP();
2236 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07002237 }
2238 }
2239
Andreas Gampe2e8c7672018-07-20 13:01:08 -07002240 @GuardedBy({"mPackagesLock", "mRestrictionsLock"})
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002241 private void fallbackToSingleUserLP() {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07002242 int flags = UserInfo.FLAG_INITIALIZED;
2243 // In split system user mode, the admin and primary flags are assigned to the first human
2244 // user.
2245 if (!UserManager.isSplitSystemUser()) {
2246 flags |= UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY;
2247 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -07002248 // Create the system user
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07002249 UserInfo system = new UserInfo(UserHandle.USER_SYSTEM, null, null, flags);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002250 UserData userData = putUserInfo(system);
Amith Yamasani634cf312012-10-04 17:34:21 -07002251 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -04002252 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -08002253
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05002254 Bundle restrictions = new Bundle();
Mahaver Chopra3d9805d2016-07-07 16:25:05 +01002255 try {
2256 final String[] defaultFirstUserRestrictions = mContext.getResources().getStringArray(
2257 com.android.internal.R.array.config_defaultFirstUserRestrictions);
2258 for (String userRestriction : defaultFirstUserRestrictions) {
2259 if (UserRestrictionsUtils.isValidRestriction(userRestriction)) {
2260 restrictions.putBoolean(userRestriction, true);
2261 }
2262 }
2263 } catch (Resources.NotFoundException e) {
2264 Log.e(LOG_TAG, "Couldn't find resource: config_defaultFirstUserRestrictions", e);
2265 }
2266
Pavel Grafov6a40f092016-10-25 15:46:51 +01002267 if (!restrictions.isEmpty()) {
2268 synchronized (mRestrictionsLock) {
2269 mBaseUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions);
2270 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07002271 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08002272
Fyodor Kupolov82402752015-10-28 14:54:51 -07002273 updateUserIds();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07002274 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002275
Amith Yamasani12747872015-12-07 14:19:49 -08002276 writeUserLP(userData);
Jeff Sharkeycd575992016-03-29 14:12:49 -06002277 writeUserListLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002278 }
2279
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07002280 private String getOwnerName() {
2281 return mContext.getResources().getString(com.android.internal.R.string.owner_name);
2282 }
2283
Amith Yamasani12747872015-12-07 14:19:49 -08002284 private void scheduleWriteUser(UserData UserData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002285 if (DBG) {
2286 debug("scheduleWriteUser");
2287 }
Makoto Onuki9e935a32015-11-06 14:24:24 -08002288 // No need to wrap it within a lock -- worst case, we'll just post the same message
2289 // twice.
Amith Yamasani12747872015-12-07 14:19:49 -08002290 if (!mHandler.hasMessages(WRITE_USER_MSG, UserData)) {
2291 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, UserData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002292 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
2293 }
2294 }
2295
Amith Yamasani12747872015-12-07 14:19:49 -08002296 private void writeUserLP(UserData userData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002297 if (DBG) {
Amith Yamasani12747872015-12-07 14:19:49 -08002298 debug("writeUserLP " + userData);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002299 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002300 FileOutputStream fos = null;
Amith Yamasani12747872015-12-07 14:19:49 -08002301 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userData.info.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002302 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07002303 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002304 final BufferedOutputStream bos = new BufferedOutputStream(fos);
Kenny Guy02c89902016-11-15 19:36:38 +00002305 writeUserLP(userData, bos);
Amith Yamasani2a003292012-08-14 18:25:45 -07002306 userFile.finishWrite(fos);
2307 } catch (Exception ioe) {
Jeff Sharkeycd575992016-03-29 14:12:49 -06002308 Slog.e(LOG_TAG, "Error writing user info " + userData.info.id, ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -07002309 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002310 }
2311 }
2312
2313 /*
Kenny Guy02c89902016-11-15 19:36:38 +00002314 * Writes the user file in this format:
2315 *
2316 * <user flags="20039023" id="0">
2317 * <name>Primary</name>
2318 * </user>
2319 */
2320 @VisibleForTesting
2321 void writeUserLP(UserData userData, OutputStream os)
2322 throws IOException, XmlPullParserException {
2323 // XmlSerializer serializer = XmlUtils.serializerInstance();
2324 final XmlSerializer serializer = new FastXmlSerializer();
2325 serializer.setOutput(os, StandardCharsets.UTF_8.name());
2326 serializer.startDocument(null, true);
2327 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2328
2329 final UserInfo userInfo = userData.info;
2330 serializer.startTag(null, TAG_USER);
2331 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
2332 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
2333 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
2334 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
2335 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
2336 Long.toString(userInfo.lastLoggedInTime));
2337 if (userInfo.lastLoggedInFingerprint != null) {
2338 serializer.attribute(null, ATTR_LAST_LOGGED_IN_FINGERPRINT,
2339 userInfo.lastLoggedInFingerprint);
2340 }
2341 if (userInfo.iconPath != null) {
2342 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
2343 }
2344 if (userInfo.partial) {
2345 serializer.attribute(null, ATTR_PARTIAL, "true");
2346 }
Felipe Leme7ad2f6b2019-09-11 09:23:26 -07002347 if (userInfo.preCreated) {
2348 serializer.attribute(null, ATTR_PRE_CREATED, "true");
2349 }
Kenny Guy02c89902016-11-15 19:36:38 +00002350 if (userInfo.guestToRemove) {
2351 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
2352 }
2353 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
2354 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
2355 Integer.toString(userInfo.profileGroupId));
2356 }
2357 serializer.attribute(null, ATTR_PROFILE_BADGE,
2358 Integer.toString(userInfo.profileBadge));
2359 if (userInfo.restrictedProfileParentId != UserInfo.NO_PROFILE_GROUP_ID) {
2360 serializer.attribute(null, ATTR_RESTRICTED_PROFILE_PARENT_ID,
2361 Integer.toString(userInfo.restrictedProfileParentId));
2362 }
2363 // Write seed data
2364 if (userData.persistSeedData) {
2365 if (userData.seedAccountName != null) {
2366 serializer.attribute(null, ATTR_SEED_ACCOUNT_NAME, userData.seedAccountName);
2367 }
2368 if (userData.seedAccountType != null) {
2369 serializer.attribute(null, ATTR_SEED_ACCOUNT_TYPE, userData.seedAccountType);
2370 }
2371 }
2372 if (userInfo.name != null) {
2373 serializer.startTag(null, TAG_NAME);
2374 serializer.text(userInfo.name);
2375 serializer.endTag(null, TAG_NAME);
2376 }
2377 synchronized (mRestrictionsLock) {
2378 UserRestrictionsUtils.writeRestrictions(serializer,
2379 mBaseUserRestrictions.get(userInfo.id), TAG_RESTRICTIONS);
2380 UserRestrictionsUtils.writeRestrictions(serializer,
2381 mDevicePolicyLocalUserRestrictions.get(userInfo.id),
2382 TAG_DEVICE_POLICY_RESTRICTIONS);
Pavel Grafov6a40f092016-10-25 15:46:51 +01002383 UserRestrictionsUtils.writeRestrictions(serializer,
2384 mDevicePolicyGlobalUserRestrictions.get(userInfo.id),
2385 TAG_DEVICE_POLICY_GLOBAL_RESTRICTIONS);
Kenny Guy02c89902016-11-15 19:36:38 +00002386 }
2387
2388 if (userData.account != null) {
2389 serializer.startTag(null, TAG_ACCOUNT);
2390 serializer.text(userData.account);
2391 serializer.endTag(null, TAG_ACCOUNT);
2392 }
2393
2394 if (userData.persistSeedData && userData.seedAccountOptions != null) {
2395 serializer.startTag(null, TAG_SEED_ACCOUNT_OPTIONS);
2396 userData.seedAccountOptions.saveToXml(serializer);
2397 serializer.endTag(null, TAG_SEED_ACCOUNT_OPTIONS);
2398 }
2399
arangelov9b632d72018-12-07 23:21:22 +00002400 if (userData.getLastRequestQuietModeEnabledMillis() != 0L) {
2401 serializer.startTag(/* namespace */ null, TAG_LAST_REQUEST_QUIET_MODE_ENABLED_CALL);
2402 serializer.text(String.valueOf(userData.getLastRequestQuietModeEnabledMillis()));
2403 serializer.endTag(/* namespace */ null, TAG_LAST_REQUEST_QUIET_MODE_ENABLED_CALL);
2404 }
2405
Kenny Guy02c89902016-11-15 19:36:38 +00002406 serializer.endTag(null, TAG_USER);
2407
2408 serializer.endDocument();
2409 }
2410
2411 /*
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002412 * Writes the user list file in this format:
2413 *
Amith Yamasani2a003292012-08-14 18:25:45 -07002414 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002415 * <user id="0"></user>
2416 * <user id="2"></user>
2417 * </users>
2418 */
Andreas Gampe2e8c7672018-07-20 13:01:08 -07002419 @GuardedBy({"mRestrictionsLock", "mPackagesLock"})
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002420 private void writeUserListLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002421 if (DBG) {
2422 debug("writeUserList");
2423 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002424 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07002425 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002426 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07002427 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002428 final BufferedOutputStream bos = new BufferedOutputStream(fos);
2429
2430 // XmlSerializer serializer = XmlUtils.serializerInstance();
2431 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002432 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002433 serializer.startDocument(null, true);
2434 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2435
2436 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -07002437 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -07002438 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002439
Adam Lesinskieddeb492014-09-08 17:50:03 -07002440 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002441 synchronized (mGuestRestrictions) {
2442 UserRestrictionsUtils
2443 .writeRestrictions(serializer, mGuestRestrictions, TAG_RESTRICTIONS);
2444 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05302445 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Pavel Grafov6a40f092016-10-25 15:46:51 +01002446 serializer.startTag(null, TAG_DEVICE_OWNER_USER_ID);
2447 serializer.attribute(null, ATTR_ID, Integer.toString(mDeviceOwnerUserId));
2448 serializer.endTag(null, TAG_DEVICE_OWNER_USER_ID);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002449 int[] userIdsToWrite;
2450 synchronized (mUsersLock) {
2451 userIdsToWrite = new int[mUsers.size()];
2452 for (int i = 0; i < userIdsToWrite.length; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002453 UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002454 userIdsToWrite[i] = user.id;
2455 }
2456 }
2457 for (int id : userIdsToWrite) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002458 serializer.startTag(null, TAG_USER);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002459 serializer.attribute(null, ATTR_ID, Integer.toString(id));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002460 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002461 }
2462
2463 serializer.endTag(null, TAG_USERS);
2464
2465 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07002466 userListFile.finishWrite(fos);
2467 } catch (Exception e) {
2468 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -07002469 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002470 }
2471 }
2472
Amith Yamasani12747872015-12-07 14:19:49 -08002473 private UserData readUserLP(int id) {
Kenny Guy02c89902016-11-15 19:36:38 +00002474 FileInputStream fis = null;
2475 try {
2476 AtomicFile userFile =
2477 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
2478 fis = userFile.openRead();
2479 return readUserLP(id, fis);
2480 } catch (IOException ioe) {
2481 Slog.e(LOG_TAG, "Error reading user list");
2482 } catch (XmlPullParserException pe) {
2483 Slog.e(LOG_TAG, "Error reading user list");
2484 } finally {
2485 IoUtils.closeQuietly(fis);
2486 }
2487 return null;
2488 }
2489
2490 @VisibleForTesting
2491 UserData readUserLP(int id, InputStream is) throws IOException,
2492 XmlPullParserException {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002493 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -07002494 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002495 String name = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -08002496 String account = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002497 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -07002498 long creationTime = 0L;
2499 long lastLoggedInTime = 0L;
arangelov9b632d72018-12-07 23:21:22 +00002500 long lastRequestQuietModeEnabledTimestamp = 0L;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002501 String lastLoggedInFingerprint = null;
Kenny Guy2a764942014-04-02 13:29:20 +01002502 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Kenny Guy02c89902016-11-15 19:36:38 +00002503 int profileBadge = 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002504 int restrictedProfileParentId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002505 boolean partial = false;
Felipe Leme7ad2f6b2019-09-11 09:23:26 -07002506 boolean preCreated = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -07002507 boolean guestToRemove = false;
Amith Yamasani12747872015-12-07 14:19:49 -08002508 boolean persistSeedData = false;
2509 String seedAccountName = null;
2510 String seedAccountType = null;
2511 PersistableBundle seedAccountOptions = null;
Pavel Grafov6a40f092016-10-25 15:46:51 +01002512 Bundle baseRestrictions = null;
2513 Bundle localRestrictions = null;
2514 Bundle globalRestrictions = null;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002515
Kenny Guy02c89902016-11-15 19:36:38 +00002516 XmlPullParser parser = Xml.newPullParser();
2517 parser.setInput(is, StandardCharsets.UTF_8.name());
2518 int type;
2519 while ((type = parser.next()) != XmlPullParser.START_TAG
2520 && type != XmlPullParser.END_DOCUMENT) {
2521 // Skip
2522 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002523
Kenny Guy02c89902016-11-15 19:36:38 +00002524 if (type != XmlPullParser.START_TAG) {
2525 Slog.e(LOG_TAG, "Unable to read user " + id);
2526 return null;
2527 }
2528
2529 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
2530 int storedId = readIntAttribute(parser, ATTR_ID, -1);
2531 if (storedId != id) {
2532 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002533 return null;
2534 }
Kenny Guy02c89902016-11-15 19:36:38 +00002535 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
2536 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
2537 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
2538 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
2539 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
2540 lastLoggedInFingerprint = parser.getAttributeValue(null,
2541 ATTR_LAST_LOGGED_IN_FINGERPRINT);
2542 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
2543 UserInfo.NO_PROFILE_GROUP_ID);
2544 profileBadge = readIntAttribute(parser, ATTR_PROFILE_BADGE, 0);
2545 restrictedProfileParentId = readIntAttribute(parser,
2546 ATTR_RESTRICTED_PROFILE_PARENT_ID, UserInfo.NO_PROFILE_GROUP_ID);
2547 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
2548 if ("true".equals(valueString)) {
2549 partial = true;
2550 }
Felipe Leme7ad2f6b2019-09-11 09:23:26 -07002551 valueString = parser.getAttributeValue(null, ATTR_PRE_CREATED);
2552 if ("true".equals(valueString)) {
2553 preCreated = true;
2554 }
Kenny Guy02c89902016-11-15 19:36:38 +00002555 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
2556 if ("true".equals(valueString)) {
2557 guestToRemove = true;
2558 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002559
Kenny Guy02c89902016-11-15 19:36:38 +00002560 seedAccountName = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_NAME);
2561 seedAccountType = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_TYPE);
2562 if (seedAccountName != null || seedAccountType != null) {
2563 persistSeedData = true;
2564 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002565
Kenny Guy02c89902016-11-15 19:36:38 +00002566 int outerDepth = parser.getDepth();
2567 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2568 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2569 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2570 continue;
2571 }
2572 String tag = parser.getName();
2573 if (TAG_NAME.equals(tag)) {
2574 type = parser.next();
2575 if (type == XmlPullParser.TEXT) {
2576 name = parser.getText();
2577 }
2578 } else if (TAG_RESTRICTIONS.equals(tag)) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01002579 baseRestrictions = UserRestrictionsUtils.readRestrictions(parser);
Kenny Guy02c89902016-11-15 19:36:38 +00002580 } else if (TAG_DEVICE_POLICY_RESTRICTIONS.equals(tag)) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01002581 localRestrictions = UserRestrictionsUtils.readRestrictions(parser);
2582 } else if (TAG_DEVICE_POLICY_GLOBAL_RESTRICTIONS.equals(tag)) {
2583 globalRestrictions = UserRestrictionsUtils.readRestrictions(parser);
Kenny Guy02c89902016-11-15 19:36:38 +00002584 } else if (TAG_ACCOUNT.equals(tag)) {
2585 type = parser.next();
2586 if (type == XmlPullParser.TEXT) {
2587 account = parser.getText();
2588 }
2589 } else if (TAG_SEED_ACCOUNT_OPTIONS.equals(tag)) {
2590 seedAccountOptions = PersistableBundle.restoreFromXml(parser);
Amith Yamasani12747872015-12-07 14:19:49 -08002591 persistSeedData = true;
arangelov9b632d72018-12-07 23:21:22 +00002592 } else if (TAG_LAST_REQUEST_QUIET_MODE_ENABLED_CALL.equals(tag)) {
2593 type = parser.next();
2594 if (type == XmlPullParser.TEXT) {
2595 lastRequestQuietModeEnabledTimestamp = Long.parseLong(parser.getText());
2596 }
Amith Yamasani12747872015-12-07 14:19:49 -08002597 }
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08002598 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002599 }
Kenny Guy02c89902016-11-15 19:36:38 +00002600
2601 // Create the UserInfo object that gets passed around
2602 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
2603 userInfo.serialNumber = serialNumber;
2604 userInfo.creationTime = creationTime;
2605 userInfo.lastLoggedInTime = lastLoggedInTime;
2606 userInfo.lastLoggedInFingerprint = lastLoggedInFingerprint;
2607 userInfo.partial = partial;
Felipe Leme7ad2f6b2019-09-11 09:23:26 -07002608 userInfo.preCreated = preCreated;
Kenny Guy02c89902016-11-15 19:36:38 +00002609 userInfo.guestToRemove = guestToRemove;
2610 userInfo.profileGroupId = profileGroupId;
2611 userInfo.profileBadge = profileBadge;
2612 userInfo.restrictedProfileParentId = restrictedProfileParentId;
2613
2614 // Create the UserData object that's internal to this class
2615 UserData userData = new UserData();
2616 userData.info = userInfo;
2617 userData.account = account;
2618 userData.seedAccountName = seedAccountName;
2619 userData.seedAccountType = seedAccountType;
2620 userData.persistSeedData = persistSeedData;
2621 userData.seedAccountOptions = seedAccountOptions;
arangelov9b632d72018-12-07 23:21:22 +00002622 userData.setLastRequestQuietModeEnabledMillis(lastRequestQuietModeEnabledTimestamp);
Kenny Guy02c89902016-11-15 19:36:38 +00002623
2624 synchronized (mRestrictionsLock) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01002625 if (baseRestrictions != null) {
2626 mBaseUserRestrictions.put(id, baseRestrictions);
2627 }
2628 if (localRestrictions != null) {
2629 mDevicePolicyLocalUserRestrictions.put(id, localRestrictions);
2630 }
2631 if (globalRestrictions != null) {
2632 mDevicePolicyGlobalUserRestrictions.put(id, globalRestrictions);
2633 }
Kenny Guy02c89902016-11-15 19:36:38 +00002634 }
2635 return userData;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002636 }
2637
Amith Yamasani920ace02012-09-20 22:15:37 -07002638 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
2639 String valueString = parser.getAttributeValue(null, attr);
2640 if (valueString == null) return defaultValue;
2641 try {
2642 return Integer.parseInt(valueString);
2643 } catch (NumberFormatException nfe) {
2644 return defaultValue;
2645 }
2646 }
2647
2648 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
2649 String valueString = parser.getAttributeValue(null, attr);
2650 if (valueString == null) return defaultValue;
2651 try {
2652 return Long.parseLong(valueString);
2653 } catch (NumberFormatException nfe) {
2654 return defaultValue;
2655 }
2656 }
2657
Amith Yamasanib82add22013-07-09 11:24:44 -07002658 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002659 * Removes the app restrictions file for a specific package and user id, if it exists.
2660 */
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07002661 private static void cleanAppRestrictionsForPackageLAr(String pkg, int userId) {
2662 File dir = Environment.getUserSystemDirectory(userId);
2663 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
2664 if (resFile.exists()) {
2665 resFile.delete();
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002666 }
2667 }
2668
Kenny Guya52dc3e2014-02-11 15:33:14 +00002669 @Override
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002670 public UserInfo createProfileForUser(String name, int flags, int userId,
2671 String[] disallowedPackages) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002672 checkManageOrCreateUsersPermission(flags);
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002673 return createUserInternal(name, flags, userId, disallowedPackages);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002674 }
2675
Amith Yamasani258848d2012-08-10 17:06:33 -07002676 @Override
Tony Mak6dc428f2016-10-10 15:48:27 +01002677 public UserInfo createProfileForUserEvenWhenDisallowed(String name, int flags, int userId,
2678 String[] disallowedPackages) {
2679 checkManageOrCreateUsersPermission(flags);
Felipe Leme7ad2f6b2019-09-11 09:23:26 -07002680 return createUserInternalUnchecked(name, flags, userId, /* preCreate= */ false,
2681 disallowedPackages);
Tony Mak6dc428f2016-10-10 15:48:27 +01002682 }
2683
2684 @Override
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00002685 public boolean removeUserEvenWhenDisallowed(@UserIdInt int userHandle) {
2686 checkManageOrCreateUsersPermission("Only the system can remove users");
2687 return removeUserUnchecked(userHandle);
2688 }
2689
2690 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07002691 public UserInfo createUser(String name, int flags) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002692 checkManageOrCreateUsersPermission(flags);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00002693 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002694 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07002695
Felipe Leme7ad2f6b2019-09-11 09:23:26 -07002696 @Override
2697 public UserInfo preCreateUser(int flags) {
2698 checkManageOrCreateUsersPermission(flags);
2699
2700 Preconditions.checkArgument(!UserInfo.isManagedProfile(flags),
2701 "cannot pre-create managed profiles");
2702
Felipe Leme0b3863f2019-10-02 16:27:46 -07002703 Slog.i(LOG_TAG, "Pre-creating user with flags " + UserInfo.flagsToString(flags));
2704
Felipe Leme7ad2f6b2019-09-11 09:23:26 -07002705 return createUserInternalUnchecked(/* name= */ null, flags,
2706 /* parentId= */ UserHandle.USER_NULL, /* preCreate= */ true,
2707 /* disallowedPackages= */ null);
2708 }
2709
2710 private UserInfo createUserInternal(@Nullable String name, @UserInfoFlag int flags,
2711 @UserIdInt int parentId) {
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002712 return createUserInternal(name, flags, parentId, null);
2713 }
2714
Felipe Leme7ad2f6b2019-09-11 09:23:26 -07002715 private UserInfo createUserInternal(@Nullable String name, @UserInfoFlag int flags,
2716 @UserIdInt int parentId, @Nullable String[] disallowedPackages) {
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002717 String restriction = ((flags & UserInfo.FLAG_MANAGED_PROFILE) != 0)
2718 ? UserManager.DISALLOW_ADD_MANAGED_PROFILE
2719 : UserManager.DISALLOW_ADD_USER;
2720 if (hasUserRestriction(restriction, UserHandle.getCallingUserId())) {
2721 Log.w(LOG_TAG, "Cannot add user. " + restriction + " is enabled.");
Julia Reynolds75175022014-06-26 16:35:00 -04002722 return null;
2723 }
Felipe Leme7ad2f6b2019-09-11 09:23:26 -07002724 return createUserInternalUnchecked(name, flags, parentId, /* preCreate= */ false,
2725 disallowedPackages);
Tony Mak6dc428f2016-10-10 15:48:27 +01002726 }
2727
Felipe Leme7ad2f6b2019-09-11 09:23:26 -07002728 private UserInfo createUserInternalUnchecked(@Nullable String name, @UserInfoFlag int flags,
2729 @UserIdInt int parentId, boolean preCreate,
2730 @Nullable String[] disallowedPackages) {
2731 final TimingsTraceLog t = new TimingsTraceLog(LOG_TAG, Trace.TRACE_TAG_SYSTEM_SERVER);
2732 t.traceBegin("createUser-" + flags);
2733 try {
2734 return createUserInternalUncheckedNoTracing(name, flags, parentId, preCreate,
2735 disallowedPackages, t);
2736 } finally {
2737 t.traceEnd();
2738 }
2739 }
2740
2741 private UserInfo createUserInternalUncheckedNoTracing(@Nullable String name,
2742 @UserInfoFlag int flags, @UserIdInt int parentId, boolean preCreate,
2743 @Nullable String[] disallowedPackages, @NonNull TimingsTraceLog t) {
2744
2745 // First try to use a pre-created user (if available).
2746 // NOTE: currently we don't support pre-created managed profiles
2747 if (!preCreate && (parentId < 0 && !UserInfo.isManagedProfile(flags))) {
2748 final UserData preCreatedUserData;
2749 synchronized (mUsersLock) {
2750 preCreatedUserData = getPreCreatedUserLU(flags);
2751 }
2752 if (preCreatedUserData != null) {
2753 final UserInfo preCreatedUser = preCreatedUserData.info;
2754 Log.i(LOG_TAG, "Reusing pre-created user " + preCreatedUser.id + " for flags + "
2755 + UserInfo.flagsToString(flags));
2756 if (DBG) {
2757 Log.d(LOG_TAG, "pre-created user flags: "
2758 + UserInfo.flagsToString(preCreatedUser.flags)
2759 + " new-user flags: " + UserInfo.flagsToString(flags));
2760 }
2761 preCreatedUser.name = name;
2762 preCreatedUser.preCreated = false;
2763 preCreatedUser.creationTime = getCreationTime();
2764
2765 dispatchUserAddedIntent(preCreatedUser);
2766
2767 writeUserLP(preCreatedUserData);
2768 writeUserListLP();
2769
2770 return preCreatedUser;
2771 }
2772 }
2773
Suprabh Shuklac5e057c2016-08-08 16:22:44 -07002774 DeviceStorageMonitorInternal dsm = LocalServices
2775 .getService(DeviceStorageMonitorInternal.class);
2776 if (dsm.isMemoryLow()) {
2777 Log.w(LOG_TAG, "Cannot add user. Not enough space on disk.");
2778 return null;
2779 }
Felipe Leme7ad2f6b2019-09-11 09:23:26 -07002780 final boolean isGuest = UserInfo.isGuest(flags);
2781 final boolean isManagedProfile = UserInfo.isManagedProfile(flags);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002782 final boolean isRestricted = (flags & UserInfo.FLAG_RESTRICTED) != 0;
Amith Yamasani52c21e32016-05-31 09:12:20 -07002783 final boolean isDemo = (flags & UserInfo.FLAG_DEMO) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002784 final long ident = Binder.clearCallingIdentity();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002785 UserInfo userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08002786 UserData userData;
Amith Yamasanibb054c92015-07-09 14:16:27 -07002787 final int userId;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002788 try {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002789 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002790 UserData parent = null;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002791 if (parentId != UserHandle.USER_NULL) {
2792 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002793 parent = getUserDataLU(parentId);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00002794 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002795 if (parent == null) return null;
2796 }
2797 if (isManagedProfile && !canAddMoreManagedProfiles(parentId, false)) {
2798 Log.e(LOG_TAG, "Cannot add more managed profiles for user " + parentId);
2799 return null;
2800 }
Amith Yamasani52c21e32016-05-31 09:12:20 -07002801 if (!isGuest && !isManagedProfile && !isDemo && isUserLimitReached()) {
Felipe Leme7ad2f6b2019-09-11 09:23:26 -07002802 // If we're not adding a guest/demo user or a managed profile,
2803 // and the limit has been reached, cannot add a user.
jovanaka6763a32018-12-03 17:23:20 -08002804 Log.e(LOG_TAG, "Cannot add user. Maximum user limit is reached.");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002805 return null;
2806 }
2807 // If we're adding a guest and there already exists one, bail.
2808 if (isGuest && findCurrentGuestUser() != null) {
jovanaka6763a32018-12-03 17:23:20 -08002809 Log.e(LOG_TAG, "Cannot add guest user. Guest user already exists.");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002810 return null;
2811 }
2812 // In legacy mode, restricted profile's parent can only be the owner user
2813 if (isRestricted && !UserManager.isSplitSystemUser()
2814 && (parentId != UserHandle.USER_SYSTEM)) {
2815 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
2816 return null;
2817 }
2818 if (isRestricted && UserManager.isSplitSystemUser()) {
2819 if (parent == null) {
2820 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be "
2821 + "specified");
Nicolas Prevot12678a92015-05-13 12:15:03 -07002822 return null;
2823 }
Amith Yamasani12747872015-12-07 14:19:49 -08002824 if (!parent.info.canHaveProfile()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002825 Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be "
2826 + "created for the specified parent user id " + parentId);
Amith Yamasani95ab7842014-08-11 17:09:26 -07002827 return null;
2828 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002829 }
2830 // In split system user mode, we assign the first human user the primary flag.
2831 // And if there is no device owner, we also assign the admin flag to primary user.
2832 if (UserManager.isSplitSystemUser()
2833 && !isGuest && !isManagedProfile && getPrimaryUser() == null) {
2834 flags |= UserInfo.FLAG_PRIMARY;
Makoto Onukie7927da2015-11-25 10:05:17 -08002835 synchronized (mUsersLock) {
2836 if (!mIsDeviceManaged) {
2837 flags |= UserInfo.FLAG_ADMIN;
2838 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07002839 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002840 }
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002841
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002842 userId = getNextAvailableId();
2843 Environment.getUserSystemDirectory(userId).mkdirs();
Felipe Leme7ad2f6b2019-09-11 09:23:26 -07002844 boolean ephemeralGuests = areGuestUsersEphemeral();
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002845
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002846 synchronized (mUsersLock) {
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002847 // Add ephemeral flag to guests/users if required. Also inherit it from parent.
2848 if ((isGuest && ephemeralGuests) || mForceEphemeralUsers
2849 || (parent != null && parent.info.isEphemeral())) {
2850 flags |= UserInfo.FLAG_EPHEMERAL;
2851 }
2852
2853 userInfo = new UserInfo(userId, name, null, flags);
2854 userInfo.serialNumber = mNextSerialNumber++;
Felipe Leme7ad2f6b2019-09-11 09:23:26 -07002855 userInfo.creationTime = getCreationTime();
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002856 userInfo.partial = true;
Felipe Leme7ad2f6b2019-09-11 09:23:26 -07002857 userInfo.preCreated = preCreate;
Fyodor Kupolov83c24242016-03-31 13:30:42 -07002858 userInfo.lastLoggedInFingerprint = Build.FINGERPRINT;
Kenny Guy02c89902016-11-15 19:36:38 +00002859 if (isManagedProfile && parentId != UserHandle.USER_NULL) {
2860 userInfo.profileBadge = getFreeProfileBadgeLU(parentId);
2861 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002862 userData = new UserData();
2863 userData.info = userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08002864 mUsers.put(userId, userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002865 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06002866 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002867 writeUserListLP();
2868 if (parent != null) {
2869 if (isManagedProfile) {
Amith Yamasani12747872015-12-07 14:19:49 -08002870 if (parent.info.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
2871 parent.info.profileGroupId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002872 writeUserLP(parent);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002873 }
Amith Yamasani12747872015-12-07 14:19:49 -08002874 userInfo.profileGroupId = parent.info.profileGroupId;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002875 } else if (isRestricted) {
Amith Yamasani12747872015-12-07 14:19:49 -08002876 if (parent.info.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) {
2877 parent.info.restrictedProfileParentId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002878 writeUserLP(parent);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002879 }
Amith Yamasani12747872015-12-07 14:19:49 -08002880 userInfo.restrictedProfileParentId = parent.info.restrictedProfileParentId;
Makoto Onuki068c54a2015-10-13 14:34:03 -07002881 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002882 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07002883 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002884 final StorageManager storage = mContext.getSystemService(StorageManager.class);
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002885 storage.createUserKey(userId, userInfo.serialNumber, userInfo.isEphemeral());
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -08002886 mUserDataPreparer.prepareUserData(userId, userInfo.serialNumber,
Jeff Sharkey47f71082016-02-01 17:03:54 -07002887 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002888 mPm.createNewUser(userId, disallowedPackages);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002889 userInfo.partial = false;
2890 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002891 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002892 }
2893 updateUserIds();
2894 Bundle restrictions = new Bundle();
Fyodor Kupolove04462c2015-11-30 15:02:53 -08002895 if (isGuest) {
2896 synchronized (mGuestRestrictions) {
2897 restrictions.putAll(mGuestRestrictions);
2898 }
2899 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002900 synchronized (mRestrictionsLock) {
2901 mBaseUserRestrictions.append(userId, restrictions);
2902 }
Fyodor Kupolov5fd967d2016-07-12 14:46:19 -07002903 mPm.onNewUserCreated(userId);
Felipe Leme7ad2f6b2019-09-11 09:23:26 -07002904 if (preCreate) {
2905 // Must start user (which will be stopped right away, through
2906 // UserController.finishUserUnlockedCompleted) so services can properly
2907 // intialize it.
2908 // TODO(b/140750212): in the long-term, we should add a onCreateUser() callback
2909 // on SystemService instead.
2910 Slog.i(LOG_TAG, "starting pre-created user " + userInfo.toFullString());
2911 final IActivityManager am = ActivityManager.getService();
2912 try {
2913 am.startUserInBackground(userId);
2914 } catch (RemoteException e) {
2915 Slog.w(LOG_TAG, "could not start pre-created user " + userId, e);
2916 }
2917 } else {
2918 dispatchUserAddedIntent(userInfo);
2919 }
2920
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002921 } finally {
2922 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07002923 }
Felipe Leme7ad2f6b2019-09-11 09:23:26 -07002924
2925 // TODO(b/140750212): it's possible to reach "max users overflow" when the user is created
2926 // "from scratch" (i.e., not from a pre-created user) and reaches the maximum number of
2927 // users without counting the pre-created one. Then when the pre-created is converted, the
2928 // "effective" number of max users is exceeds. Example:
2929 // Max: 3 Current: 2 full (u0 and u10) + 1 pre-created (u11)
2930 // Step 1: create(/* flags doesn't match u11 */): u12 is created, "effective max" is now 3
2931 // (u0, u10, u12) but "real" max is 4 (u0, u10, u11, u12)
2932 // Step 2: create(/* flags match u11 */): u11 is converted, now "effective max" is also 4
2933 // (u0, u10, u11, u12)
2934 // One way to avoid this issue is by removing a pre-created user from the pool when the
2935 // "real" max exceeds the max here.
2936
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002937 return userInfo;
2938 }
2939
Felipe Leme7ad2f6b2019-09-11 09:23:26 -07002940 private long getCreationTime() {
2941 final long now = System.currentTimeMillis();
2942 return (now > EPOCH_PLUS_30_YEARS) ? now : 0;
2943 }
2944
2945 private void dispatchUserAddedIntent(@NonNull UserInfo userInfo) {
2946 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
2947 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userInfo.id);
2948 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
2949 android.Manifest.permission.MANAGE_USERS);
2950 MetricsLogger.count(mContext, userInfo.isGuest() ? TRON_GUEST_CREATED
2951 : (userInfo.isDemo() ? TRON_DEMO_CREATED : TRON_USER_CREATED), 1);
2952 }
2953
2954 private boolean areGuestUsersEphemeral() {
2955 return Resources.getSystem()
2956 .getBoolean(com.android.internal.R.bool.config_guestUserEphemeral);
2957 }
2958
2959 /**
2960 * Gets a pre-created user for the given flag.
2961 *
2962 * <p>Should be used only during user creation, so the pre-created user can be used (instead of
2963 * creating and initializing a new user from scratch).
2964 */
2965 // TODO(b/140750212): add unit test
2966 @GuardedBy("mUsersLock")
2967 private @Nullable UserData getPreCreatedUserLU(@UserInfoFlag int flags) {
2968 if (DBG) {
2969 Slog.d(LOG_TAG, "getPreCreatedUser(): initialFlags= " + UserInfo.flagsToString(flags));
2970 }
2971 if (UserInfo.isGuest(flags) && areGuestUsersEphemeral()) {
2972 flags |= UserInfo.FLAG_EPHEMERAL;
2973 }
2974 if (DBG) {
2975 Slog.d(LOG_TAG, "getPreCreatedUser(): targetFlags= " + UserInfo.flagsToString(flags));
2976 }
2977 final int userSize = mUsers.size();
2978 for (int i = 0; i < userSize; i++) {
2979 final UserData user = mUsers.valueAt(i);
2980 if (DBG) Slog.d(LOG_TAG, i + ":" + user.info.toFullString());
2981 if (user.info.preCreated
2982 && (user.info.flags & ~UserInfo.FLAG_INITIALIZED) == flags) {
2983 if (!user.info.isInitialized()) {
2984 Slog.w(LOG_TAG, "found pre-created user for flags "
2985 + "" + UserInfo.flagsToString(flags)
2986 + ", but it's not initialized yet: " + user.info.toFullString());
2987 continue;
2988 }
2989 return user;
2990 }
2991 }
2992 return null;
2993 }
2994
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002995 @VisibleForTesting
2996 UserData putUserInfo(UserInfo userInfo) {
2997 final UserData userData = new UserData();
2998 userData.info = userInfo;
2999 synchronized (mUsers) {
3000 mUsers.put(userInfo.id, userData);
3001 }
3002 return userData;
3003 }
3004
3005 @VisibleForTesting
3006 void removeUserInfo(int userId) {
3007 synchronized (mUsers) {
3008 mUsers.remove(userId);
3009 }
3010 }
3011
Amith Yamasani0b285492011-04-14 17:35:23 -07003012 /**
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003013 * @hide
3014 */
Amith Yamasani12747872015-12-07 14:19:49 -08003015 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003016 public UserInfo createRestrictedProfile(String name, int parentUserId) {
Sudheer Shanka53d41472016-06-16 09:11:08 -07003017 checkManageOrCreateUsersPermission("setupRestrictedProfile");
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07003018 final UserInfo user = createProfileForUser(
3019 name, UserInfo.FLAG_RESTRICTED, parentUserId, null);
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003020 if (user == null) {
3021 return null;
3022 }
Fyodor Kupolov9e912ba2016-02-09 18:29:43 -08003023 long identity = Binder.clearCallingIdentity();
3024 try {
3025 setUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, true, user.id);
3026 // Change the setting before applying the DISALLOW_SHARE_LOCATION restriction, otherwise
3027 // the putIntForUser() will fail.
3028 android.provider.Settings.Secure.putIntForUser(mContext.getContentResolver(),
3029 android.provider.Settings.Secure.LOCATION_MODE,
3030 android.provider.Settings.Secure.LOCATION_MODE_OFF, user.id);
3031 setUserRestriction(UserManager.DISALLOW_SHARE_LOCATION, true, user.id);
3032 } finally {
3033 Binder.restoreCallingIdentity(identity);
3034 }
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003035 return user;
3036 }
3037
3038 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07003039 * Find the current guest user. If the Guest user is partial,
3040 * then do not include it in the results as it is about to die.
Adam Lesinskieddeb492014-09-08 17:50:03 -07003041 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07003042 private UserInfo findCurrentGuestUser() {
3043 synchronized (mUsersLock) {
3044 final int size = mUsers.size();
3045 for (int i = 0; i < size; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003046 final UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003047 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
3048 return user;
3049 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07003050 }
3051 }
3052 return null;
3053 }
3054
3055 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07003056 * Mark this guest user for deletion to allow us to create another guest
3057 * and switch to that user before actually removing this guest.
3058 * @param userHandle the userid of the current guest
3059 * @return whether the user could be marked for deletion
3060 */
Amith Yamasani12747872015-12-07 14:19:49 -08003061 @Override
Amith Yamasani1df14732014-08-29 21:37:27 -07003062 public boolean markGuestForDeletion(int userHandle) {
3063 checkManageUsersPermission("Only the system can remove users");
3064 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
3065 UserManager.DISALLOW_REMOVE_USER, false)) {
3066 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
3067 return false;
3068 }
3069
3070 long ident = Binder.clearCallingIdentity();
3071 try {
Amith Yamasani12747872015-12-07 14:19:49 -08003072 final UserData userData;
Amith Yamasani1df14732014-08-29 21:37:27 -07003073 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003074 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08003075 userData = mUsers.get(userHandle);
3076 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003077 return false;
3078 }
Amith Yamasani1df14732014-08-29 21:37:27 -07003079 }
Amith Yamasani12747872015-12-07 14:19:49 -08003080 if (!userData.info.isGuest()) {
Amith Yamasani1df14732014-08-29 21:37:27 -07003081 return false;
3082 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07003083 // We set this to a guest user that is to be removed. This is a temporary state
3084 // where we are allowed to add new Guest users, even if this one is still not
3085 // removed. This user will still show up in getUserInfo() calls.
3086 // If we don't get around to removing this Guest user, it will be purged on next
3087 // startup.
Amith Yamasani12747872015-12-07 14:19:49 -08003088 userData.info.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07003089 // Mark it as disabled, so that it isn't returned any more when
3090 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08003091 userData.info.flags |= UserInfo.FLAG_DISABLED;
3092 writeUserLP(userData);
Amith Yamasani1df14732014-08-29 21:37:27 -07003093 }
3094 } finally {
3095 Binder.restoreCallingIdentity(ident);
3096 }
3097 return true;
3098 }
3099
3100 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07003101 * Removes a user and all data directories created for that user. This method should be called
3102 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07003103 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07003104 */
Amith Yamasani12747872015-12-07 14:19:49 -08003105 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -07003106 public boolean removeUser(int userHandle) {
Fyodor Kupolov4593e422016-10-27 11:00:29 -07003107 Slog.i(LOG_TAG, "removeUser u" + userHandle);
Sudheer Shankaf5cea032016-06-08 17:13:24 -07003108 checkManageOrCreateUsersPermission("Only the system can remove users");
Esteban Talavera6c9116a2016-11-24 16:12:44 +00003109
3110 final boolean isManagedProfile;
3111 synchronized (mUsersLock) {
3112 UserInfo userInfo = getUserInfoLU(userHandle);
3113 isManagedProfile = userInfo != null && userInfo.isManagedProfile();
3114 }
3115 String restriction = isManagedProfile
3116 ? UserManager.DISALLOW_REMOVE_MANAGED_PROFILE : UserManager.DISALLOW_REMOVE_USER;
3117 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(restriction, false)) {
3118 Log.w(LOG_TAG, "Cannot remove user. " + restriction + " is enabled.");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04003119 return false;
3120 }
Nicolas Prevotdf1b87d2016-10-25 13:57:08 +01003121 return removeUserUnchecked(userHandle);
3122 }
Julia Reynolds4ac5f852014-06-23 17:38:51 -04003123
Nicolas Prevotdf1b87d2016-10-25 13:57:08 +01003124 private boolean removeUserUnchecked(int userHandle) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01003125 long ident = Binder.clearCallingIdentity();
3126 try {
Amith Yamasani12747872015-12-07 14:19:49 -08003127 final UserData userData;
Fyodor Kupolov0df68cd2015-10-01 13:54:22 -07003128 int currentUser = ActivityManager.getCurrentUser();
3129 if (currentUser == userHandle) {
jovanaka6763a32018-12-03 17:23:20 -08003130 Log.w(LOG_TAG, "Current user cannot be removed.");
Fyodor Kupolov0df68cd2015-10-01 13:54:22 -07003131 return false;
3132 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01003133 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003134 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08003135 userData = mUsers.get(userHandle);
jovanaka6763a32018-12-03 17:23:20 -08003136 if (userHandle == UserHandle.USER_SYSTEM) {
3137 Log.e(LOG_TAG, "System user cannot be removed.");
3138 return false;
3139 }
3140
3141 if (userData == null) {
3142 Log.e(LOG_TAG, String.format(
3143 "Cannot remove user %d, invalid user id provided.", userHandle));
3144 return false;
3145 }
3146
3147 if (mRemovingUserIds.get(userHandle)) {
3148 Log.e(LOG_TAG, String.format(
3149 "User %d is already scheduled for removal.", userHandle));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003150 return false;
3151 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08003152
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003153 addRemovingUserIdLocked(userHandle);
Fyodor Kupolov82402752015-10-28 14:54:51 -07003154 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08003155
Kenny Guyee58b4f2014-05-23 15:19:53 +01003156 // Set this to a partially created user, so that the user will be purged
3157 // on next startup, in case the runtime stops now before stopping and
3158 // removing the user completely.
Amith Yamasani12747872015-12-07 14:19:49 -08003159 userData.info.partial = true;
Kenny Guyee58b4f2014-05-23 15:19:53 +01003160 // Mark it as disabled, so that it isn't returned any more when
3161 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08003162 userData.info.flags |= UserInfo.FLAG_DISABLED;
3163 writeUserLP(userData);
Kenny Guyee58b4f2014-05-23 15:19:53 +01003164 }
Fyodor Kupolov6c96f7f2017-06-28 18:22:59 -07003165 try {
3166 mAppOpsService.removeUser(userHandle);
3167 } catch (RemoteException e) {
jovanaka6763a32018-12-03 17:23:20 -08003168 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user.", e);
Fyodor Kupolov6c96f7f2017-06-28 18:22:59 -07003169 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01003170
Amith Yamasani12747872015-12-07 14:19:49 -08003171 if (userData.info.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
3172 && userData.info.isManagedProfile()) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01003173 // Send broadcast to notify system that the user removed was a
3174 // managed user.
Amith Yamasani12747872015-12-07 14:19:49 -08003175 sendProfileRemovedBroadcast(userData.info.profileGroupId, userData.info.id);
Kenny Guyee58b4f2014-05-23 15:19:53 +01003176 }
3177
3178 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
3179 int res;
3180 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003181 res = ActivityManager.getService().stopUser(userHandle, /* force= */ true,
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07003182 new IStopUserCallback.Stub() {
Kenny Guyee58b4f2014-05-23 15:19:53 +01003183 @Override
3184 public void userStopped(int userId) {
3185 finishRemoveUser(userId);
3186 }
3187 @Override
3188 public void userStopAborted(int userId) {
3189 }
3190 });
3191 } catch (RemoteException e) {
jovanaka6763a32018-12-03 17:23:20 -08003192 Log.w(LOG_TAG, "Failed to stop user during removal.", e);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003193 return false;
3194 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01003195 return res == ActivityManager.USER_OP_SUCCESS;
3196 } finally {
3197 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003198 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003199 }
3200
Andreas Gampea36dc622018-02-05 17:19:22 -08003201 @GuardedBy("mUsersLock")
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003202 @VisibleForTesting
3203 void addRemovingUserIdLocked(int userId) {
3204 // We remember deleted user IDs to prevent them from being
3205 // reused during the current boot; they can still be reused
3206 // after a reboot or recycling of userIds.
3207 mRemovingUserIds.put(userId, true);
3208 mRecentlyRemovedIds.add(userId);
3209 // Keep LRU queue of recently removed IDs for recycling
3210 if (mRecentlyRemovedIds.size() > MAX_RECENTLY_REMOVED_IDS_SIZE) {
3211 mRecentlyRemovedIds.removeFirst();
3212 }
3213 }
3214
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07003215 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07003216 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07003217 // Let other services shutdown any activity and clean up their state before completely
3218 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07003219 long ident = Binder.clearCallingIdentity();
3220 try {
3221 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
3222 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07003223 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
3224 android.Manifest.permission.MANAGE_USERS,
3225
3226 new BroadcastReceiver() {
3227 @Override
3228 public void onReceive(Context context, Intent intent) {
3229 if (DBG) {
3230 Slog.i(LOG_TAG,
3231 "USER_REMOVED broadcast sent, cleaning up user data "
3232 + userHandle);
3233 }
3234 new Thread() {
Amith Yamasani12747872015-12-07 14:19:49 -08003235 @Override
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07003236 public void run() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003237 // Clean up any ActivityTaskManager state
3238 LocalServices.getService(ActivityTaskManagerInternal.class)
3239 .onUserStopped(userHandle);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003240 removeUserState(userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07003241 }
3242 }.start();
3243 }
3244 },
3245
3246 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07003247 } finally {
3248 Binder.restoreCallingIdentity(ident);
3249 }
Amith Yamasani2a003292012-08-14 18:25:45 -07003250 }
3251
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003252 private void removeUserState(final int userHandle) {
Paul Crowley91293792016-03-25 15:23:07 -07003253 try {
3254 mContext.getSystemService(StorageManager.class).destroyUserKey(userHandle);
3255 } catch (IllegalStateException e) {
3256 // This may be simply because the user was partially created.
3257 Slog.i(LOG_TAG,
3258 "Destroying key for user " + userHandle + " failed, continuing anyway", e);
3259 }
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06003260
Amith Yamasanid04aaa32016-06-13 12:09:36 -07003261 // Cleanup gatekeeper secure user id
3262 try {
3263 final IGateKeeperService gk = GateKeeper.getService();
3264 if (gk != null) {
3265 gk.clearSecureUserId(userHandle);
3266 }
3267 } catch (Exception ex) {
3268 Slog.w(LOG_TAG, "unable to clear GK secure user id");
3269 }
3270
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003271 // Cleanup package manager settings
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003272 mPm.cleanUpUser(this, userHandle);
Amith Yamasanid04aaa32016-06-13 12:09:36 -07003273
3274 // Clean up all data before removing metadata
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -08003275 mUserDataPreparer.destroyUserData(userHandle,
Amith Yamasanid04aaa32016-06-13 12:09:36 -07003276 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
3277
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003278 // Remove this user from the list
Fyodor Kupolov82402752015-10-28 14:54:51 -07003279 synchronized (mUsersLock) {
3280 mUsers.remove(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08003281 mIsUserManaged.delete(userHandle);
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003282 }
3283 synchronized (mUserStates) {
3284 mUserStates.delete(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08003285 }
3286 synchronized (mRestrictionsLock) {
3287 mBaseUserRestrictions.remove(userHandle);
3288 mAppliedUserRestrictions.remove(userHandle);
3289 mCachedEffectiveUserRestrictions.remove(userHandle);
3290 mDevicePolicyLocalUserRestrictions.remove(userHandle);
Pavel Grafov6a40f092016-10-25 15:46:51 +01003291 if (mDevicePolicyGlobalUserRestrictions.get(userHandle) != null) {
3292 mDevicePolicyGlobalUserRestrictions.remove(userHandle);
3293 applyUserRestrictionsForAllUsersLR();
3294 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07003295 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003296 // Update the user list
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003297 synchronized (mPackagesLock) {
3298 writeUserListLP();
3299 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06003300 // Remove user file
3301 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
3302 userFile.delete();
Fyodor Kupolov82402752015-10-28 14:54:51 -07003303 updateUserIds();
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003304 if (RELEASE_DELETED_USER_ID) {
3305 synchronized (mUsers) {
3306 mRemovingUserIds.delete(userHandle);
3307 }
3308 }
Amith Yamasani61f57372012-08-31 12:12:28 -07003309 }
3310
Kenny Guyf8d3a232014-05-15 16:09:52 +01003311 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01003312 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01003313 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
3314 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01003315 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
Jeff Sharkeyaf6ec292015-12-17 11:19:00 -07003316 managedProfileIntent.putExtra(Intent.EXTRA_USER_HANDLE, removedUserId);
Kenny Guyf8d3a232014-05-15 16:09:52 +01003317 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01003318 }
3319
Amith Yamasani2a003292012-08-14 18:25:45 -07003320 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07003321 public Bundle getApplicationRestrictions(String packageName) {
3322 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
3323 }
3324
3325 @Override
3326 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003327 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07003328 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07003329 checkSystemOrRoot("get application restrictions for other user/app " + packageName);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003330 }
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003331 synchronized (mAppRestrictionsLock) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003332 // Read the restrictions from XML
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003333 return readApplicationRestrictionsLAr(packageName, userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003334 }
3335 }
3336
3337 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07003338 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003339 int userId) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00003340 checkSystemOrRoot("set application restrictions");
Fyodor Kupolov0d88d542016-04-19 11:37:22 -07003341 if (restrictions != null) {
3342 restrictions.setDefusable(true);
3343 }
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003344 synchronized (mAppRestrictionsLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01003345 if (restrictions == null || restrictions.isEmpty()) {
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003346 cleanAppRestrictionsForPackageLAr(packageName, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01003347 } else {
3348 // Write the restrictions to XML
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003349 writeApplicationRestrictionsLAr(packageName, restrictions, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01003350 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003351 }
Robin Lee66e5d962014-04-09 16:44:21 +01003352
Fyodor Kupolovd2846122016-02-11 18:06:34 -08003353 // Notify package of changes via an intent - only sent to explicitly registered receivers.
3354 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
3355 changeIntent.setPackage(packageName);
3356 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3357 mContext.sendBroadcastAsUser(changeIntent, UserHandle.of(userId));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003358 }
3359
3360 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07003361 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003362 try {
3363 return mContext.getPackageManager().getApplicationInfo(packageName,
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07003364 PackageManager.MATCH_ANY_USER).uid;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003365 } catch (NameNotFoundException nnfe) {
3366 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07003367 } finally {
3368 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003369 }
3370 }
3371
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003372 @GuardedBy("mAppRestrictionsLock")
3373 private static Bundle readApplicationRestrictionsLAr(String packageName, int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003374 AtomicFile restrictionsFile =
3375 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
3376 packageToRestrictionsFileName(packageName)));
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003377 return readApplicationRestrictionsLAr(restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003378 }
3379
3380 @VisibleForTesting
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003381 @GuardedBy("mAppRestrictionsLock")
3382 static Bundle readApplicationRestrictionsLAr(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07003383 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003384 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07003385 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07003386 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07003387 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003388
3389 FileInputStream fis = null;
3390 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003391 fis = restrictionsFile.openRead();
3392 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01003393 parser.setInput(fis, StandardCharsets.UTF_8.name());
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003394 XmlUtils.nextElement(parser);
3395 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003396 Slog.e(LOG_TAG, "Unable to read restrictions file "
3397 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07003398 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003399 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003400 while (parser.next() != XmlPullParser.END_DOCUMENT) {
3401 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003402 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003403 } catch (IOException|XmlPullParserException e) {
3404 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003405 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003406 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003407 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07003408 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003409 }
3410
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003411 private static void readEntry(Bundle restrictions, ArrayList<String> values,
3412 XmlPullParser parser) throws XmlPullParserException, IOException {
3413 int type = parser.getEventType();
3414 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
3415 String key = parser.getAttributeValue(null, ATTR_KEY);
3416 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
3417 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
3418 if (multiple != null) {
3419 values.clear();
3420 int count = Integer.parseInt(multiple);
3421 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
3422 if (type == XmlPullParser.START_TAG
3423 && parser.getName().equals(TAG_VALUE)) {
3424 values.add(parser.nextText().trim());
3425 count--;
3426 }
3427 }
3428 String [] valueStrings = new String[values.size()];
3429 values.toArray(valueStrings);
3430 restrictions.putStringArray(key, valueStrings);
3431 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
3432 restrictions.putBundle(key, readBundleEntry(parser, values));
3433 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
3434 final int outerDepth = parser.getDepth();
3435 ArrayList<Bundle> bundleList = new ArrayList<>();
3436 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
3437 Bundle childBundle = readBundleEntry(parser, values);
3438 bundleList.add(childBundle);
3439 }
3440 restrictions.putParcelableArray(key,
3441 bundleList.toArray(new Bundle[bundleList.size()]));
3442 } else {
3443 String value = parser.nextText().trim();
3444 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
3445 restrictions.putBoolean(key, Boolean.parseBoolean(value));
3446 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
3447 restrictions.putInt(key, Integer.parseInt(value));
3448 } else {
3449 restrictions.putString(key, value);
3450 }
3451 }
3452 }
3453 }
3454
3455 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
3456 throws IOException, XmlPullParserException {
3457 Bundle childBundle = new Bundle();
3458 final int outerDepth = parser.getDepth();
3459 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
3460 readEntry(childBundle, values, parser);
3461 }
3462 return childBundle;
3463 }
3464
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003465 @GuardedBy("mAppRestrictionsLock")
3466 private static void writeApplicationRestrictionsLAr(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07003467 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003468 AtomicFile restrictionsFile = new AtomicFile(
3469 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07003470 packageToRestrictionsFileName(packageName)));
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003471 writeApplicationRestrictionsLAr(restrictions, restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003472 }
3473
3474 @VisibleForTesting
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003475 @GuardedBy("mAppRestrictionsLock")
3476 static void writeApplicationRestrictionsLAr(Bundle restrictions, AtomicFile restrictionsFile) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003477 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003478 try {
3479 fos = restrictionsFile.startWrite();
3480 final BufferedOutputStream bos = new BufferedOutputStream(fos);
3481
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003482 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01003483 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003484 serializer.startDocument(null, true);
3485 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
3486
3487 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003488 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003489 serializer.endTag(null, TAG_RESTRICTIONS);
3490
3491 serializer.endDocument();
3492 restrictionsFile.finishWrite(fos);
3493 } catch (Exception e) {
3494 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003495 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
3496 }
3497 }
3498
3499 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
3500 throws IOException {
3501 for (String key : restrictions.keySet()) {
3502 Object value = restrictions.get(key);
3503 serializer.startTag(null, TAG_ENTRY);
3504 serializer.attribute(null, ATTR_KEY, key);
3505
3506 if (value instanceof Boolean) {
3507 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
3508 serializer.text(value.toString());
3509 } else if (value instanceof Integer) {
3510 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
3511 serializer.text(value.toString());
3512 } else if (value == null || value instanceof String) {
3513 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
3514 serializer.text(value != null ? (String) value : "");
3515 } else if (value instanceof Bundle) {
3516 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
3517 writeBundle((Bundle) value, serializer);
3518 } else if (value instanceof Parcelable[]) {
3519 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
3520 Parcelable[] array = (Parcelable[]) value;
3521 for (Parcelable parcelable : array) {
3522 if (!(parcelable instanceof Bundle)) {
3523 throw new IllegalArgumentException("bundle-array can only hold Bundles");
3524 }
3525 serializer.startTag(null, TAG_ENTRY);
3526 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
3527 writeBundle((Bundle) parcelable, serializer);
3528 serializer.endTag(null, TAG_ENTRY);
3529 }
3530 } else {
3531 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
3532 String[] values = (String[]) value;
3533 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
3534 for (String choice : values) {
3535 serializer.startTag(null, TAG_VALUE);
3536 serializer.text(choice != null ? choice : "");
3537 serializer.endTag(null, TAG_VALUE);
3538 }
3539 }
3540 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003541 }
3542 }
3543
3544 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07003545 public int getUserSerialNumber(int userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003546 synchronized (mUsersLock) {
Pavel Grafov9c295d42019-03-26 19:42:08 +00003547 final UserInfo userInfo = getUserInfoLU(userHandle);
3548 return userInfo != null ? userInfo.serialNumber : -1;
Amith Yamasani2a003292012-08-14 18:25:45 -07003549 }
3550 }
3551
3552 @Override
Fyodor Kupolov605b12a2017-05-10 15:58:09 -07003553 public boolean isUserNameSet(int userHandle) {
3554 synchronized (mUsersLock) {
Pavel Grafov9c295d42019-03-26 19:42:08 +00003555 final UserInfo userInfo = getUserInfoLU(userHandle);
Fyodor Kupolov605b12a2017-05-10 15:58:09 -07003556 return userInfo != null && userInfo.name != null;
3557 }
3558 }
3559
3560 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07003561 public int getUserHandle(int userSerialNumber) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003562 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07003563 for (int userId : mUserIds) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003564 UserInfo info = getUserInfoLU(userId);
Kenny Guy945f8832015-02-10 15:17:26 +00003565 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07003566 }
3567 // Not found
3568 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07003569 }
3570 }
3571
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003572 @Override
3573 public long getUserCreationTime(int userHandle) {
3574 int callingUserId = UserHandle.getCallingUserId();
3575 UserInfo userInfo = null;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003576 synchronized (mUsersLock) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003577 if (callingUserId == userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003578 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003579 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003580 UserInfo parent = getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003581 if (parent != null && parent.id == callingUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003582 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003583 }
3584 }
3585 }
3586 if (userInfo == null) {
3587 throw new SecurityException("userHandle can only be the calling user or a managed "
3588 + "profile associated with this user");
3589 }
3590 return userInfo.creationTime;
3591 }
3592
Amith Yamasani0b285492011-04-14 17:35:23 -07003593 /**
3594 * Caches the list of user ids in an array, adjusting the array size when necessary.
3595 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07003596 private void updateUserIds() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003597 int num = 0;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003598 synchronized (mUsersLock) {
3599 final int userSize = mUsers.size();
3600 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003601 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003602 num++;
3603 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003604 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07003605 final int[] newUsers = new int[num];
3606 int n = 0;
3607 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003608 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003609 newUsers[n++] = mUsers.keyAt(i);
3610 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003611 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07003612 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07003613 }
3614 }
3615
3616 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003617 * Called right before a user is started. This gives us a chance to prepare
3618 * app storage and apply any user restrictions.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003619 */
3620 public void onBeforeStartUser(int userId) {
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003621 UserInfo userInfo = getUserInfo(userId);
3622 if (userInfo == null) {
3623 return;
3624 }
3625 final int userSerial = userInfo.serialNumber;
3626 // Migrate only if build fingerprints mismatch
3627 boolean migrateAppsData = !Build.FINGERPRINT.equals(userInfo.lastLoggedInFingerprint);
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -08003628 mUserDataPreparer.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_DE);
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003629 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_DE, migrateAppsData);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003630
3631 if (userId != UserHandle.USER_SYSTEM) {
3632 synchronized (mRestrictionsLock) {
3633 applyUserRestrictionsLR(userId);
3634 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003635 }
3636 }
3637
3638 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003639 * Called right before a user is unlocked. This gives us a chance to prepare
3640 * app storage.
3641 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003642 public void onBeforeUnlockUser(@UserIdInt int userId) {
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003643 UserInfo userInfo = getUserInfo(userId);
3644 if (userInfo == null) {
3645 return;
3646 }
3647 final int userSerial = userInfo.serialNumber;
3648 // Migrate only if build fingerprints mismatch
3649 boolean migrateAppsData = !Build.FINGERPRINT.equals(userInfo.lastLoggedInFingerprint);
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -08003650 mUserDataPreparer.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_CE);
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003651 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_CE, migrateAppsData);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003652 }
3653
3654 /**
Fyodor Kupolov50979d12017-01-27 17:36:32 -08003655 * Examine all users present on given mounted volume, and destroy data
3656 * belonging to users that are no longer valid, or whose user ID has been
3657 * recycled.
3658 */
3659 void reconcileUsers(String volumeUuid) {
3660 mUserDataPreparer.reconcileUsers(volumeUuid, getUsers(true /* excludeDying */));
3661 }
3662
3663 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07003664 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasanieb437d42016-04-29 09:31:25 -07003665 * This is called with ActivityManagerService lock held.
Amith Yamasani920ace02012-09-20 22:15:37 -07003666 * @param userId the user that was just foregrounded
3667 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003668 public void onUserLoggedIn(@UserIdInt int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -08003669 UserData userData = getUserDataNoChecks(userId);
3670 if (userData == null || userData.info.partial) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003671 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
3672 return;
3673 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003674
3675 final long now = System.currentTimeMillis();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003676 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani12747872015-12-07 14:19:49 -08003677 userData.info.lastLoggedInTime = now;
Amith Yamasani920ace02012-09-20 22:15:37 -07003678 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003679 userData.info.lastLoggedInFingerprint = Build.FINGERPRINT;
3680 scheduleWriteUser(userData);
Amith Yamasani920ace02012-09-20 22:15:37 -07003681 }
3682
3683 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07003684 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani0b285492011-04-14 17:35:23 -07003685 */
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003686 @VisibleForTesting
3687 int getNextAvailableId() {
3688 int nextId;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003689 synchronized (mUsersLock) {
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003690 nextId = scanNextAvailableIdLocked();
3691 if (nextId >= 0) {
3692 return nextId;
3693 }
3694 // All ids up to MAX_USER_ID were used. Remove all mRemovingUserIds,
3695 // except most recently removed
3696 if (mRemovingUserIds.size() > 0) {
3697 Slog.i(LOG_TAG, "All available IDs are used. Recycling LRU ids.");
3698 mRemovingUserIds.clear();
3699 for (Integer recentlyRemovedId : mRecentlyRemovedIds) {
3700 mRemovingUserIds.put(recentlyRemovedId, true);
Amith Yamasani195263742012-08-21 15:40:12 -07003701 }
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003702 nextId = scanNextAvailableIdLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003703 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003704 }
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003705 if (nextId < 0) {
3706 throw new IllegalStateException("No user id available!");
3707 }
3708 return nextId;
3709 }
3710
Andreas Gampea36dc622018-02-05 17:19:22 -08003711 @GuardedBy("mUsersLock")
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003712 private int scanNextAvailableIdLocked() {
3713 for (int i = MIN_USER_ID; i < MAX_USER_ID; i++) {
3714 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
3715 return i;
3716 }
3717 }
3718 return -1;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003719 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003720
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003721 private static String packageToRestrictionsFileName(String packageName) {
Amith Yamasanifc95e702013-09-26 13:20:17 -07003722 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
3723 }
3724
Amith Yamasani920ace02012-09-20 22:15:37 -07003725 @Override
Amith Yamasani12747872015-12-07 14:19:49 -08003726 public void setSeedAccountData(int userId, String accountName, String accountType,
3727 PersistableBundle accountOptions, boolean persist) {
3728 checkManageUsersPermission("Require MANAGE_USERS permission to set user seed data");
3729 synchronized (mPackagesLock) {
3730 final UserData userData;
3731 synchronized (mUsersLock) {
3732 userData = getUserDataLU(userId);
3733 if (userData == null) {
3734 Slog.e(LOG_TAG, "No such user for settings seed data u=" + userId);
3735 return;
3736 }
3737 userData.seedAccountName = accountName;
3738 userData.seedAccountType = accountType;
3739 userData.seedAccountOptions = accountOptions;
3740 userData.persistSeedData = persist;
3741 }
3742 if (persist) {
3743 writeUserLP(userData);
3744 }
3745 }
3746 }
3747
3748 @Override
3749 public String getSeedAccountName() throws RemoteException {
3750 checkManageUsersPermission("Cannot get seed account information");
3751 synchronized (mUsersLock) {
3752 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3753 return userData.seedAccountName;
3754 }
3755 }
3756
3757 @Override
3758 public String getSeedAccountType() throws RemoteException {
3759 checkManageUsersPermission("Cannot get seed account information");
3760 synchronized (mUsersLock) {
3761 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3762 return userData.seedAccountType;
3763 }
3764 }
3765
3766 @Override
3767 public PersistableBundle getSeedAccountOptions() throws RemoteException {
3768 checkManageUsersPermission("Cannot get seed account information");
3769 synchronized (mUsersLock) {
3770 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3771 return userData.seedAccountOptions;
3772 }
3773 }
3774
3775 @Override
3776 public void clearSeedAccountData() throws RemoteException {
3777 checkManageUsersPermission("Cannot clear seed account information");
3778 synchronized (mPackagesLock) {
3779 UserData userData;
3780 synchronized (mUsersLock) {
3781 userData = getUserDataLU(UserHandle.getCallingUserId());
3782 if (userData == null) return;
3783 userData.clearSeedAccountData();
3784 }
3785 writeUserLP(userData);
3786 }
3787 }
3788
3789 @Override
3790 public boolean someUserHasSeedAccount(String accountName, String accountType)
3791 throws RemoteException {
3792 checkManageUsersPermission("Cannot check seed account information");
3793 synchronized (mUsersLock) {
3794 final int userSize = mUsers.size();
3795 for (int i = 0; i < userSize; i++) {
3796 final UserData data = mUsers.valueAt(i);
3797 if (data.info.isInitialized()) continue;
3798 if (data.seedAccountName == null || !data.seedAccountName.equals(accountName)) {
3799 continue;
3800 }
3801 if (data.seedAccountType == null || !data.seedAccountType.equals(accountType)) {
3802 continue;
3803 }
3804 return true;
3805 }
3806 }
3807 return false;
3808 }
3809
3810 @Override
Todd Kennedy60459ab2015-10-30 11:32:16 -07003811 public void onShellCommand(FileDescriptor in, FileDescriptor out,
Dianne Hackborn354736e2016-08-22 17:00:05 -07003812 FileDescriptor err, String[] args, ShellCallback callback,
3813 ResultReceiver resultReceiver) {
3814 (new Shell()).exec(this, in, out, err, args, callback, resultReceiver);
Todd Kennedy60459ab2015-10-30 11:32:16 -07003815 }
3816
3817 int onShellCommand(Shell shell, String cmd) {
3818 if (cmd == null) {
3819 return shell.handleDefaultCommands(cmd);
3820 }
3821
3822 final PrintWriter pw = shell.getOutPrintWriter();
3823 try {
3824 switch(cmd) {
3825 case "list":
Felipe Leme7ad2f6b2019-09-11 09:23:26 -07003826 return runList(pw, shell);
Hui Yu8ba65972018-04-16 18:45:48 -07003827 default:
3828 return shell.handleDefaultCommands(cmd);
Todd Kennedy60459ab2015-10-30 11:32:16 -07003829 }
3830 } catch (RemoteException e) {
3831 pw.println("Remote exception: " + e);
3832 }
3833 return -1;
3834 }
3835
Felipe Leme7ad2f6b2019-09-11 09:23:26 -07003836 private int runList(PrintWriter pw, Shell shell) throws RemoteException {
3837 boolean all = false;
3838 boolean verbose = false;
3839 String opt;
3840 while ((opt = shell.getNextOption()) != null) {
3841 switch (opt) {
3842 case "-v":
3843 verbose = true;
3844 break;
3845 case "--all":
3846 all = true;
3847 break;
3848 default:
3849 pw.println("Invalid option: " + opt);
3850 return -1;
3851 }
3852 }
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003853 final IActivityManager am = ActivityManager.getService();
Felipe Leme7ad2f6b2019-09-11 09:23:26 -07003854 final List<UserInfo> users = getUsers(/* excludePartial= */ !all,
3855 /* excludingDying=*/ false, /* excludePreCreated= */ !all);
Todd Kennedy60459ab2015-10-30 11:32:16 -07003856 if (users == null) {
3857 pw.println("Error: couldn't get users");
3858 return 1;
3859 } else {
Felipe Leme7ad2f6b2019-09-11 09:23:26 -07003860 final int size = users.size();
3861 int currentUser = UserHandle.USER_NULL;
3862 if (verbose) {
3863 pw.printf("%d users:\n\n", size);
3864 currentUser = am.getCurrentUser().id;
3865 } else {
3866 // NOTE: the standard "list users" command is used by integration tests and
3867 // hence should not be changed. If you need to add more info, use the
3868 // verbose option.
3869 pw.println("Users:");
3870 }
3871 for (int i = 0; i < size; i++) {
3872 final UserInfo user = users.get(i);
3873 final boolean running = am.isUserRunning(user.id, 0);
3874 final boolean current = user.id == currentUser;
3875 if (verbose) {
3876 pw.printf("%d: id=%d, name=%s, flags=%s%s%s%s%s\n", i, user.id, user.name,
3877 UserInfo.flagsToString(user.flags),
3878 running ? " (running)" : "",
3879 user.partial ? " (partial)" : "",
3880 user.preCreated ? " (pre-created)" : "",
3881 current ? " (current)" : "");
3882 } else {
3883 // NOTE: the standard "list users" command is used by integration tests and
3884 // hence should not be changed. If you need to add more info, use the
3885 // verbose option.
3886 pw.printf("\t%s%s\n", user, running ? " running" : "");
3887 }
Todd Kennedy60459ab2015-10-30 11:32:16 -07003888 }
3889 return 0;
3890 }
3891 }
3892
3893 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -07003894 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06003895 if (!DumpUtils.checkDumpPermission(mContext, LOG_TAG, pw)) return;
Amith Yamasani920ace02012-09-20 22:15:37 -07003896
3897 long now = System.currentTimeMillis();
Makoto Onuki73dded22017-12-20 13:14:48 +09003898 final long nowRealtime = SystemClock.elapsedRealtime();
Felipe Leme3c5e8862019-06-12 17:40:53 -07003899
Felipe Leme5b8dc762019-10-04 16:23:16 -07003900 final ActivityManagerInternal amInternal = LocalServices
3901 .getService(ActivityManagerInternal.class);
3902 pw.print("Current user: ");
3903 if (amInternal != null) {
3904 pw.println(amInternal.getCurrentUserId());
3905 } else {
3906 pw.println("N/A");
3907 }
Felipe Leme3c5e8862019-06-12 17:40:53 -07003908
Amith Yamasani920ace02012-09-20 22:15:37 -07003909 StringBuilder sb = new StringBuilder();
3910 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003911 synchronized (mUsersLock) {
3912 pw.println("Users:");
3913 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003914 UserData userData = mUsers.valueAt(i);
3915 if (userData == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003916 continue;
3917 }
Amith Yamasani12747872015-12-07 14:19:49 -08003918 UserInfo userInfo = userData.info;
3919 final int userId = userInfo.id;
3920 pw.print(" "); pw.print(userInfo);
3921 pw.print(" serialNo="); pw.print(userInfo.serialNumber);
Felipe Leme3c5e8862019-06-12 17:40:53 -07003922 pw.print(" isPrimary="); pw.print(userInfo.isPrimary());
Makoto Onukie7927da2015-11-25 10:05:17 -08003923 if (mRemovingUserIds.get(userId)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003924 pw.print(" <removing> ");
3925 }
Amith Yamasani12747872015-12-07 14:19:49 -08003926 if (userInfo.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003927 pw.print(" <partial>");
3928 }
Felipe Leme7ad2f6b2019-09-11 09:23:26 -07003929 if (userInfo.preCreated) {
3930 pw.print(" <pre-created>");
3931 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07003932 pw.println();
Makoto Onuki88aef752017-03-29 16:52:03 -07003933 pw.print(" State: ");
3934 final int state;
3935 synchronized (mUserStates) {
3936 state = mUserStates.get(userId, -1);
3937 }
3938 pw.println(UserState.stateToString(state));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003939 pw.print(" Created: ");
Makoto Onuki73dded22017-12-20 13:14:48 +09003940 dumpTimeAgo(pw, sb, now, userInfo.creationTime);
3941
Fyodor Kupolov82402752015-10-28 14:54:51 -07003942 pw.print(" Last logged in: ");
Makoto Onuki73dded22017-12-20 13:14:48 +09003943 dumpTimeAgo(pw, sb, now, userInfo.lastLoggedInTime);
3944
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003945 pw.print(" Last logged in fingerprint: ");
3946 pw.println(userInfo.lastLoggedInFingerprint);
Makoto Onuki73dded22017-12-20 13:14:48 +09003947
3948 pw.print(" Start time: ");
3949 dumpTimeAgo(pw, sb, nowRealtime, userData.startRealtime);
3950
3951 pw.print(" Unlock time: ");
3952 dumpTimeAgo(pw, sb, nowRealtime, userData.unlockRealtime);
3953
Makoto Onukie7927da2015-11-25 10:05:17 -08003954 pw.print(" Has profile owner: ");
3955 pw.println(mIsUserManaged.get(userId));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003956 pw.println(" Restrictions:");
3957 synchronized (mRestrictionsLock) {
3958 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003959 pw, " ", mBaseUserRestrictions.get(userInfo.id));
Pavel Grafov6a40f092016-10-25 15:46:51 +01003960 pw.println(" Device policy global restrictions:");
3961 UserRestrictionsUtils.dumpRestrictions(
3962 pw, " ", mDevicePolicyGlobalUserRestrictions.get(userInfo.id));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003963 pw.println(" Device policy local restrictions:");
3964 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003965 pw, " ", mDevicePolicyLocalUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003966 pw.println(" Effective restrictions:");
3967 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003968 pw, " ", mCachedEffectiveUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003969 }
Amith Yamasani12747872015-12-07 14:19:49 -08003970
3971 if (userData.account != null) {
3972 pw.print(" Account name: " + userData.account);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08003973 pw.println();
3974 }
Amith Yamasani12747872015-12-07 14:19:49 -08003975
3976 if (userData.seedAccountName != null) {
3977 pw.print(" Seed account name: " + userData.seedAccountName);
3978 pw.println();
3979 if (userData.seedAccountType != null) {
3980 pw.print(" account type: " + userData.seedAccountType);
3981 pw.println();
3982 }
3983 if (userData.seedAccountOptions != null) {
3984 pw.print(" account options exist");
3985 pw.println();
3986 }
3987 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003988 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003989 }
Amith Yamasani12747872015-12-07 14:19:49 -08003990 pw.println();
Pavel Grafov6a40f092016-10-25 15:46:51 +01003991 pw.println(" Device owner id:" + mDeviceOwnerUserId);
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01003992 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003993 pw.println(" Guest restrictions:");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003994 synchronized (mGuestRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003995 UserRestrictionsUtils.dumpRestrictions(pw, " ", mGuestRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003996 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003997 synchronized (mUsersLock) {
3998 pw.println();
3999 pw.println(" Device managed: " + mIsDeviceManaged);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07004000 if (mRemovingUserIds.size() > 0) {
4001 pw.println();
4002 pw.println(" Recently removed userIds: " + mRecentlyRemovedIds);
4003 }
Makoto Onukie7927da2015-11-25 10:05:17 -08004004 }
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00004005 synchronized (mUserStates) {
4006 pw.println(" Started users state: " + mUserStates);
4007 }
Felipe Leme3c5e8862019-06-12 17:40:53 -07004008 } // synchronized (mPackagesLock)
4009
4010 // Dump some capabilities
4011 pw.println();
Felipe Leme7ad2f6b2019-09-11 09:23:26 -07004012 pw.print(" Max users: " + UserManager.getMaxSupportedUsers());
4013 pw.println(" (limit reached: " + isUserLimitReached() + ")");
Felipe Leme3c5e8862019-06-12 17:40:53 -07004014 pw.println(" Supports switchable users: " + UserManager.supportsMultipleUsers());
Felipe Leme7ad2f6b2019-09-11 09:23:26 -07004015 pw.println(" All guests ephemeral: " + areGuestUsersEphemeral());
Felipe Leme3c5e8862019-06-12 17:40:53 -07004016 pw.println(" Is split-system user: " + UserManager.isSplitSystemUser());
Felipe Leme7ad2f6b2019-09-11 09:23:26 -07004017 pw.println(" User version: " + mUserVersion);
Amith Yamasani920ace02012-09-20 22:15:37 -07004018 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08004019
Makoto Onuki73dded22017-12-20 13:14:48 +09004020 private static void dumpTimeAgo(PrintWriter pw, StringBuilder sb, long nowTime, long time) {
4021 if (time == 0) {
4022 pw.println("<unknown>");
4023 } else {
4024 sb.setLength(0);
4025 TimeUtils.formatDuration(nowTime - time, sb);
4026 sb.append(" ago");
4027 pw.println(sb);
4028 }
4029 }
4030
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08004031 final class MainHandler extends Handler {
4032
4033 @Override
4034 public void handleMessage(Message msg) {
4035 switch (msg.what) {
4036 case WRITE_USER_MSG:
4037 removeMessages(WRITE_USER_MSG, msg.obj);
4038 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08004039 int userId = ((UserData) msg.obj).info.id;
4040 UserData userData = getUserDataNoChecks(userId);
4041 if (userData != null) {
4042 writeUserLP(userData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08004043 }
4044 }
4045 }
4046 }
4047 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07004048
4049 /**
4050 * @param userId
4051 * @return whether the user has been initialized yet
4052 */
Todd Kennedy0eb97382017-10-03 16:57:22 -07004053 boolean isUserInitialized(int userId) {
4054 return mLocalService.isUserInitialized(userId);
Amith Yamasanibb054c92015-07-09 14:16:27 -07004055 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07004056
4057 private class LocalService extends UserManagerInternal {
Makoto Onuki068c54a2015-10-13 14:34:03 -07004058 @Override
Pavel Grafov6a40f092016-10-25 15:46:51 +01004059 public void setDevicePolicyUserRestrictions(int userId, @Nullable Bundle restrictions,
4060 boolean isDeviceOwner, int cameraRestrictionScope) {
4061 UserManagerService.this.setDevicePolicyUserRestrictionsInner(userId, restrictions,
4062 isDeviceOwner, cameraRestrictionScope);
Makoto Onuki068c54a2015-10-13 14:34:03 -07004063 }
4064
4065 @Override
4066 public Bundle getBaseUserRestrictions(int userId) {
4067 synchronized (mRestrictionsLock) {
4068 return mBaseUserRestrictions.get(userId);
4069 }
4070 }
4071
4072 @Override
4073 public void setBaseUserRestrictionsByDpmsForMigration(
4074 int userId, Bundle baseRestrictions) {
4075 synchronized (mRestrictionsLock) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01004076 if (updateRestrictionsIfNeededLR(
4077 userId, new Bundle(baseRestrictions), mBaseUserRestrictions)) {
4078 invalidateEffectiveUserRestrictionsLR(userId);
4079 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07004080 }
4081
Amith Yamasani12747872015-12-07 14:19:49 -08004082 final UserData userData = getUserDataNoChecks(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07004083 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08004084 if (userData != null) {
4085 writeUserLP(userData);
Makoto Onuki068c54a2015-10-13 14:34:03 -07004086 } else {
4087 Slog.w(LOG_TAG, "UserInfo not found for " + userId);
4088 }
4089 }
4090 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08004091
4092 @Override
4093 public boolean getUserRestriction(int userId, String key) {
4094 return getUserRestrictions(userId).getBoolean(key);
4095 }
4096
4097 @Override
4098 public void addUserRestrictionsListener(UserRestrictionsListener listener) {
4099 synchronized (mUserRestrictionsListeners) {
4100 mUserRestrictionsListeners.add(listener);
4101 }
4102 }
4103
4104 @Override
4105 public void removeUserRestrictionsListener(UserRestrictionsListener listener) {
4106 synchronized (mUserRestrictionsListeners) {
4107 mUserRestrictionsListeners.remove(listener);
4108 }
4109 }
Makoto Onukie7927da2015-11-25 10:05:17 -08004110
4111 @Override
4112 public void setDeviceManaged(boolean isManaged) {
4113 synchronized (mUsersLock) {
4114 mIsDeviceManaged = isManaged;
4115 }
4116 }
4117
4118 @Override
4119 public void setUserManaged(int userId, boolean isManaged) {
4120 synchronized (mUsersLock) {
4121 mIsUserManaged.put(userId, isManaged);
4122 }
4123 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01004124
4125 @Override
4126 public void setUserIcon(int userId, Bitmap bitmap) {
4127 long ident = Binder.clearCallingIdentity();
4128 try {
4129 synchronized (mPackagesLock) {
4130 UserData userData = getUserDataNoChecks(userId);
4131 if (userData == null || userData.info.partial) {
4132 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
4133 return;
4134 }
4135 writeBitmapLP(userData.info, bitmap);
4136 writeUserLP(userData);
4137 }
4138 sendUserInfoChangedBroadcast(userId);
4139 } finally {
4140 Binder.restoreCallingIdentity(ident);
4141 }
4142 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01004143
4144 @Override
4145 public void setForceEphemeralUsers(boolean forceEphemeralUsers) {
4146 synchronized (mUsersLock) {
4147 mForceEphemeralUsers = forceEphemeralUsers;
4148 }
4149 }
4150
4151 @Override
4152 public void removeAllUsers() {
4153 if (UserHandle.USER_SYSTEM == ActivityManager.getCurrentUser()) {
4154 // Remove the non-system users straight away.
4155 removeNonSystemUsers();
4156 } else {
4157 // Switch to the system user first and then remove the other users.
4158 BroadcastReceiver userSwitchedReceiver = new BroadcastReceiver() {
4159 @Override
4160 public void onReceive(Context context, Intent intent) {
4161 int userId =
4162 intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
4163 if (userId != UserHandle.USER_SYSTEM) {
4164 return;
4165 }
4166 mContext.unregisterReceiver(this);
4167 removeNonSystemUsers();
4168 }
4169 };
4170 IntentFilter userSwitchedFilter = new IntentFilter();
4171 userSwitchedFilter.addAction(Intent.ACTION_USER_SWITCHED);
4172 mContext.registerReceiver(
4173 userSwitchedReceiver, userSwitchedFilter, null, mHandler);
4174
4175 // Switch to the system user.
4176 ActivityManager am =
4177 (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
4178 am.switchUser(UserHandle.USER_SYSTEM);
4179 }
4180 }
phweisse9c44062016-02-10 12:57:38 +01004181
4182 @Override
Lenka Trochtova1ddda472016-02-12 10:42:12 +01004183 public void onEphemeralUserStop(int userId) {
4184 synchronized (mUsersLock) {
4185 UserInfo userInfo = getUserInfoLU(userId);
4186 if (userInfo != null && userInfo.isEphemeral()) {
4187 // Do not allow switching back to the ephemeral user again as the user is going
4188 // to be deleted.
4189 userInfo.flags |= UserInfo.FLAG_DISABLED;
4190 if (userInfo.isGuest()) {
4191 // Indicate that the guest will be deleted after it stops.
4192 userInfo.guestToRemove = true;
4193 }
4194 }
4195 }
4196 }
4197
4198 @Override
Alex Chaub6a9f942017-11-07 11:28:56 +08004199 public UserInfo createUserEvenWhenDisallowed(String name, int flags,
4200 String[] disallowedPackages) {
4201 UserInfo user = createUserInternalUnchecked(name, flags, UserHandle.USER_NULL,
Felipe Leme7ad2f6b2019-09-11 09:23:26 -07004202 /* preCreated= */ false, disallowedPackages);
phweisse9c44062016-02-10 12:57:38 +01004203 // Keep this in sync with UserManager.createUser
Christine Franks97a54802017-08-09 10:06:43 -07004204 if (user != null && !user.isAdmin() && !user.isDemo()) {
phweisse9c44062016-02-10 12:57:38 +01004205 setUserRestriction(UserManager.DISALLOW_SMS, true, user.id);
4206 setUserRestriction(UserManager.DISALLOW_OUTGOING_CALLS, true, user.id);
4207 }
4208 return user;
4209 }
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07004210
4211 @Override
Nicolas Prevotdf1b87d2016-10-25 13:57:08 +01004212 public boolean removeUserEvenWhenDisallowed(int userId) {
4213 return removeUserUnchecked(userId);
4214 }
4215
4216 @Override
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00004217 public boolean isUserRunning(int userId) {
4218 synchronized (mUserStates) {
4219 return mUserStates.get(userId, -1) >= 0;
4220 }
4221 }
4222
4223 @Override
4224 public void setUserState(int userId, int userState) {
4225 synchronized (mUserStates) {
4226 mUserStates.put(userId, userState);
4227 }
4228 }
4229
4230 @Override
4231 public void removeUserState(int userId) {
4232 synchronized (mUserStates) {
4233 mUserStates.delete(userId);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07004234 }
4235 }
4236
4237 @Override
Michael Wachenschwanz3f2b6552017-05-15 13:53:09 -07004238 public int[] getUserIds() {
4239 return UserManagerService.this.getUserIds();
4240 }
4241
4242 @Override
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07004243 public boolean isUserUnlockingOrUnlocked(int userId) {
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07004244 int state;
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00004245 synchronized (mUserStates) {
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07004246 state = mUserStates.get(userId, -1);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07004247 }
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07004248 // Special case, in the stopping/shutdown state user key can still be unlocked
4249 if (state == UserState.STATE_STOPPING || state == UserState.STATE_SHUTDOWN) {
4250 return StorageManager.isUserKeyUnlocked(userId);
4251 }
4252 return (state == UserState.STATE_RUNNING_UNLOCKING)
4253 || (state == UserState.STATE_RUNNING_UNLOCKED);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07004254 }
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08004255
4256 @Override
4257 public boolean isUserUnlocked(int userId) {
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07004258 int state;
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08004259 synchronized (mUserStates) {
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07004260 state = mUserStates.get(userId, -1);
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08004261 }
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07004262 // Special case, in the stopping/shutdown state user key can still be unlocked
4263 if (state == UserState.STATE_STOPPING || state == UserState.STATE_SHUTDOWN) {
4264 return StorageManager.isUserKeyUnlocked(userId);
4265 }
4266 return state == UserState.STATE_RUNNING_UNLOCKED;
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08004267 }
Todd Kennedy0eb97382017-10-03 16:57:22 -07004268
4269 @Override
4270 public boolean isUserInitialized(int userId) {
4271 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
4272 }
4273
4274 @Override
4275 public boolean exists(int userId) {
4276 return getUserInfoNoChecks(userId) != null;
4277 }
Sunny Goyal145c8f82018-02-15 14:27:09 -08004278
4279 @Override
4280 public boolean isProfileAccessible(int callingUserId, int targetUserId, String debugMsg,
4281 boolean throwSecurityException) {
4282 if (targetUserId == callingUserId) {
4283 return true;
4284 }
4285 synchronized (mUsersLock) {
4286 UserInfo callingUserInfo = getUserInfoLU(callingUserId);
4287 if (callingUserInfo == null || callingUserInfo.isManagedProfile()) {
4288 if (throwSecurityException) {
4289 throw new SecurityException(
4290 debugMsg + " for another profile "
4291 + targetUserId + " from " + callingUserId);
4292 }
4293 }
4294
4295 UserInfo targetUserInfo = getUserInfoLU(targetUserId);
4296 if (targetUserInfo == null || !targetUserInfo.isEnabled()) {
4297 // Do not throw any exception here as this could happen due to race conditions
4298 // between the system updating its state and the client getting notified.
4299 if (throwSecurityException) {
4300 Slog.w(LOG_TAG, debugMsg + " for disabled profile "
4301 + targetUserId + " from " + callingUserId);
4302 }
4303 return false;
4304 }
4305
4306 if (targetUserInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID ||
4307 targetUserInfo.profileGroupId != callingUserInfo.profileGroupId) {
4308 if (throwSecurityException) {
4309 throw new SecurityException(
4310 debugMsg + " for unrelated profile " + targetUserId);
4311 }
4312 return false;
4313 }
4314 }
4315 return true;
4316 }
4317
4318 @Override
4319 public int getProfileParentId(int userId) {
4320 synchronized (mUsersLock) {
4321 UserInfo profileParent = getProfileParentLU(userId);
4322 if (profileParent == null) {
4323 return userId;
4324 }
4325 return profileParent.id;
4326 }
4327 }
yuemingw1d13eae2018-01-30 17:27:54 +00004328
4329 @Override
4330 public boolean isSettingRestrictedForUser(String setting, @UserIdInt int userId,
4331 String value, int callingUid) {
4332 return UserRestrictionsUtils.isSettingRestrictedForUser(mContext, setting, userId,
4333 value, callingUid);
4334 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01004335 }
4336
4337 /* Remove all the users except of the system one. */
4338 private void removeNonSystemUsers() {
4339 ArrayList<UserInfo> usersToRemove = new ArrayList<>();
4340 synchronized (mUsersLock) {
4341 final int userSize = mUsers.size();
4342 for (int i = 0; i < userSize; i++) {
4343 UserInfo ui = mUsers.valueAt(i).info;
4344 if (ui.id != UserHandle.USER_SYSTEM) {
4345 usersToRemove.add(ui);
4346 }
4347 }
4348 }
4349 for (UserInfo ui: usersToRemove) {
4350 removeUser(ui.id);
4351 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07004352 }
Todd Kennedy60459ab2015-10-30 11:32:16 -07004353
4354 private class Shell extends ShellCommand {
4355 @Override
4356 public int onCommand(String cmd) {
4357 return onShellCommand(this, cmd);
4358 }
4359
4360 @Override
4361 public void onHelp() {
4362 final PrintWriter pw = getOutPrintWriter();
4363 pw.println("User manager (user) commands:");
4364 pw.println(" help");
4365 pw.println(" Print this help text.");
4366 pw.println("");
Felipe Leme7ad2f6b2019-09-11 09:23:26 -07004367 pw.println(" list [-v] [-all]");
Todd Kennedy60459ab2015-10-30 11:32:16 -07004368 pw.println(" Prints all users on the system.");
4369 }
4370 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08004371
4372 private static void debug(String message) {
4373 Log.d(LOG_TAG, message +
4374 (DBG_WITH_STACKTRACE ? " called at\n" + Debug.getCallers(10, " ") : ""));
4375 }
Kenny Guy02c89902016-11-15 19:36:38 +00004376
4377 @VisibleForTesting
4378 static int getMaxManagedProfiles() {
4379 // Allow overriding max managed profiles on debuggable builds for testing
4380 // of multiple profiles.
4381 if (!Build.IS_DEBUGGABLE) {
4382 return MAX_MANAGED_PROFILES;
4383 } else {
4384 return SystemProperties.getInt("persist.sys.max_profiles",
4385 MAX_MANAGED_PROFILES);
4386 }
4387 }
4388
Andreas Gampe2e8c7672018-07-20 13:01:08 -07004389 @GuardedBy("mUsersLock")
Kenny Guy02c89902016-11-15 19:36:38 +00004390 @VisibleForTesting
4391 int getFreeProfileBadgeLU(int parentUserId) {
4392 int maxManagedProfiles = getMaxManagedProfiles();
4393 boolean[] usedBadges = new boolean[maxManagedProfiles];
4394 final int userSize = mUsers.size();
4395 for (int i = 0; i < userSize; i++) {
4396 UserInfo ui = mUsers.valueAt(i).info;
4397 // Check which badge indexes are already used by this profile group.
4398 if (ui.isManagedProfile()
4399 && ui.profileGroupId == parentUserId
4400 && !mRemovingUserIds.get(ui.id)
4401 && ui.profileBadge < maxManagedProfiles) {
4402 usedBadges[ui.profileBadge] = true;
4403 }
4404 }
4405 for (int i = 0; i < maxManagedProfiles; i++) {
4406 if (!usedBadges[i]) {
4407 return i;
4408 }
4409 }
4410 return 0;
4411 }
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07004412
4413 /**
4414 * Checks if the given user has a managed profile associated with it.
4415 * @param userId The parent user
4416 * @return
4417 */
4418 boolean hasManagedProfile(int userId) {
4419 synchronized (mUsersLock) {
4420 UserInfo userInfo = getUserInfoLU(userId);
4421 final int userSize = mUsers.size();
4422 for (int i = 0; i < userSize; i++) {
4423 UserInfo profile = mUsers.valueAt(i).info;
4424 if (userId != profile.id && isProfileOf(userInfo, profile)) {
4425 return true;
4426 }
4427 }
4428 return false;
4429 }
4430 }
Tony Makd390ae92017-12-28 13:23:10 +00004431
4432 /**
4433 * Check if the calling package name matches with the calling UID, throw
4434 * {@link SecurityException} if not.
4435 */
4436 private void verifyCallingPackage(String callingPackage, int callingUid) {
4437 int packageUid = mPm.getPackageUid(callingPackage, 0, UserHandle.getUserId(callingUid));
4438 if (packageUid != callingUid) {
4439 throw new SecurityException("Specified package " + callingPackage
4440 + " does not match the calling uid " + callingUid);
4441 }
4442 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07004443}