blob: ed60aa54212f4baa5ceb13d805deddc5b0ff0ddc [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
653 @Override
Xiaohui Chen594f2082015-08-18 11:04:20 -0700654 public @NonNull List<UserInfo> getUsers(boolean excludeDying) {
Felipe Leme7ad2f6b2019-09-11 09:23:26 -0700655 return getUsers(/*excludePartial= */ true, excludeDying, /* excludePreCreated= */ true);
656 }
657
658 private @NonNull List<UserInfo> getUsers(boolean excludePartial, boolean excludeDying,
659 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
2703 return createUserInternalUnchecked(/* name= */ null, flags,
2704 /* parentId= */ UserHandle.USER_NULL, /* preCreate= */ true,
2705 /* disallowedPackages= */ null);
2706 }
2707
2708 private UserInfo createUserInternal(@Nullable String name, @UserInfoFlag int flags,
2709 @UserIdInt int parentId) {
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002710 return createUserInternal(name, flags, parentId, null);
2711 }
2712
Felipe Leme7ad2f6b2019-09-11 09:23:26 -07002713 private UserInfo createUserInternal(@Nullable String name, @UserInfoFlag int flags,
2714 @UserIdInt int parentId, @Nullable String[] disallowedPackages) {
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002715 String restriction = ((flags & UserInfo.FLAG_MANAGED_PROFILE) != 0)
2716 ? UserManager.DISALLOW_ADD_MANAGED_PROFILE
2717 : UserManager.DISALLOW_ADD_USER;
2718 if (hasUserRestriction(restriction, UserHandle.getCallingUserId())) {
2719 Log.w(LOG_TAG, "Cannot add user. " + restriction + " is enabled.");
Julia Reynolds75175022014-06-26 16:35:00 -04002720 return null;
2721 }
Felipe Leme7ad2f6b2019-09-11 09:23:26 -07002722 return createUserInternalUnchecked(name, flags, parentId, /* preCreate= */ false,
2723 disallowedPackages);
Tony Mak6dc428f2016-10-10 15:48:27 +01002724 }
2725
Felipe Leme7ad2f6b2019-09-11 09:23:26 -07002726 private UserInfo createUserInternalUnchecked(@Nullable String name, @UserInfoFlag int flags,
2727 @UserIdInt int parentId, boolean preCreate,
2728 @Nullable String[] disallowedPackages) {
2729 final TimingsTraceLog t = new TimingsTraceLog(LOG_TAG, Trace.TRACE_TAG_SYSTEM_SERVER);
2730 t.traceBegin("createUser-" + flags);
2731 try {
2732 return createUserInternalUncheckedNoTracing(name, flags, parentId, preCreate,
2733 disallowedPackages, t);
2734 } finally {
2735 t.traceEnd();
2736 }
2737 }
2738
2739 private UserInfo createUserInternalUncheckedNoTracing(@Nullable String name,
2740 @UserInfoFlag int flags, @UserIdInt int parentId, boolean preCreate,
2741 @Nullable String[] disallowedPackages, @NonNull TimingsTraceLog t) {
2742
2743 // First try to use a pre-created user (if available).
2744 // NOTE: currently we don't support pre-created managed profiles
2745 if (!preCreate && (parentId < 0 && !UserInfo.isManagedProfile(flags))) {
2746 final UserData preCreatedUserData;
2747 synchronized (mUsersLock) {
2748 preCreatedUserData = getPreCreatedUserLU(flags);
2749 }
2750 if (preCreatedUserData != null) {
2751 final UserInfo preCreatedUser = preCreatedUserData.info;
2752 Log.i(LOG_TAG, "Reusing pre-created user " + preCreatedUser.id + " for flags + "
2753 + UserInfo.flagsToString(flags));
2754 if (DBG) {
2755 Log.d(LOG_TAG, "pre-created user flags: "
2756 + UserInfo.flagsToString(preCreatedUser.flags)
2757 + " new-user flags: " + UserInfo.flagsToString(flags));
2758 }
2759 preCreatedUser.name = name;
2760 preCreatedUser.preCreated = false;
2761 preCreatedUser.creationTime = getCreationTime();
2762
2763 dispatchUserAddedIntent(preCreatedUser);
2764
2765 writeUserLP(preCreatedUserData);
2766 writeUserListLP();
2767
2768 return preCreatedUser;
2769 }
2770 }
2771
Suprabh Shuklac5e057c2016-08-08 16:22:44 -07002772 DeviceStorageMonitorInternal dsm = LocalServices
2773 .getService(DeviceStorageMonitorInternal.class);
2774 if (dsm.isMemoryLow()) {
2775 Log.w(LOG_TAG, "Cannot add user. Not enough space on disk.");
2776 return null;
2777 }
Felipe Leme7ad2f6b2019-09-11 09:23:26 -07002778 final boolean isGuest = UserInfo.isGuest(flags);
2779 final boolean isManagedProfile = UserInfo.isManagedProfile(flags);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002780 final boolean isRestricted = (flags & UserInfo.FLAG_RESTRICTED) != 0;
Amith Yamasani52c21e32016-05-31 09:12:20 -07002781 final boolean isDemo = (flags & UserInfo.FLAG_DEMO) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002782 final long ident = Binder.clearCallingIdentity();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002783 UserInfo userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08002784 UserData userData;
Amith Yamasanibb054c92015-07-09 14:16:27 -07002785 final int userId;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002786 try {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002787 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002788 UserData parent = null;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002789 if (parentId != UserHandle.USER_NULL) {
2790 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002791 parent = getUserDataLU(parentId);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00002792 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002793 if (parent == null) return null;
2794 }
2795 if (isManagedProfile && !canAddMoreManagedProfiles(parentId, false)) {
2796 Log.e(LOG_TAG, "Cannot add more managed profiles for user " + parentId);
2797 return null;
2798 }
Amith Yamasani52c21e32016-05-31 09:12:20 -07002799 if (!isGuest && !isManagedProfile && !isDemo && isUserLimitReached()) {
Felipe Leme7ad2f6b2019-09-11 09:23:26 -07002800 // If we're not adding a guest/demo user or a managed profile,
2801 // and the limit has been reached, cannot add a user.
jovanaka6763a32018-12-03 17:23:20 -08002802 Log.e(LOG_TAG, "Cannot add user. Maximum user limit is reached.");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002803 return null;
2804 }
2805 // If we're adding a guest and there already exists one, bail.
2806 if (isGuest && findCurrentGuestUser() != null) {
jovanaka6763a32018-12-03 17:23:20 -08002807 Log.e(LOG_TAG, "Cannot add guest user. Guest user already exists.");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002808 return null;
2809 }
2810 // In legacy mode, restricted profile's parent can only be the owner user
2811 if (isRestricted && !UserManager.isSplitSystemUser()
2812 && (parentId != UserHandle.USER_SYSTEM)) {
2813 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
2814 return null;
2815 }
2816 if (isRestricted && UserManager.isSplitSystemUser()) {
2817 if (parent == null) {
2818 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be "
2819 + "specified");
Nicolas Prevot12678a92015-05-13 12:15:03 -07002820 return null;
2821 }
Amith Yamasani12747872015-12-07 14:19:49 -08002822 if (!parent.info.canHaveProfile()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002823 Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be "
2824 + "created for the specified parent user id " + parentId);
Amith Yamasani95ab7842014-08-11 17:09:26 -07002825 return null;
2826 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002827 }
2828 // In split system user mode, we assign the first human user the primary flag.
2829 // And if there is no device owner, we also assign the admin flag to primary user.
2830 if (UserManager.isSplitSystemUser()
2831 && !isGuest && !isManagedProfile && getPrimaryUser() == null) {
2832 flags |= UserInfo.FLAG_PRIMARY;
Makoto Onukie7927da2015-11-25 10:05:17 -08002833 synchronized (mUsersLock) {
2834 if (!mIsDeviceManaged) {
2835 flags |= UserInfo.FLAG_ADMIN;
2836 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07002837 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002838 }
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002839
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002840 userId = getNextAvailableId();
2841 Environment.getUserSystemDirectory(userId).mkdirs();
Felipe Leme7ad2f6b2019-09-11 09:23:26 -07002842 boolean ephemeralGuests = areGuestUsersEphemeral();
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002843
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002844 synchronized (mUsersLock) {
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002845 // Add ephemeral flag to guests/users if required. Also inherit it from parent.
2846 if ((isGuest && ephemeralGuests) || mForceEphemeralUsers
2847 || (parent != null && parent.info.isEphemeral())) {
2848 flags |= UserInfo.FLAG_EPHEMERAL;
2849 }
2850
2851 userInfo = new UserInfo(userId, name, null, flags);
2852 userInfo.serialNumber = mNextSerialNumber++;
Felipe Leme7ad2f6b2019-09-11 09:23:26 -07002853 userInfo.creationTime = getCreationTime();
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002854 userInfo.partial = true;
Felipe Leme7ad2f6b2019-09-11 09:23:26 -07002855 userInfo.preCreated = preCreate;
Fyodor Kupolov83c24242016-03-31 13:30:42 -07002856 userInfo.lastLoggedInFingerprint = Build.FINGERPRINT;
Kenny Guy02c89902016-11-15 19:36:38 +00002857 if (isManagedProfile && parentId != UserHandle.USER_NULL) {
2858 userInfo.profileBadge = getFreeProfileBadgeLU(parentId);
2859 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002860 userData = new UserData();
2861 userData.info = userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08002862 mUsers.put(userId, userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002863 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06002864 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002865 writeUserListLP();
2866 if (parent != null) {
2867 if (isManagedProfile) {
Amith Yamasani12747872015-12-07 14:19:49 -08002868 if (parent.info.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
2869 parent.info.profileGroupId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002870 writeUserLP(parent);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002871 }
Amith Yamasani12747872015-12-07 14:19:49 -08002872 userInfo.profileGroupId = parent.info.profileGroupId;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002873 } else if (isRestricted) {
Amith Yamasani12747872015-12-07 14:19:49 -08002874 if (parent.info.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) {
2875 parent.info.restrictedProfileParentId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002876 writeUserLP(parent);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002877 }
Amith Yamasani12747872015-12-07 14:19:49 -08002878 userInfo.restrictedProfileParentId = parent.info.restrictedProfileParentId;
Makoto Onuki068c54a2015-10-13 14:34:03 -07002879 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002880 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07002881 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002882 final StorageManager storage = mContext.getSystemService(StorageManager.class);
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002883 storage.createUserKey(userId, userInfo.serialNumber, userInfo.isEphemeral());
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -08002884 mUserDataPreparer.prepareUserData(userId, userInfo.serialNumber,
Jeff Sharkey47f71082016-02-01 17:03:54 -07002885 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002886 mPm.createNewUser(userId, disallowedPackages);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002887 userInfo.partial = false;
2888 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002889 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002890 }
2891 updateUserIds();
2892 Bundle restrictions = new Bundle();
Fyodor Kupolove04462c2015-11-30 15:02:53 -08002893 if (isGuest) {
2894 synchronized (mGuestRestrictions) {
2895 restrictions.putAll(mGuestRestrictions);
2896 }
2897 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002898 synchronized (mRestrictionsLock) {
2899 mBaseUserRestrictions.append(userId, restrictions);
2900 }
Fyodor Kupolov5fd967d2016-07-12 14:46:19 -07002901 mPm.onNewUserCreated(userId);
Felipe Leme7ad2f6b2019-09-11 09:23:26 -07002902 if (preCreate) {
2903 // Must start user (which will be stopped right away, through
2904 // UserController.finishUserUnlockedCompleted) so services can properly
2905 // intialize it.
2906 // TODO(b/140750212): in the long-term, we should add a onCreateUser() callback
2907 // on SystemService instead.
2908 Slog.i(LOG_TAG, "starting pre-created user " + userInfo.toFullString());
2909 final IActivityManager am = ActivityManager.getService();
2910 try {
2911 am.startUserInBackground(userId);
2912 } catch (RemoteException e) {
2913 Slog.w(LOG_TAG, "could not start pre-created user " + userId, e);
2914 }
2915 } else {
2916 dispatchUserAddedIntent(userInfo);
2917 }
2918
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002919 } finally {
2920 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07002921 }
Felipe Leme7ad2f6b2019-09-11 09:23:26 -07002922
2923 // TODO(b/140750212): it's possible to reach "max users overflow" when the user is created
2924 // "from scratch" (i.e., not from a pre-created user) and reaches the maximum number of
2925 // users without counting the pre-created one. Then when the pre-created is converted, the
2926 // "effective" number of max users is exceeds. Example:
2927 // Max: 3 Current: 2 full (u0 and u10) + 1 pre-created (u11)
2928 // Step 1: create(/* flags doesn't match u11 */): u12 is created, "effective max" is now 3
2929 // (u0, u10, u12) but "real" max is 4 (u0, u10, u11, u12)
2930 // Step 2: create(/* flags match u11 */): u11 is converted, now "effective max" is also 4
2931 // (u0, u10, u11, u12)
2932 // One way to avoid this issue is by removing a pre-created user from the pool when the
2933 // "real" max exceeds the max here.
2934
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002935 return userInfo;
2936 }
2937
Felipe Leme7ad2f6b2019-09-11 09:23:26 -07002938 private long getCreationTime() {
2939 final long now = System.currentTimeMillis();
2940 return (now > EPOCH_PLUS_30_YEARS) ? now : 0;
2941 }
2942
2943 private void dispatchUserAddedIntent(@NonNull UserInfo userInfo) {
2944 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
2945 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userInfo.id);
2946 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
2947 android.Manifest.permission.MANAGE_USERS);
2948 MetricsLogger.count(mContext, userInfo.isGuest() ? TRON_GUEST_CREATED
2949 : (userInfo.isDemo() ? TRON_DEMO_CREATED : TRON_USER_CREATED), 1);
2950 }
2951
2952 private boolean areGuestUsersEphemeral() {
2953 return Resources.getSystem()
2954 .getBoolean(com.android.internal.R.bool.config_guestUserEphemeral);
2955 }
2956
2957 /**
2958 * Gets a pre-created user for the given flag.
2959 *
2960 * <p>Should be used only during user creation, so the pre-created user can be used (instead of
2961 * creating and initializing a new user from scratch).
2962 */
2963 // TODO(b/140750212): add unit test
2964 @GuardedBy("mUsersLock")
2965 private @Nullable UserData getPreCreatedUserLU(@UserInfoFlag int flags) {
2966 if (DBG) {
2967 Slog.d(LOG_TAG, "getPreCreatedUser(): initialFlags= " + UserInfo.flagsToString(flags));
2968 }
2969 if (UserInfo.isGuest(flags) && areGuestUsersEphemeral()) {
2970 flags |= UserInfo.FLAG_EPHEMERAL;
2971 }
2972 if (DBG) {
2973 Slog.d(LOG_TAG, "getPreCreatedUser(): targetFlags= " + UserInfo.flagsToString(flags));
2974 }
2975 final int userSize = mUsers.size();
2976 for (int i = 0; i < userSize; i++) {
2977 final UserData user = mUsers.valueAt(i);
2978 if (DBG) Slog.d(LOG_TAG, i + ":" + user.info.toFullString());
2979 if (user.info.preCreated
2980 && (user.info.flags & ~UserInfo.FLAG_INITIALIZED) == flags) {
2981 if (!user.info.isInitialized()) {
2982 Slog.w(LOG_TAG, "found pre-created user for flags "
2983 + "" + UserInfo.flagsToString(flags)
2984 + ", but it's not initialized yet: " + user.info.toFullString());
2985 continue;
2986 }
2987 return user;
2988 }
2989 }
2990 return null;
2991 }
2992
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002993 @VisibleForTesting
2994 UserData putUserInfo(UserInfo userInfo) {
2995 final UserData userData = new UserData();
2996 userData.info = userInfo;
2997 synchronized (mUsers) {
2998 mUsers.put(userInfo.id, userData);
2999 }
3000 return userData;
3001 }
3002
3003 @VisibleForTesting
3004 void removeUserInfo(int userId) {
3005 synchronized (mUsers) {
3006 mUsers.remove(userId);
3007 }
3008 }
3009
Amith Yamasani0b285492011-04-14 17:35:23 -07003010 /**
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003011 * @hide
3012 */
Amith Yamasani12747872015-12-07 14:19:49 -08003013 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003014 public UserInfo createRestrictedProfile(String name, int parentUserId) {
Sudheer Shanka53d41472016-06-16 09:11:08 -07003015 checkManageOrCreateUsersPermission("setupRestrictedProfile");
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07003016 final UserInfo user = createProfileForUser(
3017 name, UserInfo.FLAG_RESTRICTED, parentUserId, null);
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003018 if (user == null) {
3019 return null;
3020 }
Fyodor Kupolov9e912ba2016-02-09 18:29:43 -08003021 long identity = Binder.clearCallingIdentity();
3022 try {
3023 setUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, true, user.id);
3024 // Change the setting before applying the DISALLOW_SHARE_LOCATION restriction, otherwise
3025 // the putIntForUser() will fail.
3026 android.provider.Settings.Secure.putIntForUser(mContext.getContentResolver(),
3027 android.provider.Settings.Secure.LOCATION_MODE,
3028 android.provider.Settings.Secure.LOCATION_MODE_OFF, user.id);
3029 setUserRestriction(UserManager.DISALLOW_SHARE_LOCATION, true, user.id);
3030 } finally {
3031 Binder.restoreCallingIdentity(identity);
3032 }
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003033 return user;
3034 }
3035
3036 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07003037 * Find the current guest user. If the Guest user is partial,
3038 * then do not include it in the results as it is about to die.
Adam Lesinskieddeb492014-09-08 17:50:03 -07003039 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07003040 private UserInfo findCurrentGuestUser() {
3041 synchronized (mUsersLock) {
3042 final int size = mUsers.size();
3043 for (int i = 0; i < size; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003044 final UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003045 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
3046 return user;
3047 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07003048 }
3049 }
3050 return null;
3051 }
3052
3053 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07003054 * Mark this guest user for deletion to allow us to create another guest
3055 * and switch to that user before actually removing this guest.
3056 * @param userHandle the userid of the current guest
3057 * @return whether the user could be marked for deletion
3058 */
Amith Yamasani12747872015-12-07 14:19:49 -08003059 @Override
Amith Yamasani1df14732014-08-29 21:37:27 -07003060 public boolean markGuestForDeletion(int userHandle) {
3061 checkManageUsersPermission("Only the system can remove users");
3062 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
3063 UserManager.DISALLOW_REMOVE_USER, false)) {
3064 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
3065 return false;
3066 }
3067
3068 long ident = Binder.clearCallingIdentity();
3069 try {
Amith Yamasani12747872015-12-07 14:19:49 -08003070 final UserData userData;
Amith Yamasani1df14732014-08-29 21:37:27 -07003071 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003072 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08003073 userData = mUsers.get(userHandle);
3074 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003075 return false;
3076 }
Amith Yamasani1df14732014-08-29 21:37:27 -07003077 }
Amith Yamasani12747872015-12-07 14:19:49 -08003078 if (!userData.info.isGuest()) {
Amith Yamasani1df14732014-08-29 21:37:27 -07003079 return false;
3080 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07003081 // We set this to a guest user that is to be removed. This is a temporary state
3082 // where we are allowed to add new Guest users, even if this one is still not
3083 // removed. This user will still show up in getUserInfo() calls.
3084 // If we don't get around to removing this Guest user, it will be purged on next
3085 // startup.
Amith Yamasani12747872015-12-07 14:19:49 -08003086 userData.info.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07003087 // Mark it as disabled, so that it isn't returned any more when
3088 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08003089 userData.info.flags |= UserInfo.FLAG_DISABLED;
3090 writeUserLP(userData);
Amith Yamasani1df14732014-08-29 21:37:27 -07003091 }
3092 } finally {
3093 Binder.restoreCallingIdentity(ident);
3094 }
3095 return true;
3096 }
3097
3098 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07003099 * Removes a user and all data directories created for that user. This method should be called
3100 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07003101 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07003102 */
Amith Yamasani12747872015-12-07 14:19:49 -08003103 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -07003104 public boolean removeUser(int userHandle) {
Fyodor Kupolov4593e422016-10-27 11:00:29 -07003105 Slog.i(LOG_TAG, "removeUser u" + userHandle);
Sudheer Shankaf5cea032016-06-08 17:13:24 -07003106 checkManageOrCreateUsersPermission("Only the system can remove users");
Esteban Talavera6c9116a2016-11-24 16:12:44 +00003107
3108 final boolean isManagedProfile;
3109 synchronized (mUsersLock) {
3110 UserInfo userInfo = getUserInfoLU(userHandle);
3111 isManagedProfile = userInfo != null && userInfo.isManagedProfile();
3112 }
3113 String restriction = isManagedProfile
3114 ? UserManager.DISALLOW_REMOVE_MANAGED_PROFILE : UserManager.DISALLOW_REMOVE_USER;
3115 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(restriction, false)) {
3116 Log.w(LOG_TAG, "Cannot remove user. " + restriction + " is enabled.");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04003117 return false;
3118 }
Nicolas Prevotdf1b87d2016-10-25 13:57:08 +01003119 return removeUserUnchecked(userHandle);
3120 }
Julia Reynolds4ac5f852014-06-23 17:38:51 -04003121
Nicolas Prevotdf1b87d2016-10-25 13:57:08 +01003122 private boolean removeUserUnchecked(int userHandle) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01003123 long ident = Binder.clearCallingIdentity();
3124 try {
Amith Yamasani12747872015-12-07 14:19:49 -08003125 final UserData userData;
Fyodor Kupolov0df68cd2015-10-01 13:54:22 -07003126 int currentUser = ActivityManager.getCurrentUser();
3127 if (currentUser == userHandle) {
jovanaka6763a32018-12-03 17:23:20 -08003128 Log.w(LOG_TAG, "Current user cannot be removed.");
Fyodor Kupolov0df68cd2015-10-01 13:54:22 -07003129 return false;
3130 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01003131 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003132 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08003133 userData = mUsers.get(userHandle);
jovanaka6763a32018-12-03 17:23:20 -08003134 if (userHandle == UserHandle.USER_SYSTEM) {
3135 Log.e(LOG_TAG, "System user cannot be removed.");
3136 return false;
3137 }
3138
3139 if (userData == null) {
3140 Log.e(LOG_TAG, String.format(
3141 "Cannot remove user %d, invalid user id provided.", userHandle));
3142 return false;
3143 }
3144
3145 if (mRemovingUserIds.get(userHandle)) {
3146 Log.e(LOG_TAG, String.format(
3147 "User %d is already scheduled for removal.", userHandle));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003148 return false;
3149 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08003150
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003151 addRemovingUserIdLocked(userHandle);
Fyodor Kupolov82402752015-10-28 14:54:51 -07003152 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08003153
Kenny Guyee58b4f2014-05-23 15:19:53 +01003154 // Set this to a partially created user, so that the user will be purged
3155 // on next startup, in case the runtime stops now before stopping and
3156 // removing the user completely.
Amith Yamasani12747872015-12-07 14:19:49 -08003157 userData.info.partial = true;
Kenny Guyee58b4f2014-05-23 15:19:53 +01003158 // Mark it as disabled, so that it isn't returned any more when
3159 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08003160 userData.info.flags |= UserInfo.FLAG_DISABLED;
3161 writeUserLP(userData);
Kenny Guyee58b4f2014-05-23 15:19:53 +01003162 }
Fyodor Kupolov6c96f7f2017-06-28 18:22:59 -07003163 try {
3164 mAppOpsService.removeUser(userHandle);
3165 } catch (RemoteException e) {
jovanaka6763a32018-12-03 17:23:20 -08003166 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user.", e);
Fyodor Kupolov6c96f7f2017-06-28 18:22:59 -07003167 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01003168
Amith Yamasani12747872015-12-07 14:19:49 -08003169 if (userData.info.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
3170 && userData.info.isManagedProfile()) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01003171 // Send broadcast to notify system that the user removed was a
3172 // managed user.
Amith Yamasani12747872015-12-07 14:19:49 -08003173 sendProfileRemovedBroadcast(userData.info.profileGroupId, userData.info.id);
Kenny Guyee58b4f2014-05-23 15:19:53 +01003174 }
3175
3176 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
3177 int res;
3178 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003179 res = ActivityManager.getService().stopUser(userHandle, /* force= */ true,
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07003180 new IStopUserCallback.Stub() {
Kenny Guyee58b4f2014-05-23 15:19:53 +01003181 @Override
3182 public void userStopped(int userId) {
3183 finishRemoveUser(userId);
3184 }
3185 @Override
3186 public void userStopAborted(int userId) {
3187 }
3188 });
3189 } catch (RemoteException e) {
jovanaka6763a32018-12-03 17:23:20 -08003190 Log.w(LOG_TAG, "Failed to stop user during removal.", e);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003191 return false;
3192 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01003193 return res == ActivityManager.USER_OP_SUCCESS;
3194 } finally {
3195 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003196 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003197 }
3198
Andreas Gampea36dc622018-02-05 17:19:22 -08003199 @GuardedBy("mUsersLock")
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003200 @VisibleForTesting
3201 void addRemovingUserIdLocked(int userId) {
3202 // We remember deleted user IDs to prevent them from being
3203 // reused during the current boot; they can still be reused
3204 // after a reboot or recycling of userIds.
3205 mRemovingUserIds.put(userId, true);
3206 mRecentlyRemovedIds.add(userId);
3207 // Keep LRU queue of recently removed IDs for recycling
3208 if (mRecentlyRemovedIds.size() > MAX_RECENTLY_REMOVED_IDS_SIZE) {
3209 mRecentlyRemovedIds.removeFirst();
3210 }
3211 }
3212
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07003213 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07003214 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07003215 // Let other services shutdown any activity and clean up their state before completely
3216 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07003217 long ident = Binder.clearCallingIdentity();
3218 try {
3219 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
3220 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07003221 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
3222 android.Manifest.permission.MANAGE_USERS,
3223
3224 new BroadcastReceiver() {
3225 @Override
3226 public void onReceive(Context context, Intent intent) {
3227 if (DBG) {
3228 Slog.i(LOG_TAG,
3229 "USER_REMOVED broadcast sent, cleaning up user data "
3230 + userHandle);
3231 }
3232 new Thread() {
Amith Yamasani12747872015-12-07 14:19:49 -08003233 @Override
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07003234 public void run() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003235 // Clean up any ActivityTaskManager state
3236 LocalServices.getService(ActivityTaskManagerInternal.class)
3237 .onUserStopped(userHandle);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003238 removeUserState(userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07003239 }
3240 }.start();
3241 }
3242 },
3243
3244 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07003245 } finally {
3246 Binder.restoreCallingIdentity(ident);
3247 }
Amith Yamasani2a003292012-08-14 18:25:45 -07003248 }
3249
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003250 private void removeUserState(final int userHandle) {
Paul Crowley91293792016-03-25 15:23:07 -07003251 try {
3252 mContext.getSystemService(StorageManager.class).destroyUserKey(userHandle);
3253 } catch (IllegalStateException e) {
3254 // This may be simply because the user was partially created.
3255 Slog.i(LOG_TAG,
3256 "Destroying key for user " + userHandle + " failed, continuing anyway", e);
3257 }
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06003258
Amith Yamasanid04aaa32016-06-13 12:09:36 -07003259 // Cleanup gatekeeper secure user id
3260 try {
3261 final IGateKeeperService gk = GateKeeper.getService();
3262 if (gk != null) {
3263 gk.clearSecureUserId(userHandle);
3264 }
3265 } catch (Exception ex) {
3266 Slog.w(LOG_TAG, "unable to clear GK secure user id");
3267 }
3268
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003269 // Cleanup package manager settings
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003270 mPm.cleanUpUser(this, userHandle);
Amith Yamasanid04aaa32016-06-13 12:09:36 -07003271
3272 // Clean up all data before removing metadata
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -08003273 mUserDataPreparer.destroyUserData(userHandle,
Amith Yamasanid04aaa32016-06-13 12:09:36 -07003274 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
3275
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003276 // Remove this user from the list
Fyodor Kupolov82402752015-10-28 14:54:51 -07003277 synchronized (mUsersLock) {
3278 mUsers.remove(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08003279 mIsUserManaged.delete(userHandle);
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003280 }
3281 synchronized (mUserStates) {
3282 mUserStates.delete(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08003283 }
3284 synchronized (mRestrictionsLock) {
3285 mBaseUserRestrictions.remove(userHandle);
3286 mAppliedUserRestrictions.remove(userHandle);
3287 mCachedEffectiveUserRestrictions.remove(userHandle);
3288 mDevicePolicyLocalUserRestrictions.remove(userHandle);
Pavel Grafov6a40f092016-10-25 15:46:51 +01003289 if (mDevicePolicyGlobalUserRestrictions.get(userHandle) != null) {
3290 mDevicePolicyGlobalUserRestrictions.remove(userHandle);
3291 applyUserRestrictionsForAllUsersLR();
3292 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07003293 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003294 // Update the user list
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003295 synchronized (mPackagesLock) {
3296 writeUserListLP();
3297 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06003298 // Remove user file
3299 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
3300 userFile.delete();
Fyodor Kupolov82402752015-10-28 14:54:51 -07003301 updateUserIds();
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003302 if (RELEASE_DELETED_USER_ID) {
3303 synchronized (mUsers) {
3304 mRemovingUserIds.delete(userHandle);
3305 }
3306 }
Amith Yamasani61f57372012-08-31 12:12:28 -07003307 }
3308
Kenny Guyf8d3a232014-05-15 16:09:52 +01003309 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01003310 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01003311 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
3312 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01003313 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
Jeff Sharkeyaf6ec292015-12-17 11:19:00 -07003314 managedProfileIntent.putExtra(Intent.EXTRA_USER_HANDLE, removedUserId);
Kenny Guyf8d3a232014-05-15 16:09:52 +01003315 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01003316 }
3317
Amith Yamasani2a003292012-08-14 18:25:45 -07003318 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07003319 public Bundle getApplicationRestrictions(String packageName) {
3320 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
3321 }
3322
3323 @Override
3324 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003325 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07003326 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07003327 checkSystemOrRoot("get application restrictions for other user/app " + packageName);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003328 }
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003329 synchronized (mAppRestrictionsLock) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003330 // Read the restrictions from XML
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003331 return readApplicationRestrictionsLAr(packageName, userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003332 }
3333 }
3334
3335 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07003336 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003337 int userId) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00003338 checkSystemOrRoot("set application restrictions");
Fyodor Kupolov0d88d542016-04-19 11:37:22 -07003339 if (restrictions != null) {
3340 restrictions.setDefusable(true);
3341 }
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003342 synchronized (mAppRestrictionsLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01003343 if (restrictions == null || restrictions.isEmpty()) {
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003344 cleanAppRestrictionsForPackageLAr(packageName, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01003345 } else {
3346 // Write the restrictions to XML
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003347 writeApplicationRestrictionsLAr(packageName, restrictions, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01003348 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003349 }
Robin Lee66e5d962014-04-09 16:44:21 +01003350
Fyodor Kupolovd2846122016-02-11 18:06:34 -08003351 // Notify package of changes via an intent - only sent to explicitly registered receivers.
3352 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
3353 changeIntent.setPackage(packageName);
3354 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3355 mContext.sendBroadcastAsUser(changeIntent, UserHandle.of(userId));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003356 }
3357
3358 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07003359 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003360 try {
3361 return mContext.getPackageManager().getApplicationInfo(packageName,
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07003362 PackageManager.MATCH_ANY_USER).uid;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003363 } catch (NameNotFoundException nnfe) {
3364 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07003365 } finally {
3366 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003367 }
3368 }
3369
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003370 @GuardedBy("mAppRestrictionsLock")
3371 private static Bundle readApplicationRestrictionsLAr(String packageName, int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003372 AtomicFile restrictionsFile =
3373 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
3374 packageToRestrictionsFileName(packageName)));
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003375 return readApplicationRestrictionsLAr(restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003376 }
3377
3378 @VisibleForTesting
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003379 @GuardedBy("mAppRestrictionsLock")
3380 static Bundle readApplicationRestrictionsLAr(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07003381 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003382 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07003383 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07003384 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07003385 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003386
3387 FileInputStream fis = null;
3388 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003389 fis = restrictionsFile.openRead();
3390 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01003391 parser.setInput(fis, StandardCharsets.UTF_8.name());
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003392 XmlUtils.nextElement(parser);
3393 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003394 Slog.e(LOG_TAG, "Unable to read restrictions file "
3395 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07003396 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003397 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003398 while (parser.next() != XmlPullParser.END_DOCUMENT) {
3399 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003400 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003401 } catch (IOException|XmlPullParserException e) {
3402 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003403 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003404 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003405 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07003406 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003407 }
3408
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003409 private static void readEntry(Bundle restrictions, ArrayList<String> values,
3410 XmlPullParser parser) throws XmlPullParserException, IOException {
3411 int type = parser.getEventType();
3412 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
3413 String key = parser.getAttributeValue(null, ATTR_KEY);
3414 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
3415 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
3416 if (multiple != null) {
3417 values.clear();
3418 int count = Integer.parseInt(multiple);
3419 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
3420 if (type == XmlPullParser.START_TAG
3421 && parser.getName().equals(TAG_VALUE)) {
3422 values.add(parser.nextText().trim());
3423 count--;
3424 }
3425 }
3426 String [] valueStrings = new String[values.size()];
3427 values.toArray(valueStrings);
3428 restrictions.putStringArray(key, valueStrings);
3429 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
3430 restrictions.putBundle(key, readBundleEntry(parser, values));
3431 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
3432 final int outerDepth = parser.getDepth();
3433 ArrayList<Bundle> bundleList = new ArrayList<>();
3434 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
3435 Bundle childBundle = readBundleEntry(parser, values);
3436 bundleList.add(childBundle);
3437 }
3438 restrictions.putParcelableArray(key,
3439 bundleList.toArray(new Bundle[bundleList.size()]));
3440 } else {
3441 String value = parser.nextText().trim();
3442 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
3443 restrictions.putBoolean(key, Boolean.parseBoolean(value));
3444 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
3445 restrictions.putInt(key, Integer.parseInt(value));
3446 } else {
3447 restrictions.putString(key, value);
3448 }
3449 }
3450 }
3451 }
3452
3453 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
3454 throws IOException, XmlPullParserException {
3455 Bundle childBundle = new Bundle();
3456 final int outerDepth = parser.getDepth();
3457 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
3458 readEntry(childBundle, values, parser);
3459 }
3460 return childBundle;
3461 }
3462
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003463 @GuardedBy("mAppRestrictionsLock")
3464 private static void writeApplicationRestrictionsLAr(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07003465 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003466 AtomicFile restrictionsFile = new AtomicFile(
3467 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07003468 packageToRestrictionsFileName(packageName)));
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003469 writeApplicationRestrictionsLAr(restrictions, restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003470 }
3471
3472 @VisibleForTesting
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003473 @GuardedBy("mAppRestrictionsLock")
3474 static void writeApplicationRestrictionsLAr(Bundle restrictions, AtomicFile restrictionsFile) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003475 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003476 try {
3477 fos = restrictionsFile.startWrite();
3478 final BufferedOutputStream bos = new BufferedOutputStream(fos);
3479
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003480 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01003481 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003482 serializer.startDocument(null, true);
3483 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
3484
3485 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003486 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003487 serializer.endTag(null, TAG_RESTRICTIONS);
3488
3489 serializer.endDocument();
3490 restrictionsFile.finishWrite(fos);
3491 } catch (Exception e) {
3492 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003493 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
3494 }
3495 }
3496
3497 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
3498 throws IOException {
3499 for (String key : restrictions.keySet()) {
3500 Object value = restrictions.get(key);
3501 serializer.startTag(null, TAG_ENTRY);
3502 serializer.attribute(null, ATTR_KEY, key);
3503
3504 if (value instanceof Boolean) {
3505 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
3506 serializer.text(value.toString());
3507 } else if (value instanceof Integer) {
3508 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
3509 serializer.text(value.toString());
3510 } else if (value == null || value instanceof String) {
3511 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
3512 serializer.text(value != null ? (String) value : "");
3513 } else if (value instanceof Bundle) {
3514 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
3515 writeBundle((Bundle) value, serializer);
3516 } else if (value instanceof Parcelable[]) {
3517 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
3518 Parcelable[] array = (Parcelable[]) value;
3519 for (Parcelable parcelable : array) {
3520 if (!(parcelable instanceof Bundle)) {
3521 throw new IllegalArgumentException("bundle-array can only hold Bundles");
3522 }
3523 serializer.startTag(null, TAG_ENTRY);
3524 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
3525 writeBundle((Bundle) parcelable, serializer);
3526 serializer.endTag(null, TAG_ENTRY);
3527 }
3528 } else {
3529 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
3530 String[] values = (String[]) value;
3531 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
3532 for (String choice : values) {
3533 serializer.startTag(null, TAG_VALUE);
3534 serializer.text(choice != null ? choice : "");
3535 serializer.endTag(null, TAG_VALUE);
3536 }
3537 }
3538 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003539 }
3540 }
3541
3542 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07003543 public int getUserSerialNumber(int userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003544 synchronized (mUsersLock) {
Pavel Grafov9c295d42019-03-26 19:42:08 +00003545 final UserInfo userInfo = getUserInfoLU(userHandle);
3546 return userInfo != null ? userInfo.serialNumber : -1;
Amith Yamasani2a003292012-08-14 18:25:45 -07003547 }
3548 }
3549
3550 @Override
Fyodor Kupolov605b12a2017-05-10 15:58:09 -07003551 public boolean isUserNameSet(int userHandle) {
3552 synchronized (mUsersLock) {
Pavel Grafov9c295d42019-03-26 19:42:08 +00003553 final UserInfo userInfo = getUserInfoLU(userHandle);
Fyodor Kupolov605b12a2017-05-10 15:58:09 -07003554 return userInfo != null && userInfo.name != null;
3555 }
3556 }
3557
3558 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07003559 public int getUserHandle(int userSerialNumber) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003560 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07003561 for (int userId : mUserIds) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003562 UserInfo info = getUserInfoLU(userId);
Kenny Guy945f8832015-02-10 15:17:26 +00003563 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07003564 }
3565 // Not found
3566 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07003567 }
3568 }
3569
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003570 @Override
3571 public long getUserCreationTime(int userHandle) {
3572 int callingUserId = UserHandle.getCallingUserId();
3573 UserInfo userInfo = null;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003574 synchronized (mUsersLock) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003575 if (callingUserId == userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003576 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003577 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003578 UserInfo parent = getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003579 if (parent != null && parent.id == callingUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003580 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003581 }
3582 }
3583 }
3584 if (userInfo == null) {
3585 throw new SecurityException("userHandle can only be the calling user or a managed "
3586 + "profile associated with this user");
3587 }
3588 return userInfo.creationTime;
3589 }
3590
Amith Yamasani0b285492011-04-14 17:35:23 -07003591 /**
3592 * Caches the list of user ids in an array, adjusting the array size when necessary.
3593 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07003594 private void updateUserIds() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003595 int num = 0;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003596 synchronized (mUsersLock) {
3597 final int userSize = mUsers.size();
3598 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003599 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003600 num++;
3601 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003602 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07003603 final int[] newUsers = new int[num];
3604 int n = 0;
3605 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003606 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003607 newUsers[n++] = mUsers.keyAt(i);
3608 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003609 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07003610 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07003611 }
3612 }
3613
3614 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003615 * Called right before a user is started. This gives us a chance to prepare
3616 * app storage and apply any user restrictions.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003617 */
3618 public void onBeforeStartUser(int userId) {
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003619 UserInfo userInfo = getUserInfo(userId);
3620 if (userInfo == null) {
3621 return;
3622 }
3623 final int userSerial = userInfo.serialNumber;
3624 // Migrate only if build fingerprints mismatch
3625 boolean migrateAppsData = !Build.FINGERPRINT.equals(userInfo.lastLoggedInFingerprint);
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -08003626 mUserDataPreparer.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_DE);
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003627 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_DE, migrateAppsData);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003628
3629 if (userId != UserHandle.USER_SYSTEM) {
3630 synchronized (mRestrictionsLock) {
3631 applyUserRestrictionsLR(userId);
3632 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003633 }
3634 }
3635
3636 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003637 * Called right before a user is unlocked. This gives us a chance to prepare
3638 * app storage.
3639 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003640 public void onBeforeUnlockUser(@UserIdInt int userId) {
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003641 UserInfo userInfo = getUserInfo(userId);
3642 if (userInfo == null) {
3643 return;
3644 }
3645 final int userSerial = userInfo.serialNumber;
3646 // Migrate only if build fingerprints mismatch
3647 boolean migrateAppsData = !Build.FINGERPRINT.equals(userInfo.lastLoggedInFingerprint);
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -08003648 mUserDataPreparer.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_CE);
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003649 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_CE, migrateAppsData);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003650 }
3651
3652 /**
Fyodor Kupolov50979d12017-01-27 17:36:32 -08003653 * Examine all users present on given mounted volume, and destroy data
3654 * belonging to users that are no longer valid, or whose user ID has been
3655 * recycled.
3656 */
3657 void reconcileUsers(String volumeUuid) {
3658 mUserDataPreparer.reconcileUsers(volumeUuid, getUsers(true /* excludeDying */));
3659 }
3660
3661 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07003662 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasanieb437d42016-04-29 09:31:25 -07003663 * This is called with ActivityManagerService lock held.
Amith Yamasani920ace02012-09-20 22:15:37 -07003664 * @param userId the user that was just foregrounded
3665 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003666 public void onUserLoggedIn(@UserIdInt int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -08003667 UserData userData = getUserDataNoChecks(userId);
3668 if (userData == null || userData.info.partial) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003669 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
3670 return;
3671 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003672
3673 final long now = System.currentTimeMillis();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003674 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani12747872015-12-07 14:19:49 -08003675 userData.info.lastLoggedInTime = now;
Amith Yamasani920ace02012-09-20 22:15:37 -07003676 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003677 userData.info.lastLoggedInFingerprint = Build.FINGERPRINT;
3678 scheduleWriteUser(userData);
Amith Yamasani920ace02012-09-20 22:15:37 -07003679 }
3680
3681 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07003682 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani0b285492011-04-14 17:35:23 -07003683 */
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003684 @VisibleForTesting
3685 int getNextAvailableId() {
3686 int nextId;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003687 synchronized (mUsersLock) {
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003688 nextId = scanNextAvailableIdLocked();
3689 if (nextId >= 0) {
3690 return nextId;
3691 }
3692 // All ids up to MAX_USER_ID were used. Remove all mRemovingUserIds,
3693 // except most recently removed
3694 if (mRemovingUserIds.size() > 0) {
3695 Slog.i(LOG_TAG, "All available IDs are used. Recycling LRU ids.");
3696 mRemovingUserIds.clear();
3697 for (Integer recentlyRemovedId : mRecentlyRemovedIds) {
3698 mRemovingUserIds.put(recentlyRemovedId, true);
Amith Yamasani195263742012-08-21 15:40:12 -07003699 }
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003700 nextId = scanNextAvailableIdLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003701 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003702 }
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003703 if (nextId < 0) {
3704 throw new IllegalStateException("No user id available!");
3705 }
3706 return nextId;
3707 }
3708
Andreas Gampea36dc622018-02-05 17:19:22 -08003709 @GuardedBy("mUsersLock")
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003710 private int scanNextAvailableIdLocked() {
3711 for (int i = MIN_USER_ID; i < MAX_USER_ID; i++) {
3712 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
3713 return i;
3714 }
3715 }
3716 return -1;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003717 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003718
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003719 private static String packageToRestrictionsFileName(String packageName) {
Amith Yamasanifc95e702013-09-26 13:20:17 -07003720 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
3721 }
3722
Amith Yamasani920ace02012-09-20 22:15:37 -07003723 @Override
Amith Yamasani12747872015-12-07 14:19:49 -08003724 public void setSeedAccountData(int userId, String accountName, String accountType,
3725 PersistableBundle accountOptions, boolean persist) {
3726 checkManageUsersPermission("Require MANAGE_USERS permission to set user seed data");
3727 synchronized (mPackagesLock) {
3728 final UserData userData;
3729 synchronized (mUsersLock) {
3730 userData = getUserDataLU(userId);
3731 if (userData == null) {
3732 Slog.e(LOG_TAG, "No such user for settings seed data u=" + userId);
3733 return;
3734 }
3735 userData.seedAccountName = accountName;
3736 userData.seedAccountType = accountType;
3737 userData.seedAccountOptions = accountOptions;
3738 userData.persistSeedData = persist;
3739 }
3740 if (persist) {
3741 writeUserLP(userData);
3742 }
3743 }
3744 }
3745
3746 @Override
3747 public String getSeedAccountName() throws RemoteException {
3748 checkManageUsersPermission("Cannot get seed account information");
3749 synchronized (mUsersLock) {
3750 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3751 return userData.seedAccountName;
3752 }
3753 }
3754
3755 @Override
3756 public String getSeedAccountType() throws RemoteException {
3757 checkManageUsersPermission("Cannot get seed account information");
3758 synchronized (mUsersLock) {
3759 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3760 return userData.seedAccountType;
3761 }
3762 }
3763
3764 @Override
3765 public PersistableBundle getSeedAccountOptions() throws RemoteException {
3766 checkManageUsersPermission("Cannot get seed account information");
3767 synchronized (mUsersLock) {
3768 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3769 return userData.seedAccountOptions;
3770 }
3771 }
3772
3773 @Override
3774 public void clearSeedAccountData() throws RemoteException {
3775 checkManageUsersPermission("Cannot clear seed account information");
3776 synchronized (mPackagesLock) {
3777 UserData userData;
3778 synchronized (mUsersLock) {
3779 userData = getUserDataLU(UserHandle.getCallingUserId());
3780 if (userData == null) return;
3781 userData.clearSeedAccountData();
3782 }
3783 writeUserLP(userData);
3784 }
3785 }
3786
3787 @Override
3788 public boolean someUserHasSeedAccount(String accountName, String accountType)
3789 throws RemoteException {
3790 checkManageUsersPermission("Cannot check seed account information");
3791 synchronized (mUsersLock) {
3792 final int userSize = mUsers.size();
3793 for (int i = 0; i < userSize; i++) {
3794 final UserData data = mUsers.valueAt(i);
3795 if (data.info.isInitialized()) continue;
3796 if (data.seedAccountName == null || !data.seedAccountName.equals(accountName)) {
3797 continue;
3798 }
3799 if (data.seedAccountType == null || !data.seedAccountType.equals(accountType)) {
3800 continue;
3801 }
3802 return true;
3803 }
3804 }
3805 return false;
3806 }
3807
3808 @Override
Todd Kennedy60459ab2015-10-30 11:32:16 -07003809 public void onShellCommand(FileDescriptor in, FileDescriptor out,
Dianne Hackborn354736e2016-08-22 17:00:05 -07003810 FileDescriptor err, String[] args, ShellCallback callback,
3811 ResultReceiver resultReceiver) {
3812 (new Shell()).exec(this, in, out, err, args, callback, resultReceiver);
Todd Kennedy60459ab2015-10-30 11:32:16 -07003813 }
3814
3815 int onShellCommand(Shell shell, String cmd) {
3816 if (cmd == null) {
3817 return shell.handleDefaultCommands(cmd);
3818 }
3819
3820 final PrintWriter pw = shell.getOutPrintWriter();
3821 try {
3822 switch(cmd) {
3823 case "list":
Felipe Leme7ad2f6b2019-09-11 09:23:26 -07003824 return runList(pw, shell);
Hui Yu8ba65972018-04-16 18:45:48 -07003825 default:
3826 return shell.handleDefaultCommands(cmd);
Todd Kennedy60459ab2015-10-30 11:32:16 -07003827 }
3828 } catch (RemoteException e) {
3829 pw.println("Remote exception: " + e);
3830 }
3831 return -1;
3832 }
3833
Felipe Leme7ad2f6b2019-09-11 09:23:26 -07003834 private int runList(PrintWriter pw, Shell shell) throws RemoteException {
3835 boolean all = false;
3836 boolean verbose = false;
3837 String opt;
3838 while ((opt = shell.getNextOption()) != null) {
3839 switch (opt) {
3840 case "-v":
3841 verbose = true;
3842 break;
3843 case "--all":
3844 all = true;
3845 break;
3846 default:
3847 pw.println("Invalid option: " + opt);
3848 return -1;
3849 }
3850 }
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003851 final IActivityManager am = ActivityManager.getService();
Felipe Leme7ad2f6b2019-09-11 09:23:26 -07003852 final List<UserInfo> users = getUsers(/* excludePartial= */ !all,
3853 /* excludingDying=*/ false, /* excludePreCreated= */ !all);
Todd Kennedy60459ab2015-10-30 11:32:16 -07003854 if (users == null) {
3855 pw.println("Error: couldn't get users");
3856 return 1;
3857 } else {
Felipe Leme7ad2f6b2019-09-11 09:23:26 -07003858 final int size = users.size();
3859 int currentUser = UserHandle.USER_NULL;
3860 if (verbose) {
3861 pw.printf("%d users:\n\n", size);
3862 currentUser = am.getCurrentUser().id;
3863 } else {
3864 // NOTE: the standard "list users" command is used by integration tests and
3865 // hence should not be changed. If you need to add more info, use the
3866 // verbose option.
3867 pw.println("Users:");
3868 }
3869 for (int i = 0; i < size; i++) {
3870 final UserInfo user = users.get(i);
3871 final boolean running = am.isUserRunning(user.id, 0);
3872 final boolean current = user.id == currentUser;
3873 if (verbose) {
3874 pw.printf("%d: id=%d, name=%s, flags=%s%s%s%s%s\n", i, user.id, user.name,
3875 UserInfo.flagsToString(user.flags),
3876 running ? " (running)" : "",
3877 user.partial ? " (partial)" : "",
3878 user.preCreated ? " (pre-created)" : "",
3879 current ? " (current)" : "");
3880 } else {
3881 // NOTE: the standard "list users" command is used by integration tests and
3882 // hence should not be changed. If you need to add more info, use the
3883 // verbose option.
3884 pw.printf("\t%s%s\n", user, running ? " running" : "");
3885 }
Todd Kennedy60459ab2015-10-30 11:32:16 -07003886 }
3887 return 0;
3888 }
3889 }
3890
3891 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -07003892 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06003893 if (!DumpUtils.checkDumpPermission(mContext, LOG_TAG, pw)) return;
Amith Yamasani920ace02012-09-20 22:15:37 -07003894
3895 long now = System.currentTimeMillis();
Makoto Onuki73dded22017-12-20 13:14:48 +09003896 final long nowRealtime = SystemClock.elapsedRealtime();
Felipe Leme3c5e8862019-06-12 17:40:53 -07003897
3898 final int currentUser = LocalServices.getService(ActivityManagerInternal.class)
3899 .getCurrentUserId();
3900 pw.print("Current user: "); pw.println(currentUser);
3901
Amith Yamasani920ace02012-09-20 22:15:37 -07003902 StringBuilder sb = new StringBuilder();
3903 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003904 synchronized (mUsersLock) {
3905 pw.println("Users:");
3906 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003907 UserData userData = mUsers.valueAt(i);
3908 if (userData == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003909 continue;
3910 }
Amith Yamasani12747872015-12-07 14:19:49 -08003911 UserInfo userInfo = userData.info;
3912 final int userId = userInfo.id;
3913 pw.print(" "); pw.print(userInfo);
3914 pw.print(" serialNo="); pw.print(userInfo.serialNumber);
Felipe Leme3c5e8862019-06-12 17:40:53 -07003915 pw.print(" isPrimary="); pw.print(userInfo.isPrimary());
Makoto Onukie7927da2015-11-25 10:05:17 -08003916 if (mRemovingUserIds.get(userId)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003917 pw.print(" <removing> ");
3918 }
Amith Yamasani12747872015-12-07 14:19:49 -08003919 if (userInfo.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003920 pw.print(" <partial>");
3921 }
Felipe Leme7ad2f6b2019-09-11 09:23:26 -07003922 if (userInfo.preCreated) {
3923 pw.print(" <pre-created>");
3924 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07003925 pw.println();
Makoto Onuki88aef752017-03-29 16:52:03 -07003926 pw.print(" State: ");
3927 final int state;
3928 synchronized (mUserStates) {
3929 state = mUserStates.get(userId, -1);
3930 }
3931 pw.println(UserState.stateToString(state));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003932 pw.print(" Created: ");
Makoto Onuki73dded22017-12-20 13:14:48 +09003933 dumpTimeAgo(pw, sb, now, userInfo.creationTime);
3934
Fyodor Kupolov82402752015-10-28 14:54:51 -07003935 pw.print(" Last logged in: ");
Makoto Onuki73dded22017-12-20 13:14:48 +09003936 dumpTimeAgo(pw, sb, now, userInfo.lastLoggedInTime);
3937
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003938 pw.print(" Last logged in fingerprint: ");
3939 pw.println(userInfo.lastLoggedInFingerprint);
Makoto Onuki73dded22017-12-20 13:14:48 +09003940
3941 pw.print(" Start time: ");
3942 dumpTimeAgo(pw, sb, nowRealtime, userData.startRealtime);
3943
3944 pw.print(" Unlock time: ");
3945 dumpTimeAgo(pw, sb, nowRealtime, userData.unlockRealtime);
3946
Makoto Onukie7927da2015-11-25 10:05:17 -08003947 pw.print(" Has profile owner: ");
3948 pw.println(mIsUserManaged.get(userId));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003949 pw.println(" Restrictions:");
3950 synchronized (mRestrictionsLock) {
3951 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003952 pw, " ", mBaseUserRestrictions.get(userInfo.id));
Pavel Grafov6a40f092016-10-25 15:46:51 +01003953 pw.println(" Device policy global restrictions:");
3954 UserRestrictionsUtils.dumpRestrictions(
3955 pw, " ", mDevicePolicyGlobalUserRestrictions.get(userInfo.id));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003956 pw.println(" Device policy local restrictions:");
3957 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003958 pw, " ", mDevicePolicyLocalUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003959 pw.println(" Effective restrictions:");
3960 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003961 pw, " ", mCachedEffectiveUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003962 }
Amith Yamasani12747872015-12-07 14:19:49 -08003963
3964 if (userData.account != null) {
3965 pw.print(" Account name: " + userData.account);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08003966 pw.println();
3967 }
Amith Yamasani12747872015-12-07 14:19:49 -08003968
3969 if (userData.seedAccountName != null) {
3970 pw.print(" Seed account name: " + userData.seedAccountName);
3971 pw.println();
3972 if (userData.seedAccountType != null) {
3973 pw.print(" account type: " + userData.seedAccountType);
3974 pw.println();
3975 }
3976 if (userData.seedAccountOptions != null) {
3977 pw.print(" account options exist");
3978 pw.println();
3979 }
3980 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003981 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003982 }
Amith Yamasani12747872015-12-07 14:19:49 -08003983 pw.println();
Pavel Grafov6a40f092016-10-25 15:46:51 +01003984 pw.println(" Device owner id:" + mDeviceOwnerUserId);
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01003985 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003986 pw.println(" Guest restrictions:");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003987 synchronized (mGuestRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003988 UserRestrictionsUtils.dumpRestrictions(pw, " ", mGuestRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003989 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003990 synchronized (mUsersLock) {
3991 pw.println();
3992 pw.println(" Device managed: " + mIsDeviceManaged);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003993 if (mRemovingUserIds.size() > 0) {
3994 pw.println();
3995 pw.println(" Recently removed userIds: " + mRecentlyRemovedIds);
3996 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003997 }
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003998 synchronized (mUserStates) {
3999 pw.println(" Started users state: " + mUserStates);
4000 }
Felipe Leme3c5e8862019-06-12 17:40:53 -07004001 } // synchronized (mPackagesLock)
4002
4003 // Dump some capabilities
4004 pw.println();
Felipe Leme7ad2f6b2019-09-11 09:23:26 -07004005 pw.print(" Max users: " + UserManager.getMaxSupportedUsers());
4006 pw.println(" (limit reached: " + isUserLimitReached() + ")");
Felipe Leme3c5e8862019-06-12 17:40:53 -07004007 pw.println(" Supports switchable users: " + UserManager.supportsMultipleUsers());
Felipe Leme7ad2f6b2019-09-11 09:23:26 -07004008 pw.println(" All guests ephemeral: " + areGuestUsersEphemeral());
Felipe Leme3c5e8862019-06-12 17:40:53 -07004009 pw.println(" Is split-system user: " + UserManager.isSplitSystemUser());
Felipe Leme7ad2f6b2019-09-11 09:23:26 -07004010 pw.println(" User version: " + mUserVersion);
Amith Yamasani920ace02012-09-20 22:15:37 -07004011 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08004012
Makoto Onuki73dded22017-12-20 13:14:48 +09004013 private static void dumpTimeAgo(PrintWriter pw, StringBuilder sb, long nowTime, long time) {
4014 if (time == 0) {
4015 pw.println("<unknown>");
4016 } else {
4017 sb.setLength(0);
4018 TimeUtils.formatDuration(nowTime - time, sb);
4019 sb.append(" ago");
4020 pw.println(sb);
4021 }
4022 }
4023
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08004024 final class MainHandler extends Handler {
4025
4026 @Override
4027 public void handleMessage(Message msg) {
4028 switch (msg.what) {
4029 case WRITE_USER_MSG:
4030 removeMessages(WRITE_USER_MSG, msg.obj);
4031 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08004032 int userId = ((UserData) msg.obj).info.id;
4033 UserData userData = getUserDataNoChecks(userId);
4034 if (userData != null) {
4035 writeUserLP(userData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08004036 }
4037 }
4038 }
4039 }
4040 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07004041
4042 /**
4043 * @param userId
4044 * @return whether the user has been initialized yet
4045 */
Todd Kennedy0eb97382017-10-03 16:57:22 -07004046 boolean isUserInitialized(int userId) {
4047 return mLocalService.isUserInitialized(userId);
Amith Yamasanibb054c92015-07-09 14:16:27 -07004048 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07004049
4050 private class LocalService extends UserManagerInternal {
Makoto Onuki068c54a2015-10-13 14:34:03 -07004051 @Override
Pavel Grafov6a40f092016-10-25 15:46:51 +01004052 public void setDevicePolicyUserRestrictions(int userId, @Nullable Bundle restrictions,
4053 boolean isDeviceOwner, int cameraRestrictionScope) {
4054 UserManagerService.this.setDevicePolicyUserRestrictionsInner(userId, restrictions,
4055 isDeviceOwner, cameraRestrictionScope);
Makoto Onuki068c54a2015-10-13 14:34:03 -07004056 }
4057
4058 @Override
4059 public Bundle getBaseUserRestrictions(int userId) {
4060 synchronized (mRestrictionsLock) {
4061 return mBaseUserRestrictions.get(userId);
4062 }
4063 }
4064
4065 @Override
4066 public void setBaseUserRestrictionsByDpmsForMigration(
4067 int userId, Bundle baseRestrictions) {
4068 synchronized (mRestrictionsLock) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01004069 if (updateRestrictionsIfNeededLR(
4070 userId, new Bundle(baseRestrictions), mBaseUserRestrictions)) {
4071 invalidateEffectiveUserRestrictionsLR(userId);
4072 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07004073 }
4074
Amith Yamasani12747872015-12-07 14:19:49 -08004075 final UserData userData = getUserDataNoChecks(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07004076 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08004077 if (userData != null) {
4078 writeUserLP(userData);
Makoto Onuki068c54a2015-10-13 14:34:03 -07004079 } else {
4080 Slog.w(LOG_TAG, "UserInfo not found for " + userId);
4081 }
4082 }
4083 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08004084
4085 @Override
4086 public boolean getUserRestriction(int userId, String key) {
4087 return getUserRestrictions(userId).getBoolean(key);
4088 }
4089
4090 @Override
4091 public void addUserRestrictionsListener(UserRestrictionsListener listener) {
4092 synchronized (mUserRestrictionsListeners) {
4093 mUserRestrictionsListeners.add(listener);
4094 }
4095 }
4096
4097 @Override
4098 public void removeUserRestrictionsListener(UserRestrictionsListener listener) {
4099 synchronized (mUserRestrictionsListeners) {
4100 mUserRestrictionsListeners.remove(listener);
4101 }
4102 }
Makoto Onukie7927da2015-11-25 10:05:17 -08004103
4104 @Override
4105 public void setDeviceManaged(boolean isManaged) {
4106 synchronized (mUsersLock) {
4107 mIsDeviceManaged = isManaged;
4108 }
4109 }
4110
4111 @Override
4112 public void setUserManaged(int userId, boolean isManaged) {
4113 synchronized (mUsersLock) {
4114 mIsUserManaged.put(userId, isManaged);
4115 }
4116 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01004117
4118 @Override
4119 public void setUserIcon(int userId, Bitmap bitmap) {
4120 long ident = Binder.clearCallingIdentity();
4121 try {
4122 synchronized (mPackagesLock) {
4123 UserData userData = getUserDataNoChecks(userId);
4124 if (userData == null || userData.info.partial) {
4125 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
4126 return;
4127 }
4128 writeBitmapLP(userData.info, bitmap);
4129 writeUserLP(userData);
4130 }
4131 sendUserInfoChangedBroadcast(userId);
4132 } finally {
4133 Binder.restoreCallingIdentity(ident);
4134 }
4135 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01004136
4137 @Override
4138 public void setForceEphemeralUsers(boolean forceEphemeralUsers) {
4139 synchronized (mUsersLock) {
4140 mForceEphemeralUsers = forceEphemeralUsers;
4141 }
4142 }
4143
4144 @Override
4145 public void removeAllUsers() {
4146 if (UserHandle.USER_SYSTEM == ActivityManager.getCurrentUser()) {
4147 // Remove the non-system users straight away.
4148 removeNonSystemUsers();
4149 } else {
4150 // Switch to the system user first and then remove the other users.
4151 BroadcastReceiver userSwitchedReceiver = new BroadcastReceiver() {
4152 @Override
4153 public void onReceive(Context context, Intent intent) {
4154 int userId =
4155 intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
4156 if (userId != UserHandle.USER_SYSTEM) {
4157 return;
4158 }
4159 mContext.unregisterReceiver(this);
4160 removeNonSystemUsers();
4161 }
4162 };
4163 IntentFilter userSwitchedFilter = new IntentFilter();
4164 userSwitchedFilter.addAction(Intent.ACTION_USER_SWITCHED);
4165 mContext.registerReceiver(
4166 userSwitchedReceiver, userSwitchedFilter, null, mHandler);
4167
4168 // Switch to the system user.
4169 ActivityManager am =
4170 (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
4171 am.switchUser(UserHandle.USER_SYSTEM);
4172 }
4173 }
phweisse9c44062016-02-10 12:57:38 +01004174
4175 @Override
Lenka Trochtova1ddda472016-02-12 10:42:12 +01004176 public void onEphemeralUserStop(int userId) {
4177 synchronized (mUsersLock) {
4178 UserInfo userInfo = getUserInfoLU(userId);
4179 if (userInfo != null && userInfo.isEphemeral()) {
4180 // Do not allow switching back to the ephemeral user again as the user is going
4181 // to be deleted.
4182 userInfo.flags |= UserInfo.FLAG_DISABLED;
4183 if (userInfo.isGuest()) {
4184 // Indicate that the guest will be deleted after it stops.
4185 userInfo.guestToRemove = true;
4186 }
4187 }
4188 }
4189 }
4190
4191 @Override
Alex Chaub6a9f942017-11-07 11:28:56 +08004192 public UserInfo createUserEvenWhenDisallowed(String name, int flags,
4193 String[] disallowedPackages) {
4194 UserInfo user = createUserInternalUnchecked(name, flags, UserHandle.USER_NULL,
Felipe Leme7ad2f6b2019-09-11 09:23:26 -07004195 /* preCreated= */ false, disallowedPackages);
phweisse9c44062016-02-10 12:57:38 +01004196 // Keep this in sync with UserManager.createUser
Christine Franks97a54802017-08-09 10:06:43 -07004197 if (user != null && !user.isAdmin() && !user.isDemo()) {
phweisse9c44062016-02-10 12:57:38 +01004198 setUserRestriction(UserManager.DISALLOW_SMS, true, user.id);
4199 setUserRestriction(UserManager.DISALLOW_OUTGOING_CALLS, true, user.id);
4200 }
4201 return user;
4202 }
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07004203
4204 @Override
Nicolas Prevotdf1b87d2016-10-25 13:57:08 +01004205 public boolean removeUserEvenWhenDisallowed(int userId) {
4206 return removeUserUnchecked(userId);
4207 }
4208
4209 @Override
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00004210 public boolean isUserRunning(int userId) {
4211 synchronized (mUserStates) {
4212 return mUserStates.get(userId, -1) >= 0;
4213 }
4214 }
4215
4216 @Override
4217 public void setUserState(int userId, int userState) {
4218 synchronized (mUserStates) {
4219 mUserStates.put(userId, userState);
4220 }
4221 }
4222
4223 @Override
4224 public void removeUserState(int userId) {
4225 synchronized (mUserStates) {
4226 mUserStates.delete(userId);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07004227 }
4228 }
4229
4230 @Override
Michael Wachenschwanz3f2b6552017-05-15 13:53:09 -07004231 public int[] getUserIds() {
4232 return UserManagerService.this.getUserIds();
4233 }
4234
4235 @Override
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07004236 public boolean isUserUnlockingOrUnlocked(int userId) {
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07004237 int state;
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00004238 synchronized (mUserStates) {
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07004239 state = mUserStates.get(userId, -1);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07004240 }
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07004241 // Special case, in the stopping/shutdown state user key can still be unlocked
4242 if (state == UserState.STATE_STOPPING || state == UserState.STATE_SHUTDOWN) {
4243 return StorageManager.isUserKeyUnlocked(userId);
4244 }
4245 return (state == UserState.STATE_RUNNING_UNLOCKING)
4246 || (state == UserState.STATE_RUNNING_UNLOCKED);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07004247 }
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08004248
4249 @Override
4250 public boolean isUserUnlocked(int userId) {
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07004251 int state;
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08004252 synchronized (mUserStates) {
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07004253 state = mUserStates.get(userId, -1);
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08004254 }
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07004255 // Special case, in the stopping/shutdown state user key can still be unlocked
4256 if (state == UserState.STATE_STOPPING || state == UserState.STATE_SHUTDOWN) {
4257 return StorageManager.isUserKeyUnlocked(userId);
4258 }
4259 return state == UserState.STATE_RUNNING_UNLOCKED;
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08004260 }
Todd Kennedy0eb97382017-10-03 16:57:22 -07004261
4262 @Override
4263 public boolean isUserInitialized(int userId) {
4264 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
4265 }
4266
4267 @Override
4268 public boolean exists(int userId) {
4269 return getUserInfoNoChecks(userId) != null;
4270 }
Sunny Goyal145c8f82018-02-15 14:27:09 -08004271
4272 @Override
4273 public boolean isProfileAccessible(int callingUserId, int targetUserId, String debugMsg,
4274 boolean throwSecurityException) {
4275 if (targetUserId == callingUserId) {
4276 return true;
4277 }
4278 synchronized (mUsersLock) {
4279 UserInfo callingUserInfo = getUserInfoLU(callingUserId);
4280 if (callingUserInfo == null || callingUserInfo.isManagedProfile()) {
4281 if (throwSecurityException) {
4282 throw new SecurityException(
4283 debugMsg + " for another profile "
4284 + targetUserId + " from " + callingUserId);
4285 }
4286 }
4287
4288 UserInfo targetUserInfo = getUserInfoLU(targetUserId);
4289 if (targetUserInfo == null || !targetUserInfo.isEnabled()) {
4290 // Do not throw any exception here as this could happen due to race conditions
4291 // between the system updating its state and the client getting notified.
4292 if (throwSecurityException) {
4293 Slog.w(LOG_TAG, debugMsg + " for disabled profile "
4294 + targetUserId + " from " + callingUserId);
4295 }
4296 return false;
4297 }
4298
4299 if (targetUserInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID ||
4300 targetUserInfo.profileGroupId != callingUserInfo.profileGroupId) {
4301 if (throwSecurityException) {
4302 throw new SecurityException(
4303 debugMsg + " for unrelated profile " + targetUserId);
4304 }
4305 return false;
4306 }
4307 }
4308 return true;
4309 }
4310
4311 @Override
4312 public int getProfileParentId(int userId) {
4313 synchronized (mUsersLock) {
4314 UserInfo profileParent = getProfileParentLU(userId);
4315 if (profileParent == null) {
4316 return userId;
4317 }
4318 return profileParent.id;
4319 }
4320 }
yuemingw1d13eae2018-01-30 17:27:54 +00004321
4322 @Override
4323 public boolean isSettingRestrictedForUser(String setting, @UserIdInt int userId,
4324 String value, int callingUid) {
4325 return UserRestrictionsUtils.isSettingRestrictedForUser(mContext, setting, userId,
4326 value, callingUid);
4327 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01004328 }
4329
4330 /* Remove all the users except of the system one. */
4331 private void removeNonSystemUsers() {
4332 ArrayList<UserInfo> usersToRemove = new ArrayList<>();
4333 synchronized (mUsersLock) {
4334 final int userSize = mUsers.size();
4335 for (int i = 0; i < userSize; i++) {
4336 UserInfo ui = mUsers.valueAt(i).info;
4337 if (ui.id != UserHandle.USER_SYSTEM) {
4338 usersToRemove.add(ui);
4339 }
4340 }
4341 }
4342 for (UserInfo ui: usersToRemove) {
4343 removeUser(ui.id);
4344 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07004345 }
Todd Kennedy60459ab2015-10-30 11:32:16 -07004346
4347 private class Shell extends ShellCommand {
4348 @Override
4349 public int onCommand(String cmd) {
4350 return onShellCommand(this, cmd);
4351 }
4352
4353 @Override
4354 public void onHelp() {
4355 final PrintWriter pw = getOutPrintWriter();
4356 pw.println("User manager (user) commands:");
4357 pw.println(" help");
4358 pw.println(" Print this help text.");
4359 pw.println("");
Felipe Leme7ad2f6b2019-09-11 09:23:26 -07004360 pw.println(" list [-v] [-all]");
Todd Kennedy60459ab2015-10-30 11:32:16 -07004361 pw.println(" Prints all users on the system.");
4362 }
4363 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08004364
4365 private static void debug(String message) {
4366 Log.d(LOG_TAG, message +
4367 (DBG_WITH_STACKTRACE ? " called at\n" + Debug.getCallers(10, " ") : ""));
4368 }
Kenny Guy02c89902016-11-15 19:36:38 +00004369
4370 @VisibleForTesting
4371 static int getMaxManagedProfiles() {
4372 // Allow overriding max managed profiles on debuggable builds for testing
4373 // of multiple profiles.
4374 if (!Build.IS_DEBUGGABLE) {
4375 return MAX_MANAGED_PROFILES;
4376 } else {
4377 return SystemProperties.getInt("persist.sys.max_profiles",
4378 MAX_MANAGED_PROFILES);
4379 }
4380 }
4381
Andreas Gampe2e8c7672018-07-20 13:01:08 -07004382 @GuardedBy("mUsersLock")
Kenny Guy02c89902016-11-15 19:36:38 +00004383 @VisibleForTesting
4384 int getFreeProfileBadgeLU(int parentUserId) {
4385 int maxManagedProfiles = getMaxManagedProfiles();
4386 boolean[] usedBadges = new boolean[maxManagedProfiles];
4387 final int userSize = mUsers.size();
4388 for (int i = 0; i < userSize; i++) {
4389 UserInfo ui = mUsers.valueAt(i).info;
4390 // Check which badge indexes are already used by this profile group.
4391 if (ui.isManagedProfile()
4392 && ui.profileGroupId == parentUserId
4393 && !mRemovingUserIds.get(ui.id)
4394 && ui.profileBadge < maxManagedProfiles) {
4395 usedBadges[ui.profileBadge] = true;
4396 }
4397 }
4398 for (int i = 0; i < maxManagedProfiles; i++) {
4399 if (!usedBadges[i]) {
4400 return i;
4401 }
4402 }
4403 return 0;
4404 }
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07004405
4406 /**
4407 * Checks if the given user has a managed profile associated with it.
4408 * @param userId The parent user
4409 * @return
4410 */
4411 boolean hasManagedProfile(int userId) {
4412 synchronized (mUsersLock) {
4413 UserInfo userInfo = getUserInfoLU(userId);
4414 final int userSize = mUsers.size();
4415 for (int i = 0; i < userSize; i++) {
4416 UserInfo profile = mUsers.valueAt(i).info;
4417 if (userId != profile.id && isProfileOf(userInfo, profile)) {
4418 return true;
4419 }
4420 }
4421 return false;
4422 }
4423 }
Tony Makd390ae92017-12-28 13:23:10 +00004424
4425 /**
4426 * Check if the calling package name matches with the calling UID, throw
4427 * {@link SecurityException} if not.
4428 */
4429 private void verifyCallingPackage(String callingPackage, int callingUid) {
4430 int packageUid = mPm.getPackageUid(callingPackage, 0, UserHandle.getUserId(callingUid));
4431 if (packageUid != callingUid) {
4432 throw new SecurityException("Specified package " + callingPackage
4433 + " does not match the calling uid " + callingUid);
4434 }
4435 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07004436}