blob: 02abd7a447da3afc073cacb4a8ca21460c54df1e [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;
Lenka Trochtova02fee152015-12-22 14:26:18 +010044import android.content.res.Resources;
Amith Yamasanie928d7d2012-09-17 21:46:51 -070045import android.graphics.Bitmap;
Amith Yamasani258848d2012-08-10 17:06:33 -070046import android.os.Binder;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -060047import android.os.Build;
Amith Yamasanie4cf7342012-12-17 11:12:09 -080048import android.os.Bundle;
Makoto Onuki1a2cd742015-11-16 13:51:27 -080049import android.os.Debug;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070050import android.os.Environment;
51import android.os.FileUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080052import android.os.Handler;
Svet Ganov9cea80cd2016-02-16 11:47:00 -080053import android.os.IBinder;
Tony Mak64fd8c02017-12-01 19:11:59 +000054import android.os.IProgressListener;
Amith Yamasani258848d2012-08-10 17:06:33 -070055import android.os.IUserManager;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -080056import android.os.Message;
Adrian Roos1bdff912015-02-17 15:51:35 +010057import android.os.ParcelFileDescriptor;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070058import android.os.Parcelable;
Amith Yamasani12747872015-12-07 14:19:49 -080059import android.os.PersistableBundle;
Amith Yamasani258848d2012-08-10 17:06:33 -070060import android.os.Process;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070061import android.os.RemoteException;
Todd Kennedy60459ab2015-10-30 11:32:16 -070062import android.os.ResultReceiver;
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +010063import android.os.SELinux;
Jason Monk62062992014-05-06 09:55:28 -040064import android.os.ServiceManager;
Dianne Hackborn354736e2016-08-22 17:00:05 -070065import android.os.ShellCallback;
Todd Kennedy60459ab2015-10-30 11:32:16 -070066import android.os.ShellCommand;
Makoto Onuki73dded22017-12-20 13:14:48 +090067import android.os.SystemClock;
Kenny Guy02c89902016-11-15 19:36:38 +000068import android.os.SystemProperties;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070069import android.os.UserHandle;
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070070import android.os.UserManager;
Pavel Grafov6a40f092016-10-25 15:46:51 +010071import android.os.UserManager.EnforcingUser;
Makoto Onuki068c54a2015-10-13 14:34:03 -070072import android.os.UserManagerInternal;
Makoto Onukid45a4a22015-11-02 17:17:38 -080073import android.os.UserManagerInternal.UserRestrictionsListener;
Paul Crowley85e4e812015-05-19 12:42:00 +010074import android.os.storage.StorageManager;
Amith Yamasanid04aaa32016-06-13 12:09:36 -070075import android.security.GateKeeper;
76import android.service.gatekeeper.IGateKeeperService;
arangelov9b632d72018-12-07 23:21:22 +000077import android.stats.devicepolicy.DevicePolicyEnums;
Amith Yamasani2a003292012-08-14 18:25:45 -070078import android.util.AtomicFile;
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -070079import android.util.IntArray;
Amith Yamasani655d0e22013-06-12 14:19:10 -070080import android.util.Log;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070081import android.util.Slog;
82import android.util.SparseArray;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080083import android.util.SparseBooleanArray;
Amith Yamasaniea1b9d72016-05-27 15:57:38 +000084import android.util.SparseIntArray;
Amith Yamasani920ace02012-09-20 22:15:37 -070085import android.util.TimeUtils;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070086import android.util.Xml;
87
Makoto Onuki068c54a2015-10-13 14:34:03 -070088import com.android.internal.annotations.GuardedBy;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070089import com.android.internal.annotations.VisibleForTesting;
Jason Monk62062992014-05-06 09:55:28 -040090import com.android.internal.app.IAppOpsService;
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -080091import com.android.internal.logging.MetricsLogger;
Fyodor Kupolova68a2862018-01-30 18:22:00 -080092import com.android.internal.os.BackgroundThread;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -060093import com.android.internal.util.DumpUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080094import com.android.internal.util.FastXmlSerializer;
Makoto Onuki068c54a2015-10-13 14:34:03 -070095import com.android.internal.util.Preconditions;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070096import com.android.internal.util.XmlUtils;
Clara Bayarri10ad84a2015-12-01 17:38:05 +000097import com.android.internal.widget.LockPatternUtils;
Amith Yamasani515d4062015-09-28 11:30:06 -070098import com.android.server.LocalServices;
Jeff Sharkey5f3e9342017-03-13 14:53:11 -060099import com.android.server.LockGuard;
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700100import com.android.server.SystemService;
Amith Yamasaniea1b9d72016-05-27 15:57:38 +0000101import com.android.server.am.UserState;
Suprabh Shuklac5e057c2016-08-08 16:22:44 -0700102import com.android.server.storage.DeviceStorageMonitorInternal;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700103import com.android.server.wm.ActivityTaskManagerInternal;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800104
arangelov9b632d72018-12-07 23:21:22 +0000105import libcore.io.IoUtils;
106
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800107import org.xmlpull.v1.XmlPullParser;
108import org.xmlpull.v1.XmlPullParserException;
109import org.xmlpull.v1.XmlSerializer;
110
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700111import java.io.BufferedOutputStream;
112import java.io.File;
Amith Yamasani920ace02012-09-20 22:15:37 -0700113import java.io.FileDescriptor;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700114import java.io.FileInputStream;
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700115import java.io.FileNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700116import java.io.FileOutputStream;
Tony Mak64fd8c02017-12-01 19:11:59 +0000117import java.io.IOException;
Kenny Guy02c89902016-11-15 19:36:38 +0000118import java.io.InputStream;
119import java.io.OutputStream;
Amith Yamasani920ace02012-09-20 22:15:37 -0700120import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100121import java.nio.charset.StandardCharsets;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700122import java.util.ArrayList;
Pavel Grafov6a40f092016-10-25 15:46:51 +0100123import java.util.Collections;
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700124import java.util.LinkedList;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700125import java.util.List;
Narayan Kamath607223f2018-02-19 14:09:02 +0000126import java.util.Objects;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700127
Makoto Onuki068c54a2015-10-13 14:34:03 -0700128/**
129 * Service for {@link UserManager}.
130 *
131 * Method naming convention:
Fyodor Kupolov82402752015-10-28 14:54:51 -0700132 * <ul>
Fyodor Kupolovd31cee92017-09-05 16:31:08 -0700133 * <li> Methods suffixed with "LAr" should be called within the {@link #mAppRestrictionsLock} lock.
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800134 * <li> Methods suffixed with "LP" should be called within the {@link #mPackagesLock} lock.
Fyodor Kupolov82402752015-10-28 14:54:51 -0700135 * <li> Methods suffixed with "LR" should be called within the {@link #mRestrictionsLock} lock.
136 * <li> Methods suffixed with "LU" should be called within the {@link #mUsersLock} lock.
137 * </ul>
Makoto Onuki068c54a2015-10-13 14:34:03 -0700138 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700139public class UserManagerService extends IUserManager.Stub {
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700140
Amith Yamasani2a003292012-08-14 18:25:45 -0700141 private static final String LOG_TAG = "UserManagerService";
Makoto Onuki81c61ea2016-01-22 11:22:26 -0800142 static final boolean DBG = false; // DO NOT SUBMIT WITH TRUE
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800143 private static final boolean DBG_WITH_STACKTRACE = false; // DO NOT SUBMIT WITH TRUE
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700144 // Can be used for manual testing of id recycling
145 private static final boolean RELEASE_DELETED_USER_ID = false; // DO NOT SUBMIT WITH TRUE
Amith Yamasani16389312012-10-17 21:20:14 -0700146
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700147 private static final String TAG_NAME = "name";
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800148 private static final String TAG_ACCOUNT = "account";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700149 private static final String ATTR_FLAGS = "flags";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700150 private static final String ATTR_ICON_PATH = "icon";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700151 private static final String ATTR_ID = "id";
Amith Yamasani920ace02012-09-20 22:15:37 -0700152 private static final String ATTR_CREATION_TIME = "created";
153 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -0600154 private static final String ATTR_LAST_LOGGED_IN_FINGERPRINT = "lastLoggedInFingerprint";
Amith Yamasani2a003292012-08-14 18:25:45 -0700155 private static final String ATTR_SERIAL_NO = "serialNumber";
156 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700157 private static final String ATTR_PARTIAL = "partial";
Adam Lesinskieddeb492014-09-08 17:50:03 -0700158 private static final String ATTR_GUEST_TO_REMOVE = "guestToRemove";
Amith Yamasani6f34b412012-10-22 18:19:27 -0700159 private static final String ATTR_USER_VERSION = "version";
Kenny Guy2a764942014-04-02 13:29:20 +0100160 private static final String ATTR_PROFILE_GROUP_ID = "profileGroupId";
Kenny Guy02c89902016-11-15 19:36:38 +0000161 private static final String ATTR_PROFILE_BADGE = "profileBadge";
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700162 private static final String ATTR_RESTRICTED_PROFILE_PARENT_ID = "restrictedProfileParentId";
Amith Yamasani12747872015-12-07 14:19:49 -0800163 private static final String ATTR_SEED_ACCOUNT_NAME = "seedAccountName";
164 private static final String ATTR_SEED_ACCOUNT_TYPE = "seedAccountType";
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530165 private static final String TAG_GUEST_RESTRICTIONS = "guestRestrictions";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700166 private static final String TAG_USERS = "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700167 private static final String TAG_USER = "user";
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800168 private static final String TAG_RESTRICTIONS = "restrictions";
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800169 private static final String TAG_DEVICE_POLICY_RESTRICTIONS = "device_policy_restrictions";
Pavel Grafov6a40f092016-10-25 15:46:51 +0100170 private static final String TAG_DEVICE_POLICY_GLOBAL_RESTRICTIONS =
171 "device_policy_global_restrictions";
172 /** Legacy name for device owner id tag. */
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +0100173 private static final String TAG_GLOBAL_RESTRICTION_OWNER_ID = "globalRestrictionOwnerUserId";
Pavel Grafov6a40f092016-10-25 15:46:51 +0100174 private static final String TAG_DEVICE_OWNER_USER_ID = "deviceOwnerUserId";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800175 private static final String TAG_ENTRY = "entry";
176 private static final String TAG_VALUE = "value";
Amith Yamasani12747872015-12-07 14:19:49 -0800177 private static final String TAG_SEED_ACCOUNT_OPTIONS = "seedAccountOptions";
arangelov9b632d72018-12-07 23:21:22 +0000178 private static final String TAG_LAST_REQUEST_QUIET_MODE_ENABLED_CALL =
179 "lastRequestQuietModeEnabledCall";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800180 private static final String ATTR_KEY = "key";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700181 private static final String ATTR_VALUE_TYPE = "type";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800182 private static final String ATTR_MULTIPLE = "m";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700183
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700184 private static final String ATTR_TYPE_STRING_ARRAY = "sa";
185 private static final String ATTR_TYPE_STRING = "s";
186 private static final String ATTR_TYPE_BOOLEAN = "b";
Amith Yamasani5b5aa402014-06-01 20:10:14 -0700187 private static final String ATTR_TYPE_INTEGER = "i";
Fyodor Kupolov262f9952015-03-23 18:55:11 -0700188 private static final String ATTR_TYPE_BUNDLE = "B";
189 private static final String ATTR_TYPE_BUNDLE_ARRAY = "BA";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700190
Amith Yamasani0b285492011-04-14 17:35:23 -0700191 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700192 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700193 private static final String USER_PHOTO_FILENAME = "photo.png";
Adrian Roos1bdff912015-02-17 15:51:35 +0100194 private static final String USER_PHOTO_FILENAME_TMP = USER_PHOTO_FILENAME + ".tmp";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700195
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800196 private static final String RESTRICTIONS_FILE_PREFIX = "res_";
Amith Yamasanifc95e702013-09-26 13:20:17 -0700197 private static final String XML_SUFFIX = ".xml";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800198
Sudheer Shankaf5cea032016-06-08 17:13:24 -0700199 private static final int ALLOWED_FLAGS_FOR_CREATE_USERS_PERMISSION =
200 UserInfo.FLAG_MANAGED_PROFILE
201 | UserInfo.FLAG_EPHEMERAL
202 | UserInfo.FLAG_RESTRICTED
Sudheer Shanka234d1af2016-08-26 15:42:53 -0700203 | UserInfo.FLAG_GUEST
204 | UserInfo.FLAG_DEMO;
Sudheer Shankaf5cea032016-06-08 17:13:24 -0700205
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700206 @VisibleForTesting
207 static final int MIN_USER_ID = 10;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700208 // We need to keep process uid within Integer.MAX_VALUE.
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700209 @VisibleForTesting
210 static final int MAX_USER_ID = Integer.MAX_VALUE / UserHandle.PER_USER_RANGE;
211
212 // Max size of the queue of recently removed users
213 @VisibleForTesting
214 static final int MAX_RECENTLY_REMOVED_IDS_SIZE = 100;
Amith Yamasani634cf312012-10-04 17:34:21 -0700215
Pavel Grafov6a40f092016-10-25 15:46:51 +0100216 private static final int USER_VERSION = 7;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700217
Amith Yamasani920ace02012-09-20 22:15:37 -0700218 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
219
Nicolas Prevotb8186812015-08-06 15:00:03 +0100220 // Maximum number of managed profiles permitted per user is 1. This cannot be increased
Amith Yamasani95ab7842014-08-11 17:09:26 -0700221 // without first making sure that the rest of the framework is prepared for it.
Kenny Guy02c89902016-11-15 19:36:38 +0000222 @VisibleForTesting
223 static final int MAX_MANAGED_PROFILES = 1;
Amith Yamasani95ab7842014-08-11 17:09:26 -0700224
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800225 static final int WRITE_USER_MSG = 1;
226 static final int WRITE_USER_DELAY = 2*1000; // 2 seconds
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530227
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -0800228 // Tron counters
229 private static final String TRON_GUEST_CREATED = "users_guest_created";
230 private static final String TRON_USER_CREATED = "users_user_created";
Christine Franks88220562017-05-24 11:11:21 -0700231 private static final String TRON_DEMO_CREATED = "users_demo_created";
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -0800232
Dianne Hackborn4428e172012-08-24 17:43:05 -0700233 private final Context mContext;
234 private final PackageManagerService mPm;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700235 private final Object mPackagesLock;
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800236 private final UserDataPreparer mUserDataPreparer;
Fyodor Kupolov82402752015-10-28 14:54:51 -0700237 // Short-term lock for internal state, when interaction/sync with PM is not required
Jeff Sharkey5f3e9342017-03-13 14:53:11 -0600238 private final Object mUsersLock = LockGuard.installNewLock(LockGuard.INDEX_USER);
Fyodor Kupolov82402752015-10-28 14:54:51 -0700239 private final Object mRestrictionsLock = new Object();
Fyodor Kupolovd31cee92017-09-05 16:31:08 -0700240 // Used for serializing access to app restriction files
241 private final Object mAppRestrictionsLock = new Object();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700242
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800243 private final Handler mHandler;
244
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700245 private final File mUsersDir;
246 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700247
Svet Ganov9cea80cd2016-02-16 11:47:00 -0800248 private static final IBinder mUserRestriconToken = new Binder();
249
Makoto Onuki068c54a2015-10-13 14:34:03 -0700250 /**
Makoto Onuki73dded22017-12-20 13:14:48 +0900251 * Internal non-parcelable wrapper for UserInfo that is not exposed to other system apps.
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800252 */
Kenny Guy02c89902016-11-15 19:36:38 +0000253 @VisibleForTesting
254 static class UserData {
Amith Yamasani12747872015-12-07 14:19:49 -0800255 // Basic user information and properties
256 UserInfo info;
257 // Account name used when there is a strong association between a user and an account
258 String account;
259 // Account information for seeding into a newly created user. This could also be
260 // used for login validation for an existing user, for updating their credentials.
261 // In the latter case, data may not need to be persisted as it is only valid for the
262 // current login session.
263 String seedAccountName;
264 String seedAccountType;
265 PersistableBundle seedAccountOptions;
266 // Whether to perist the seed account information to be available after a boot
267 boolean persistSeedData;
268
Makoto Onuki73dded22017-12-20 13:14:48 +0900269 /** Elapsed realtime since boot when the user started. */
270 long startRealtime;
271
272 /** Elapsed realtime since boot when the user was unlocked. */
273 long unlockRealtime;
274
arangelov9b632d72018-12-07 23:21:22 +0000275 private long mLastRequestQuietModeEnabledMillis;
276
277 void setLastRequestQuietModeEnabledMillis(long millis) {
278 mLastRequestQuietModeEnabledMillis = millis;
279 }
280
281 long getLastRequestQuietModeEnabledMillis() {
282 return mLastRequestQuietModeEnabledMillis;
283 }
284
Amith Yamasani12747872015-12-07 14:19:49 -0800285 void clearSeedAccountData() {
286 seedAccountName = null;
287 seedAccountType = null;
288 seedAccountOptions = null;
289 persistSeedData = false;
290 }
291 }
292
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800293 @GuardedBy("mUsersLock")
Amith Yamasani12747872015-12-07 14:19:49 -0800294 private final SparseArray<UserData> mUsers = new SparseArray<>();
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800295
296 /**
Makoto Onuki068c54a2015-10-13 14:34:03 -0700297 * User restrictions set via UserManager. This doesn't include restrictions set by
Pavel Grafov6a40f092016-10-25 15:46:51 +0100298 * device owner / profile owners. Only non-empty restriction bundles are stored.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700299 *
300 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
301 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
302 * maybe shared between {@link #mBaseUserRestrictions} and
303 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
304 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700305 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700306 */
307 @GuardedBy("mRestrictionsLock")
308 private final SparseArray<Bundle> mBaseUserRestrictions = new SparseArray<>();
309
310 /**
311 * Cached user restrictions that are in effect -- i.e. {@link #mBaseUserRestrictions} combined
312 * with device / profile owner restrictions. We'll initialize it lazily; use
313 * {@link #getEffectiveUserRestrictions} to access it.
314 *
315 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
316 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
317 * maybe shared between {@link #mBaseUserRestrictions} and
318 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
319 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700320 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700321 */
322 @GuardedBy("mRestrictionsLock")
323 private final SparseArray<Bundle> mCachedEffectiveUserRestrictions = new SparseArray<>();
324
Makoto Onuki4f160732015-10-27 17:15:38 -0700325 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800326 * User restrictions that have already been applied in
327 * {@link #updateUserRestrictionsInternalLR(Bundle, int)}. We use it to detect restrictions
328 * that have changed since the last
329 * {@link #updateUserRestrictionsInternalLR(Bundle, int)} call.
Makoto Onuki4f160732015-10-27 17:15:38 -0700330 */
331 @GuardedBy("mRestrictionsLock")
332 private final SparseArray<Bundle> mAppliedUserRestrictions = new SparseArray<>();
333
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800334 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800335 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
Pavel Grafov6a40f092016-10-25 15:46:51 +0100336 * that should be applied to all users, including guests. Only non-empty restriction bundles are
337 * stored.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800338 */
339 @GuardedBy("mRestrictionsLock")
Pavel Grafov6a40f092016-10-25 15:46:51 +0100340 private final SparseArray<Bundle> mDevicePolicyGlobalUserRestrictions = new SparseArray<>();
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800341
342 /**
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +0100343 * Id of the user that set global restrictions.
344 */
345 @GuardedBy("mRestrictionsLock")
Pavel Grafov6a40f092016-10-25 15:46:51 +0100346 private int mDeviceOwnerUserId = UserHandle.USER_NULL;
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +0100347
348 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800349 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
Pavel Grafov6a40f092016-10-25 15:46:51 +0100350 * for each user. Only non-empty restriction bundles are stored.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800351 */
352 @GuardedBy("mRestrictionsLock")
353 private final SparseArray<Bundle> mDevicePolicyLocalUserRestrictions = new SparseArray<>();
354
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800355 @GuardedBy("mGuestRestrictions")
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530356 private final Bundle mGuestRestrictions = new Bundle();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800357
358 /**
359 * Set of user IDs being actively removed. Removed IDs linger in this set
360 * for several seconds to work around a VFS caching issue.
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700361 * Use {@link #addRemovingUserIdLocked(int)} to add elements to this array
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800362 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700363 @GuardedBy("mUsersLock")
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800364 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700365
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700366 /**
367 * Queue of recently removed userIds. Used for recycling of userIds
368 */
369 @GuardedBy("mUsersLock")
370 private final LinkedList<Integer> mRecentlyRemovedIds = new LinkedList<>();
371
Fyodor Kupolov82402752015-10-28 14:54:51 -0700372 @GuardedBy("mUsersLock")
Amith Yamasani0b285492011-04-14 17:35:23 -0700373 private int[] mUserIds;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800374 @GuardedBy("mPackagesLock")
Amith Yamasani2a003292012-08-14 18:25:45 -0700375 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700376 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700377
Jason Monk62062992014-05-06 09:55:28 -0400378 private IAppOpsService mAppOpsService;
379
Makoto Onuki068c54a2015-10-13 14:34:03 -0700380 private final LocalService mLocalService;
381
Makoto Onukie7927da2015-11-25 10:05:17 -0800382 @GuardedBy("mUsersLock")
383 private boolean mIsDeviceManaged;
384
385 @GuardedBy("mUsersLock")
386 private final SparseBooleanArray mIsUserManaged = new SparseBooleanArray();
387
Makoto Onukid45a4a22015-11-02 17:17:38 -0800388 @GuardedBy("mUserRestrictionsListeners")
389 private final ArrayList<UserRestrictionsListener> mUserRestrictionsListeners =
390 new ArrayList<>();
391
Clara Bayarria1771112015-12-18 16:29:18 +0000392 private final LockPatternUtils mLockPatternUtils;
393
Ricky Waib1dd80b2016-06-07 18:00:55 +0100394 private final String ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK =
395 "com.android.server.pm.DISABLE_QUIET_MODE_AFTER_UNLOCK";
396
397 private final BroadcastReceiver mDisableQuietModeCallback = new BroadcastReceiver() {
398 @Override
399 public void onReceive(Context context, Intent intent) {
Tony Mak64fd8c02017-12-01 19:11:59 +0000400 if (!ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK.equals(intent.getAction())) {
401 return;
Ricky Waib1dd80b2016-06-07 18:00:55 +0100402 }
Tony Mak64fd8c02017-12-01 19:11:59 +0000403 final IntentSender target = intent.getParcelableExtra(Intent.EXTRA_INTENT);
404 final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_ID, UserHandle.USER_NULL);
Fyodor Kupolova68a2862018-01-30 18:22:00 -0800405 // Call setQuietModeEnabled on bg thread to avoid ANR
arangelov9b632d72018-12-07 23:21:22 +0000406 BackgroundThread.getHandler().post(() ->
407 setQuietModeEnabled(userHandle, false, target, /* callingPackage */ null));
Ricky Waib1dd80b2016-06-07 18:00:55 +0100408 }
409 };
410
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +0100411 /**
Tony Mak64fd8c02017-12-01 19:11:59 +0000412 * Start an {@link IntentSender} when user is unlocked after disabling quiet mode.
413 *
Tony Makbece85d2018-01-12 12:10:17 +0000414 * @see {@link #requestQuietModeEnabled(String, boolean, int, IntentSender)}
Tony Mak64fd8c02017-12-01 19:11:59 +0000415 */
416 private class DisableQuietModeUserUnlockedCallback extends IProgressListener.Stub {
417 private final IntentSender mTarget;
418
419 public DisableQuietModeUserUnlockedCallback(IntentSender target) {
420 Preconditions.checkNotNull(target);
421 mTarget = target;
422 }
423
424 @Override
425 public void onStarted(int id, Bundle extras) {}
426
427 @Override
428 public void onProgress(int id, int progress, Bundle extras) {}
429
430 @Override
431 public void onFinished(int id, Bundle extras) {
432 try {
433 mContext.startIntentSender(mTarget, null, 0, 0, 0);
434 } catch (IntentSender.SendIntentException e) {
435 Slog.e(LOG_TAG, "Failed to start the target in the callback", e);
436 }
437 }
438 }
439
440 /**
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +0100441 * Whether all users should be created ephemeral.
442 */
443 @GuardedBy("mUsersLock")
444 private boolean mForceEphemeralUsers;
445
Amith Yamasaniea1b9d72016-05-27 15:57:38 +0000446 @GuardedBy("mUserStates")
447 private final SparseIntArray mUserStates = new SparseIntArray();
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -0700448
Amith Yamasani258848d2012-08-10 17:06:33 -0700449 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700450
Dianne Hackborn4428e172012-08-24 17:43:05 -0700451 public static UserManagerService getInstance() {
452 synchronized (UserManagerService.class) {
453 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700454 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700455 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700456
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700457 public static class LifeCycle extends SystemService {
458
459 private UserManagerService mUms;
460
461 /**
462 * @param context
463 */
464 public LifeCycle(Context context) {
465 super(context);
466 }
467
468 @Override
469 public void onStart() {
470 mUms = UserManagerService.getInstance();
471 publishBinderService(Context.USER_SERVICE, mUms);
472 }
473
474 @Override
475 public void onBootPhase(int phase) {
476 if (phase == SystemService.PHASE_ACTIVITY_MANAGER_READY) {
477 mUms.cleanupPartialUsers();
478 }
479 }
Makoto Onuki73dded22017-12-20 13:14:48 +0900480
481 @Override
482 public void onStartUser(int userHandle) {
483 synchronized (mUms.mUsersLock) {
484 final UserData user = mUms.getUserDataLU(userHandle);
485 if (user != null) {
486 user.startRealtime = SystemClock.elapsedRealtime();
487 }
488 }
489 }
490
491 @Override
492 public void onUnlockUser(int userHandle) {
493 synchronized (mUms.mUsersLock) {
494 final UserData user = mUms.getUserDataLU(userHandle);
495 if (user != null) {
496 user.unlockRealtime = SystemClock.elapsedRealtime();
497 }
498 }
499 }
500
501 @Override
502 public void onStopUser(int userHandle) {
503 synchronized (mUms.mUsersLock) {
504 final UserData user = mUms.getUserDataLU(userHandle);
505 if (user != null) {
506 user.startRealtime = 0;
507 user.unlockRealtime = 0;
508 }
509 }
510 }
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700511 }
512
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700513 // TODO b/28848102 Add support for test dependencies injection
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800514 @VisibleForTesting
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700515 UserManagerService(Context context) {
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800516 this(context, null, null, new Object(), context.getCacheDir());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700517 }
518
Dianne Hackborn4428e172012-08-24 17:43:05 -0700519 /**
520 * Called by package manager to create the service. This is closely
521 * associated with the package manager, and the given lock is the
522 * package manager's own lock.
523 */
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800524 UserManagerService(Context context, PackageManagerService pm, UserDataPreparer userDataPreparer,
525 Object packagesLock) {
526 this(context, pm, userDataPreparer, packagesLock, Environment.getDataDirectory());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700527 }
528
Dianne Hackborn4428e172012-08-24 17:43:05 -0700529 private UserManagerService(Context context, PackageManagerService pm,
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800530 UserDataPreparer userDataPreparer, Object packagesLock, File dataDir) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700531 mContext = context;
532 mPm = pm;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700533 mPackagesLock = packagesLock;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800534 mHandler = new MainHandler();
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800535 mUserDataPreparer = userDataPreparer;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800536 synchronized (mPackagesLock) {
537 mUsersDir = new File(dataDir, USER_INFO_DIR);
538 mUsersDir.mkdirs();
539 // Make zeroth user directory, for services to migrate their files to that location
540 File userZeroDir = new File(mUsersDir, String.valueOf(UserHandle.USER_SYSTEM));
541 userZeroDir.mkdirs();
542 FileUtils.setPermissions(mUsersDir.toString(),
543 FileUtils.S_IRWXU | FileUtils.S_IRWXG | FileUtils.S_IROTH | FileUtils.S_IXOTH,
544 -1, -1);
545 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
546 initDefaultGuestRestrictions();
547 readUserListLP();
548 sInstance = this;
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700549 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700550 mLocalService = new LocalService();
551 LocalServices.addService(UserManagerInternal.class, mLocalService);
Clara Bayarria1771112015-12-18 16:29:18 +0000552 mLockPatternUtils = new LockPatternUtils(mContext);
Amith Yamasaniea1b9d72016-05-27 15:57:38 +0000553 mUserStates.put(UserHandle.USER_SYSTEM, UserState.STATE_BOOTING);
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700554 }
555
556 void systemReady() {
Jason Monk62062992014-05-06 09:55:28 -0400557 mAppOpsService = IAppOpsService.Stub.asInterface(
558 ServiceManager.getService(Context.APP_OPS_SERVICE));
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800559
560 synchronized (mRestrictionsLock) {
561 applyUserRestrictionsLR(UserHandle.USER_SYSTEM);
Jason Monk62062992014-05-06 09:55:28 -0400562 }
Samuel Tand9453b82016-03-14 15:57:02 -0700563
564 UserInfo currentGuestUser = findCurrentGuestUser();
565 if (currentGuestUser != null && !hasUserRestriction(
566 UserManager.DISALLOW_CONFIG_WIFI, currentGuestUser.id)) {
567 // If a guest user currently exists, apply the DISALLOW_CONFIG_WIFI option
568 // to it, in case this guest was created in a previous version where this
569 // user restriction was not a default guest restriction.
570 setUserRestriction(UserManager.DISALLOW_CONFIG_WIFI, true, currentGuestUser.id);
571 }
Amith Yamasanieb437d42016-04-29 09:31:25 -0700572
Ricky Waib1dd80b2016-06-07 18:00:55 +0100573 mContext.registerReceiver(mDisableQuietModeCallback,
574 new IntentFilter(ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK),
575 null, mHandler);
Amith Yamasani258848d2012-08-10 17:06:33 -0700576 }
577
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700578 void cleanupPartialUsers() {
579 // Prune out any partially created, partially removed and ephemeral users.
580 ArrayList<UserInfo> partials = new ArrayList<>();
581 synchronized (mUsersLock) {
582 final int userSize = mUsers.size();
583 for (int i = 0; i < userSize; i++) {
584 UserInfo ui = mUsers.valueAt(i).info;
585 if ((ui.partial || ui.guestToRemove || ui.isEphemeral()) && i != 0) {
586 partials.add(ui);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700587 addRemovingUserIdLocked(ui.id);
Amith Yamasaniae261892016-06-27 10:40:09 -0700588 ui.partial = true;
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700589 }
590 }
591 }
592 final int partialsSize = partials.size();
593 for (int i = 0; i < partialsSize; i++) {
594 UserInfo ui = partials.get(i);
595 Slog.w(LOG_TAG, "Removing partially created user " + ui.id
596 + " (name=" + ui.name + ")");
597 removeUserState(ui.id);
598 }
599 }
600
Amith Yamasani258848d2012-08-10 17:06:33 -0700601 @Override
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800602 public String getUserAccount(int userId) {
603 checkManageUserAndAcrossUsersFullPermission("get user account");
604 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800605 return mUsers.get(userId).account;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800606 }
607 }
608
609 @Override
610 public void setUserAccount(int userId, String accountName) {
611 checkManageUserAndAcrossUsersFullPermission("set user account");
Amith Yamasani12747872015-12-07 14:19:49 -0800612 UserData userToUpdate = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800613 synchronized (mPackagesLock) {
614 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800615 final UserData userData = mUsers.get(userId);
616 if (userData == null) {
617 Slog.e(LOG_TAG, "User not found for setting user account: u" + userId);
618 return;
619 }
620 String currentAccount = userData.account;
Narayan Kamath607223f2018-02-19 14:09:02 +0000621 if (!Objects.equals(currentAccount, accountName)) {
Amith Yamasani12747872015-12-07 14:19:49 -0800622 userData.account = accountName;
623 userToUpdate = userData;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800624 }
625 }
626
627 if (userToUpdate != null) {
628 writeUserLP(userToUpdate);
629 }
630 }
631 }
632
633 @Override
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700634 public UserInfo getPrimaryUser() {
635 checkManageUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700636 synchronized (mUsersLock) {
Amith Yamasani515d4062015-09-28 11:30:06 -0700637 final int userSize = mUsers.size();
638 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800639 UserInfo ui = mUsers.valueAt(i).info;
Xiaohui Chend3e9e182015-11-18 13:37:32 -0800640 if (ui.isPrimary() && !mRemovingUserIds.get(ui.id)) {
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700641 return ui;
642 }
643 }
644 }
645 return null;
646 }
647
648 @Override
Xiaohui Chen594f2082015-08-18 11:04:20 -0700649 public @NonNull List<UserInfo> getUsers(boolean excludeDying) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -0700650 checkManageOrCreateUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700651 synchronized (mUsersLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700652 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasani515d4062015-09-28 11:30:06 -0700653 final int userSize = mUsers.size();
654 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800655 UserInfo ui = mUsers.valueAt(i).info;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700656 if (ui.partial) {
657 continue;
658 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800659 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Amith Yamasani6f48d6e2016-03-23 14:28:25 -0700660 users.add(userWithName(ui));
Amith Yamasani920ace02012-09-20 22:15:37 -0700661 }
Amith Yamasani13593602012-03-22 16:16:17 -0700662 }
663 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700664 }
Amith Yamasani13593602012-03-22 16:16:17 -0700665 }
666
Amith Yamasani258848d2012-08-10 17:06:33 -0700667 @Override
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100668 public List<UserInfo> getProfiles(int userId, boolean enabledOnly) {
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700669 boolean returnFullInfo = true;
Amith Yamasani4f582632014-02-19 14:31:52 -0800670 if (userId != UserHandle.getCallingUserId()) {
Sudheer Shanka74680912016-07-29 11:03:37 -0700671 checkManageOrCreateUsersPermission("getting profiles related to user " + userId);
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700672 } else {
673 returnFullInfo = hasManageUsersPermission();
Amith Yamasani4f582632014-02-19 14:31:52 -0800674 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700675 final long ident = Binder.clearCallingIdentity();
676 try {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700677 synchronized (mUsersLock) {
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700678 return getProfilesLU(userId, enabledOnly, returnFullInfo);
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100679 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700680 } finally {
681 Binder.restoreCallingIdentity(ident);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000682 }
683 }
684
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700685 @Override
686 public int[] getProfileIds(int userId, boolean enabledOnly) {
687 if (userId != UserHandle.getCallingUserId()) {
bohu12d23a12016-09-26 16:20:07 -0700688 checkManageOrCreateUsersPermission("getting profiles related to user " + userId);
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700689 }
690 final long ident = Binder.clearCallingIdentity();
691 try {
692 synchronized (mUsersLock) {
693 return getProfileIdsLU(userId, enabledOnly).toArray();
694 }
695 } finally {
696 Binder.restoreCallingIdentity(ident);
697 }
698 }
699
Amith Yamasanibe465322014-04-24 13:45:17 -0700700 /** Assume permissions already checked and caller's identity cleared */
Andreas Gampe2e8c7672018-07-20 13:01:08 -0700701 @GuardedBy("mUsersLock")
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700702 private List<UserInfo> getProfilesLU(int userId, boolean enabledOnly, boolean fullInfo) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700703 IntArray profileIds = getProfileIdsLU(userId, enabledOnly);
704 ArrayList<UserInfo> users = new ArrayList<>(profileIds.size());
705 for (int i = 0; i < profileIds.size(); i++) {
706 int profileId = profileIds.get(i);
707 UserInfo userInfo = mUsers.get(profileId).info;
708 // If full info is not required - clear PII data to prevent 3P apps from reading it
709 if (!fullInfo) {
710 userInfo = new UserInfo(userInfo);
711 userInfo.name = null;
712 userInfo.iconPath = null;
713 } else {
714 userInfo = userWithName(userInfo);
715 }
716 users.add(userInfo);
717 }
718 return users;
719 }
720
721 /**
722 * Assume permissions already checked and caller's identity cleared
723 */
Andreas Gampe2e8c7672018-07-20 13:01:08 -0700724 @GuardedBy("mUsersLock")
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700725 private IntArray getProfileIdsLU(int userId, boolean enabledOnly) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700726 UserInfo user = getUserInfoLU(userId);
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700727 IntArray result = new IntArray(mUsers.size());
Amith Yamasanidda003f2014-08-28 18:06:51 -0700728 if (user == null) {
729 // Probably a dying user
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700730 return result;
Amith Yamasanidda003f2014-08-28 18:06:51 -0700731 }
Amith Yamasani515d4062015-09-28 11:30:06 -0700732 final int userSize = mUsers.size();
733 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800734 UserInfo profile = mUsers.valueAt(i).info;
Amith Yamasanibe465322014-04-24 13:45:17 -0700735 if (!isProfileOf(user, profile)) {
736 continue;
737 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100738 if (enabledOnly && !profile.isEnabled()) {
739 continue;
Amith Yamasanibe465322014-04-24 13:45:17 -0700740 }
Amith Yamasani70fcf0c2014-07-11 08:40:19 -0700741 if (mRemovingUserIds.get(profile.id)) {
742 continue;
743 }
Tony Mak80189cd2016-04-05 17:21:42 +0100744 if (profile.partial) {
745 continue;
746 }
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700747 result.add(profile.id);
Amith Yamasanibe465322014-04-24 13:45:17 -0700748 }
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700749 return result;
Amith Yamasanibe465322014-04-24 13:45:17 -0700750 }
751
Jessica Hummelbe81c802014-04-22 15:49:22 +0100752 @Override
Andres Moralesc5548c02015-08-05 10:23:12 -0700753 public int getCredentialOwnerProfile(int userHandle) {
754 checkManageUsersPermission("get the credential owner");
Clara Bayarria1771112015-12-18 16:29:18 +0000755 if (!mLockPatternUtils.isSeparateProfileChallengeEnabled(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700756 synchronized (mUsersLock) {
757 UserInfo profileParent = getProfileParentLU(userHandle);
Andres Moralesc5548c02015-08-05 10:23:12 -0700758 if (profileParent != null) {
759 return profileParent.id;
760 }
761 }
762 }
763
764 return userHandle;
765 }
766
767 @Override
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700768 public boolean isSameProfileGroup(int userId, int otherUserId) {
769 if (userId == otherUserId) return true;
770 checkManageUsersPermission("check if in the same profile group");
Fyodor Kupolov0fb772e2016-10-13 16:27:34 -0700771 return isSameProfileGroupNoChecks(userId, otherUserId);
772 }
773
774 private boolean isSameProfileGroupNoChecks(int userId, int otherUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700775 synchronized (mUsersLock) {
776 UserInfo userInfo = getUserInfoLU(userId);
777 if (userInfo == null || userInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
778 return false;
779 }
780 UserInfo otherUserInfo = getUserInfoLU(otherUserId);
781 if (otherUserInfo == null
782 || otherUserInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
783 return false;
784 }
785 return userInfo.profileGroupId == otherUserInfo.profileGroupId;
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700786 }
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700787 }
788
789 @Override
Jessica Hummelbe81c802014-04-22 15:49:22 +0100790 public UserInfo getProfileParent(int userHandle) {
791 checkManageUsersPermission("get the profile parent");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700792 synchronized (mUsersLock) {
793 return getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700794 }
795 }
796
Jakub Pawlowski0f1f5b72017-11-15 14:50:43 -0800797 @Override
798 public int getProfileParentId(int userHandle) {
799 checkManageUsersPermission("get the profile parent");
Sunny Goyal145c8f82018-02-15 14:27:09 -0800800 return mLocalService.getProfileParentId(userHandle);
Jakub Pawlowski0f1f5b72017-11-15 14:50:43 -0800801 }
802
Andreas Gampe2e8c7672018-07-20 13:01:08 -0700803 @GuardedBy("mUsersLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -0700804 private UserInfo getProfileParentLU(int userHandle) {
805 UserInfo profile = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700806 if (profile == null) {
807 return null;
808 }
809 int parentUserId = profile.profileGroupId;
Amith Yamasani801e3422017-01-25 11:35:44 -0800810 if (parentUserId == userHandle || parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700811 return null;
812 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700813 return getUserInfoLU(parentUserId);
Jessica Hummelbe81c802014-04-22 15:49:22 +0100814 }
815 }
816
Fyodor Kupolov82402752015-10-28 14:54:51 -0700817 private static boolean isProfileOf(UserInfo user, UserInfo profile) {
Kenny Guy2a764942014-04-02 13:29:20 +0100818 return user.id == profile.id ||
819 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
820 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000821 }
822
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000823 private void broadcastProfileAvailabilityChanges(UserHandle profileHandle,
Rubin Xuf13c9802016-01-21 18:06:00 +0000824 UserHandle parentHandle, boolean inQuietMode) {
Rubin Xue95057a2016-04-01 16:49:25 +0100825 Intent intent = new Intent();
826 if (inQuietMode) {
827 intent.setAction(Intent.ACTION_MANAGED_PROFILE_UNAVAILABLE);
828 } else {
829 intent.setAction(Intent.ACTION_MANAGED_PROFILE_AVAILABLE);
830 }
Rubin Xuf13c9802016-01-21 18:06:00 +0000831 intent.putExtra(Intent.EXTRA_QUIET_MODE, inQuietMode);
832 intent.putExtra(Intent.EXTRA_USER, profileHandle);
833 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileHandle.getIdentifier());
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000834 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Rubin Xuf13c9802016-01-21 18:06:00 +0000835 mContext.sendBroadcastAsUser(intent, parentHandle);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000836 }
837
838 @Override
Tony Makbece85d2018-01-12 12:10:17 +0000839 public boolean requestQuietModeEnabled(@NonNull String callingPackage, boolean enableQuietMode,
Tony Make3d1f652017-12-12 11:00:37 +0000840 int userHandle, @Nullable IntentSender target) {
841 Preconditions.checkNotNull(callingPackage);
842
Tony Makb7e6fd42017-12-05 19:40:28 +0000843 if (enableQuietMode && target != null) {
844 throw new IllegalArgumentException(
845 "target should only be specified when we are disabling quiet mode.");
846 }
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000847
Tony Makd390ae92017-12-28 13:23:10 +0000848 ensureCanModifyQuietMode(callingPackage, Binder.getCallingUid(), target != null);
Tony Makb7e6fd42017-12-05 19:40:28 +0000849 final long identity = Binder.clearCallingIdentity();
850 try {
arangelov9b632d72018-12-07 23:21:22 +0000851 boolean result = false;
Tony Makb7e6fd42017-12-05 19:40:28 +0000852 if (enableQuietMode) {
arangelov9b632d72018-12-07 23:21:22 +0000853 setQuietModeEnabled(
854 userHandle, true /* enableQuietMode */, target, callingPackage);
855 result = true;
Tony Makb7e6fd42017-12-05 19:40:28 +0000856 } else {
857 boolean needToShowConfirmCredential =
858 mLockPatternUtils.isSecure(userHandle)
859 && !StorageManager.isUserKeyUnlocked(userHandle);
860 if (needToShowConfirmCredential) {
861 showConfirmCredentialToDisableQuietMode(userHandle, target);
Tony Makb7e6fd42017-12-05 19:40:28 +0000862 } else {
arangelov9b632d72018-12-07 23:21:22 +0000863 setQuietModeEnabled(
864 userHandle, false /* enableQuietMode */, target, callingPackage);
865 result = true;
Tony Makb7e6fd42017-12-05 19:40:28 +0000866 }
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000867 }
arangelov9b632d72018-12-07 23:21:22 +0000868 return result;
Tony Makb7e6fd42017-12-05 19:40:28 +0000869 } finally {
870 Binder.restoreCallingIdentity(identity);
871 }
872 }
873
Tony Make3d1f652017-12-12 11:00:37 +0000874 /**
Tony Makd390ae92017-12-28 13:23:10 +0000875 * The caller can modify quiet mode if it meets one of these conditions:
Tony Make3d1f652017-12-12 11:00:37 +0000876 * <ul>
877 * <li>Has system UID or root UID</li>
878 * <li>Has {@link Manifest.permission#MODIFY_QUIET_MODE}</li>
879 * <li>Has {@link Manifest.permission#MANAGE_USERS}</li>
880 * </ul>
Tony Makd390ae92017-12-28 13:23:10 +0000881 * <p>
882 * If caller wants to start an intent after disabling the quiet mode, it must has
883 * {@link Manifest.permission#MANAGE_USERS}.
Tony Make3d1f652017-12-12 11:00:37 +0000884 */
Tony Makd390ae92017-12-28 13:23:10 +0000885 private void ensureCanModifyQuietMode(String callingPackage, int callingUid,
886 boolean startIntent) {
Tony Make3d1f652017-12-12 11:00:37 +0000887 if (hasManageUsersPermission()) {
Tony Makd390ae92017-12-28 13:23:10 +0000888 return;
Tony Make3d1f652017-12-12 11:00:37 +0000889 }
Tony Makd390ae92017-12-28 13:23:10 +0000890 if (startIntent) {
891 throw new SecurityException("MANAGE_USERS permission is required to start intent "
892 + "after disabling quiet mode.");
893 }
jovanakf24ad492018-05-18 12:15:59 -0700894 final boolean hasModifyQuietModePermission = hasPermissionGranted(
895 Manifest.permission.MODIFY_QUIET_MODE, callingUid);
Tony Make3d1f652017-12-12 11:00:37 +0000896 if (hasModifyQuietModePermission) {
Tony Makd390ae92017-12-28 13:23:10 +0000897 return;
Tony Make3d1f652017-12-12 11:00:37 +0000898 }
899
Tony Makd390ae92017-12-28 13:23:10 +0000900 verifyCallingPackage(callingPackage, callingUid);
Tony Make3d1f652017-12-12 11:00:37 +0000901 final ShortcutServiceInternal shortcutInternal =
902 LocalServices.getService(ShortcutServiceInternal.class);
903 if (shortcutInternal != null) {
904 boolean isForegroundLauncher =
905 shortcutInternal.isForegroundDefaultLauncher(callingPackage, callingUid);
906 if (isForegroundLauncher) {
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 throw new SecurityException("Can't modify quiet mode, caller is neither foreground "
911 + "default launcher nor has MANAGE_USERS/MODIFY_QUIET_MODE permission");
Tony Make3d1f652017-12-12 11:00:37 +0000912 }
913
arangelov9b632d72018-12-07 23:21:22 +0000914 private void setQuietModeEnabled(int userHandle, boolean enableQuietMode,
915 IntentSender target, @Nullable String callingPackage) {
Tony Makb7e6fd42017-12-05 19:40:28 +0000916 final UserInfo profile, parent;
917 final UserData profileUserData;
918 synchronized (mUsersLock) {
919 profile = getUserInfoLU(userHandle);
920 parent = getProfileParentLU(userHandle);
921
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000922 if (profile == null || !profile.isManagedProfile()) {
923 throw new IllegalArgumentException("User " + userHandle + " is not a profile");
924 }
Tony Makb7e6fd42017-12-05 19:40:28 +0000925 if (profile.isQuietModeEnabled() == enableQuietMode) {
926 Slog.i(LOG_TAG, "Quiet mode is already " + enableQuietMode);
927 return;
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000928 }
Tony Makb7e6fd42017-12-05 19:40:28 +0000929 profile.flags ^= UserInfo.FLAG_QUIET_MODE;
930 profileUserData = getUserDataLU(profile.id);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000931 }
Tony Makb7e6fd42017-12-05 19:40:28 +0000932 synchronized (mPackagesLock) {
933 writeUserLP(profileUserData);
934 }
935 try {
936 if (enableQuietMode) {
937 ActivityManager.getService().stopUser(userHandle, /* force */true, null);
938 LocalServices.getService(ActivityManagerInternal.class)
939 .killForegroundAppsForUser(userHandle);
940 } else {
941 IProgressListener callback = target != null
942 ? new DisableQuietModeUserUnlockedCallback(target)
943 : null;
944 ActivityManager.getService().startUserInBackgroundWithListener(
945 userHandle, callback);
Rubin Xuf13c9802016-01-21 18:06:00 +0000946 }
arangelov9b632d72018-12-07 23:21:22 +0000947 logQuietModeEnabled(userHandle, enableQuietMode, callingPackage);
Tony Makb7e6fd42017-12-05 19:40:28 +0000948 } catch (RemoteException e) {
949 // Should not happen, same process.
950 e.rethrowAsRuntimeException();
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000951 }
Tony Makb7e6fd42017-12-05 19:40:28 +0000952 broadcastProfileAvailabilityChanges(profile.getUserHandle(), parent.getUserHandle(),
953 enableQuietMode);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000954 }
955
arangelov9b632d72018-12-07 23:21:22 +0000956 private void logQuietModeEnabled(int userHandle, boolean enableQuietMode,
957 @Nullable String callingPackage) {
958 UserData userData;
959 synchronized (mUsersLock) {
960 userData = getUserDataLU(userHandle);
961 }
962 if (userData == null) {
963 return;
964 }
965 final long now = System.currentTimeMillis();
966 final long period = (userData.getLastRequestQuietModeEnabledMillis() != 0L
967 ? now - userData.getLastRequestQuietModeEnabledMillis()
968 : now - userData.info.creationTime);
969 DevicePolicyEventLogger
970 .createEvent(DevicePolicyEnums.REQUEST_QUIET_MODE_ENABLED)
971 .setStrings(callingPackage)
972 .setBoolean(enableQuietMode)
973 .setTimePeriod(period)
974 .write();
975 userData.setLastRequestQuietModeEnabledMillis(now);
976 }
977
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000978 @Override
979 public boolean isQuietModeEnabled(int userHandle) {
980 synchronized (mPackagesLock) {
981 UserInfo info;
982 synchronized (mUsersLock) {
983 info = getUserInfoLU(userHandle);
984 }
985 if (info == null || !info.isManagedProfile()) {
Rubin Xuf13c9802016-01-21 18:06:00 +0000986 return false;
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000987 }
988 return info.isQuietModeEnabled();
989 }
990 }
991
Tony Makb7e6fd42017-12-05 19:40:28 +0000992 /**
993 * Show confirm credential screen to unlock user in order to turn off quiet mode.
994 */
995 private void showConfirmCredentialToDisableQuietMode(
Tony Mak64fd8c02017-12-01 19:11:59 +0000996 @UserIdInt int userHandle, @Nullable IntentSender target) {
Tony Makb7e6fd42017-12-05 19:40:28 +0000997 // otherwise, we show a profile challenge to trigger decryption of the user
998 final KeyguardManager km = (KeyguardManager) mContext.getSystemService(
999 Context.KEYGUARD_SERVICE);
1000 // We should use userHandle not credentialOwnerUserId here, as even if it is unified
1001 // lock, confirm screenlock page will know and show personal challenge, and unlock
1002 // work profile when personal challenge is correct
1003 final Intent unlockIntent = km.createConfirmDeviceCredentialIntent(null, null,
1004 userHandle);
1005 if (unlockIntent == null) {
1006 return;
Benjamin Franzf02420c2016-04-04 18:52:21 +01001007 }
Tony Makb7e6fd42017-12-05 19:40:28 +00001008 final Intent callBackIntent = new Intent(
1009 ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK);
1010 if (target != null) {
1011 callBackIntent.putExtra(Intent.EXTRA_INTENT, target);
Benjamin Franzf02420c2016-04-04 18:52:21 +01001012 }
Tony Makb7e6fd42017-12-05 19:40:28 +00001013 callBackIntent.putExtra(Intent.EXTRA_USER_ID, userHandle);
1014 callBackIntent.setPackage(mContext.getPackageName());
1015 callBackIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1016 final PendingIntent pendingIntent = PendingIntent.getBroadcast(
1017 mContext,
1018 0,
1019 callBackIntent,
1020 PendingIntent.FLAG_CANCEL_CURRENT |
1021 PendingIntent.FLAG_ONE_SHOT |
1022 PendingIntent.FLAG_IMMUTABLE);
1023 // After unlocking the challenge, it will disable quiet mode and run the original
1024 // intentSender
1025 unlockIntent.putExtra(Intent.EXTRA_INTENT, pendingIntent.getIntentSender());
1026 unlockIntent.setFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
1027 mContext.startActivity(unlockIntent);
Benjamin Franzf02420c2016-04-04 18:52:21 +01001028 }
1029
1030 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +01001031 public void setUserEnabled(int userId) {
1032 checkManageUsersPermission("enable user");
1033 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001034 UserInfo info;
1035 synchronized (mUsersLock) {
1036 info = getUserInfoLU(userId);
1037 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +01001038 if (info != null && !info.isEnabled()) {
1039 info.flags ^= UserInfo.FLAG_DISABLED;
Amith Yamasani12747872015-12-07 14:19:49 -08001040 writeUserLP(getUserDataLU(info.id));
Alexandra Gherghinadf35d572014-04-09 13:54:39 +01001041 }
1042 }
1043 }
1044
jovanakf24ad492018-05-18 12:15:59 -07001045 @Override
1046 public void setUserAdmin(int userId) {
1047 checkManageUserAndAcrossUsersFullPermission("set user admin");
1048
1049 synchronized (mPackagesLock) {
1050 UserInfo info;
1051 synchronized (mUsersLock) {
1052 info = getUserInfoLU(userId);
1053 }
1054 if (info == null || info.isAdmin()) {
1055 // Exit if no user found with that id, or the user is already an Admin.
1056 return;
1057 }
1058
1059 info.flags ^= UserInfo.FLAG_ADMIN;
1060 writeUserLP(getUserDataLU(info.id));
1061 }
1062
1063 // Remove non-admin restrictions.
1064 // Keep synchronized with createUserEvenWhenDisallowed.
1065 setUserRestriction(UserManager.DISALLOW_SMS, false, userId);
1066 setUserRestriction(UserManager.DISALLOW_OUTGOING_CALLS, false, userId);
1067 }
1068
Andrew Scull85a63bc2016-10-24 13:47:47 +01001069 /**
1070 * Evicts a user's CE key by stopping and restarting the user.
1071 *
1072 * The key is evicted automatically by the user controller when the user has stopped.
1073 */
1074 @Override
1075 public void evictCredentialEncryptionKey(@UserIdInt int userId) {
1076 checkManageUsersPermission("evict CE key");
1077 final IActivityManager am = ActivityManagerNative.getDefault();
1078 final long identity = Binder.clearCallingIdentity();
1079 try {
1080 am.restartUserInBackground(userId);
1081 } catch (RemoteException re) {
1082 throw re.rethrowAsRuntimeException();
1083 } finally {
1084 Binder.restoreCallingIdentity(identity);
1085 }
1086 }
1087
Alexandra Gherghinadf35d572014-04-09 13:54:39 +01001088 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -07001089 public UserInfo getUserInfo(int userId) {
Sudheer Shankaaccaa082016-06-14 16:22:57 -07001090 checkManageOrCreateUsersPermission("query user");
Tony Mak8673b282016-03-21 21:10:59 +00001091 synchronized (mUsersLock) {
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001092 return userWithName(getUserInfoLU(userId));
1093 }
1094 }
1095
1096 /**
1097 * Returns a UserInfo object with the name filled in, for Owner, or the original
1098 * if the name is already set.
1099 */
1100 private UserInfo userWithName(UserInfo orig) {
1101 if (orig != null && orig.name == null && orig.id == UserHandle.USER_SYSTEM) {
1102 UserInfo withName = new UserInfo(orig);
1103 withName.name = getOwnerName();
1104 return withName;
1105 } else {
1106 return orig;
Tony Mak8673b282016-03-21 21:10:59 +00001107 }
1108 }
1109
1110 @Override
Kenny Guy02c89902016-11-15 19:36:38 +00001111 public int getManagedProfileBadge(@UserIdInt int userId) {
Jon Miranda2b340a22019-01-25 14:03:49 -08001112 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "getManagedProfileBadge");
Kenny Guy02c89902016-11-15 19:36:38 +00001113 synchronized (mUsersLock) {
1114 UserInfo userInfo = getUserInfoLU(userId);
1115 return userInfo != null ? userInfo.profileBadge : 0;
1116 }
1117 }
1118
1119 @Override
Tony Mak8673b282016-03-21 21:10:59 +00001120 public boolean isManagedProfile(int userId) {
Jon Miranda2b340a22019-01-25 14:03:49 -08001121 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isManagedProfile");
Fyodor Kupolov82402752015-10-28 14:54:51 -07001122 synchronized (mUsersLock) {
Amith Yamasani1c41dc82016-06-28 16:13:15 -07001123 UserInfo userInfo = getUserInfoLU(userId);
Tony Mak8673b282016-03-21 21:10:59 +00001124 return userInfo != null && userInfo.isManagedProfile();
Amith Yamasani13593602012-03-22 16:16:17 -07001125 }
1126 }
1127
Amith Yamasani71e6c692013-03-24 17:39:28 -07001128 @Override
Fyodor Kupolovc413f702016-10-06 17:11:14 -07001129 public boolean isUserUnlockingOrUnlocked(int userId) {
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08001130 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isUserUnlockingOrUnlocked");
Fyodor Kupolovc413f702016-10-06 17:11:14 -07001131 return mLocalService.isUserUnlockingOrUnlocked(userId);
1132 }
1133
1134 @Override
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08001135 public boolean isUserUnlocked(int userId) {
1136 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isUserUnlocked");
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07001137 return mLocalService.isUserUnlocked(userId);
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08001138 }
1139
1140 @Override
1141 public boolean isUserRunning(int userId) {
1142 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isUserRunning");
1143 return mLocalService.isUserRunning(userId);
1144 }
1145
Makoto Onuki73dded22017-12-20 13:14:48 +09001146 @Override
Bookatzcde3d922019-03-08 14:30:00 -08001147 public String getUserName() {
1148 if (!hasManageUsersOrPermission(android.Manifest.permission.GET_ACCOUNTS_PRIVILEGED)) {
1149 throw new SecurityException("You need MANAGE_USERS or GET_ACCOUNTS_PRIVILEGED "
1150 + "permissions to: get user name");
1151 }
1152 final int userId = UserHandle.getUserId(Binder.getCallingUid());
1153 synchronized (mUsersLock) {
1154 UserInfo userInfo = userWithName(getUserInfoLU(userId));
1155 return userInfo == null ? "" : userInfo.name;
1156 }
1157 }
1158
1159 @Override
Makoto Onuki73dded22017-12-20 13:14:48 +09001160 public long getUserStartRealtime() {
1161 final int userId = UserHandle.getUserId(Binder.getCallingUid());
1162 synchronized (mUsersLock) {
1163 final UserData user = getUserDataLU(userId);
1164 if (user != null) {
1165 return user.startRealtime;
1166 }
1167 return 0;
1168 }
1169 }
1170
1171 @Override
1172 public long getUserUnlockRealtime() {
1173 synchronized (mUsersLock) {
1174 final UserData user = getUserDataLU(UserHandle.getUserId(Binder.getCallingUid()));
1175 if (user != null) {
1176 return user.unlockRealtime;
1177 }
1178 return 0;
1179 }
1180 }
1181
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08001182 private void checkManageOrInteractPermIfCallerInOtherProfileGroup(int userId, String name) {
1183 int callingUserId = UserHandle.getCallingUserId();
1184 if (callingUserId == userId || isSameProfileGroupNoChecks(callingUserId, userId) ||
1185 hasManageUsersPermission()) {
1186 return;
1187 }
jovanakf24ad492018-05-18 12:15:59 -07001188 if (!hasPermissionGranted(Manifest.permission.INTERACT_ACROSS_USERS,
1189 Binder.getCallingUid())) {
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08001190 throw new SecurityException("You need INTERACT_ACROSS_USERS or MANAGE_USERS permission "
1191 + "to: check " + name);
1192 }
1193 }
1194
1195 @Override
Amith Yamasani1c41dc82016-06-28 16:13:15 -07001196 public boolean isDemoUser(int userId) {
1197 int callingUserId = UserHandle.getCallingUserId();
1198 if (callingUserId != userId && !hasManageUsersPermission()) {
1199 throw new SecurityException("You need MANAGE_USERS permission to query if u=" + userId
1200 + " is a demo user");
1201 }
1202 synchronized (mUsersLock) {
1203 UserInfo userInfo = getUserInfoLU(userId);
1204 return userInfo != null && userInfo.isDemo();
1205 }
1206 }
1207
1208 @Override
Amith Yamasani71e6c692013-03-24 17:39:28 -07001209 public boolean isRestricted() {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001210 synchronized (mUsersLock) {
1211 return getUserInfoLU(UserHandle.getCallingUserId()).isRestricted();
Amith Yamasani71e6c692013-03-24 17:39:28 -07001212 }
1213 }
1214
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001215 @Override
1216 public boolean canHaveRestrictedProfile(int userId) {
1217 checkManageUsersPermission("canHaveRestrictedProfile");
Fyodor Kupolov82402752015-10-28 14:54:51 -07001218 synchronized (mUsersLock) {
1219 final UserInfo userInfo = getUserInfoLU(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001220 if (userInfo == null || !userInfo.canHaveProfile()) {
1221 return false;
1222 }
1223 if (!userInfo.isAdmin()) {
1224 return false;
1225 }
Makoto Onukie7927da2015-11-25 10:05:17 -08001226 // restricted profile can be created if there is no DO set and the admin user has no PO;
1227 return !mIsDeviceManaged && !mIsUserManaged.get(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001228 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001229 }
1230
Fyodor Kupolovca177562017-11-09 17:43:01 -08001231 @Override
1232 public boolean hasRestrictedProfiles() {
1233 checkManageUsersPermission("hasRestrictedProfiles");
1234 final int callingUserId = UserHandle.getCallingUserId();
1235 synchronized (mUsersLock) {
1236 final int userSize = mUsers.size();
1237 for (int i = 0; i < userSize; i++) {
1238 UserInfo profile = mUsers.valueAt(i).info;
1239 if (callingUserId != profile.id
1240 && profile.restrictedProfileParentId == callingUserId) {
1241 return true;
1242 }
1243 }
1244 return false;
1245 }
1246 }
1247
Amith Yamasani195263742012-08-21 15:40:12 -07001248 /*
1249 * Should be locked on mUsers before calling this.
1250 */
Andreas Gampe2e8c7672018-07-20 13:01:08 -07001251 @GuardedBy("mUsersLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001252 private UserInfo getUserInfoLU(int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -08001253 final UserData userData = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -07001254 // If it is partial and not in the process of being removed, return as unknown user.
Amith Yamasani12747872015-12-07 14:19:49 -08001255 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001256 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
1257 return null;
1258 }
Amith Yamasani12747872015-12-07 14:19:49 -08001259 return userData != null ? userData.info : null;
1260 }
1261
Andreas Gampe2e8c7672018-07-20 13:01:08 -07001262 @GuardedBy("mUsersLock")
Amith Yamasani12747872015-12-07 14:19:49 -08001263 private UserData getUserDataLU(int userId) {
1264 final UserData userData = mUsers.get(userId);
1265 // If it is partial and not in the process of being removed, return as unknown user.
1266 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
1267 return null;
1268 }
1269 return userData;
Amith Yamasani195263742012-08-21 15:40:12 -07001270 }
1271
Fyodor Kupolov82402752015-10-28 14:54:51 -07001272 /**
1273 * Obtains {@link #mUsersLock} and return UserInfo from mUsers.
1274 * <p>No permissions checking or any addition checks are made</p>
1275 */
1276 private UserInfo getUserInfoNoChecks(int userId) {
1277 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001278 final UserData userData = mUsers.get(userId);
1279 return userData != null ? userData.info : null;
1280 }
1281 }
1282
1283 /**
1284 * Obtains {@link #mUsersLock} and return UserData from mUsers.
1285 * <p>No permissions checking or any addition checks are made</p>
1286 */
1287 private UserData getUserDataNoChecks(int userId) {
1288 synchronized (mUsersLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001289 return mUsers.get(userId);
1290 }
1291 }
1292
Amith Yamasani236b2b52015-08-18 14:32:14 -07001293 /** Called by PackageManagerService */
Amith Yamasani13593602012-03-22 16:16:17 -07001294 public boolean exists(int userId) {
Todd Kennedy0eb97382017-10-03 16:57:22 -07001295 return mLocalService.exists(userId);
Amith Yamasani13593602012-03-22 16:16:17 -07001296 }
1297
Amith Yamasani258848d2012-08-10 17:06:33 -07001298 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001299 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001300 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001301 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -07001302 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001303 UserData userData = getUserDataNoChecks(userId);
1304 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001305 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
1306 return;
1307 }
Amith Yamasani12747872015-12-07 14:19:49 -08001308 if (name != null && !name.equals(userData.info.name)) {
1309 userData.info.name = name;
1310 writeUserLP(userData);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001311 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -07001312 }
1313 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001314 if (changed) {
Bookatzf9368552019-03-14 11:57:09 -07001315 long ident = Binder.clearCallingIdentity();
1316 try {
1317 sendUserInfoChangedBroadcast(userId);
1318 } finally {
1319 Binder.restoreCallingIdentity(ident);
1320 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001321 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001322 }
1323
Amith Yamasani258848d2012-08-10 17:06:33 -07001324 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001325 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001326 checkManageUsersPermission("update users");
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01001327 if (hasUserRestriction(UserManager.DISALLOW_SET_USER_ICON, userId)) {
1328 Log.w(LOG_TAG, "Cannot set user icon. DISALLOW_SET_USER_ICON is enabled.");
1329 return;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001330 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01001331 mLocalService.setUserIcon(userId, bitmap);
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001332 }
1333
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01001334
1335
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001336 private void sendUserInfoChangedBroadcast(int userId) {
1337 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
1338 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
1339 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -07001340 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001341 }
1342
Amith Yamasani258848d2012-08-10 17:06:33 -07001343 @Override
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001344 public ParcelFileDescriptor getUserIcon(int targetUserId) {
Bookatzcde3d922019-03-08 14:30:00 -08001345 if (!hasManageUsersOrPermission(android.Manifest.permission.GET_ACCOUNTS_PRIVILEGED)) {
1346 throw new SecurityException("You need MANAGE_USERS or GET_ACCOUNTS_PRIVILEGED "
1347 + "permissions to: get user icon");
1348 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001349 String iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001350 synchronized (mPackagesLock) {
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001351 UserInfo targetUserInfo = getUserInfoNoChecks(targetUserId);
1352 if (targetUserInfo == null || targetUserInfo.partial) {
1353 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + targetUserId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001354 return null;
1355 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001356
1357 final int callingUserId = UserHandle.getCallingUserId();
1358 final int callingGroupId = getUserInfoNoChecks(callingUserId).profileGroupId;
1359 final int targetGroupId = targetUserInfo.profileGroupId;
1360 final boolean sameGroup = (callingGroupId != UserInfo.NO_PROFILE_GROUP_ID
1361 && callingGroupId == targetGroupId);
1362 if ((callingUserId != targetUserId) && !sameGroup) {
Nicolas Prevot88cc3462014-05-14 14:51:48 +01001363 checkManageUsersPermission("get the icon of a user who is not related");
1364 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001365
1366 if (targetUserInfo.iconPath == null) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001367 return null;
1368 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001369 iconPath = targetUserInfo.iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001370 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001371
1372 try {
1373 return ParcelFileDescriptor.open(
1374 new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
1375 } catch (FileNotFoundException e) {
1376 Log.e(LOG_TAG, "Couldn't find icon file", e);
1377 }
1378 return null;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001379 }
1380
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001381 public void makeInitialized(int userId) {
1382 checkManageUsersPermission("makeInitialized");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001383 boolean scheduleWriteUser = false;
Amith Yamasani12747872015-12-07 14:19:49 -08001384 UserData userData;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001385 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001386 userData = mUsers.get(userId);
1387 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001388 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001389 return;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001390 }
Amith Yamasani12747872015-12-07 14:19:49 -08001391 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1392 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001393 scheduleWriteUser = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001394 }
1395 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001396 if (scheduleWriteUser) {
Amith Yamasani12747872015-12-07 14:19:49 -08001397 scheduleWriteUser(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001398 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001399 }
1400
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001401 /**
1402 * If default guest restrictions haven't been initialized yet, add the basic
1403 * restrictions.
1404 */
1405 private void initDefaultGuestRestrictions() {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001406 synchronized (mGuestRestrictions) {
1407 if (mGuestRestrictions.isEmpty()) {
Samuel Tand9453b82016-03-14 15:57:02 -07001408 mGuestRestrictions.putBoolean(UserManager.DISALLOW_CONFIG_WIFI, true);
Fyodor Kupolove04462c2015-11-30 15:02:53 -08001409 mGuestRestrictions.putBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, true);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001410 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
1411 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
1412 }
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001413 }
1414 }
1415
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001416 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301417 public Bundle getDefaultGuestRestrictions() {
1418 checkManageUsersPermission("getDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001419 synchronized (mGuestRestrictions) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301420 return new Bundle(mGuestRestrictions);
1421 }
1422 }
1423
1424 @Override
1425 public void setDefaultGuestRestrictions(Bundle restrictions) {
1426 checkManageUsersPermission("setDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001427 synchronized (mGuestRestrictions) {
1428 mGuestRestrictions.clear();
1429 mGuestRestrictions.putAll(restrictions);
1430 }
1431 synchronized (mPackagesLock) {
1432 writeUserListLP();
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301433 }
1434 }
1435
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001436 /**
Pavel Grafov6a40f092016-10-25 15:46:51 +01001437 * See {@link UserManagerInternal#setDevicePolicyUserRestrictions}
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001438 */
Pavel Grafov6a40f092016-10-25 15:46:51 +01001439 private void setDevicePolicyUserRestrictionsInner(int userId, @Nullable Bundle restrictions,
1440 boolean isDeviceOwner, int cameraRestrictionScope) {
1441 final Bundle global = new Bundle();
1442 final Bundle local = new Bundle();
1443
1444 // Sort restrictions into local and global ensuring they don't overlap.
1445 UserRestrictionsUtils.sortToGlobalAndLocal(restrictions, isDeviceOwner,
1446 cameraRestrictionScope, global, local);
1447
1448 boolean globalChanged, localChanged;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001449 synchronized (mRestrictionsLock) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001450 // Update global and local restrictions if they were changed.
1451 globalChanged = updateRestrictionsIfNeededLR(
1452 userId, global, mDevicePolicyGlobalUserRestrictions);
1453 localChanged = updateRestrictionsIfNeededLR(
1454 userId, local, mDevicePolicyLocalUserRestrictions);
1455
1456 if (isDeviceOwner) {
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001457 // Remember the global restriction owner userId to be able to make a distinction
1458 // in getUserRestrictionSource on who set local policies.
Pavel Grafov6a40f092016-10-25 15:46:51 +01001459 mDeviceOwnerUserId = userId;
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001460 } else {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001461 if (mDeviceOwnerUserId == userId) {
Zoltan Szatmary-Ban8a5536d2016-05-27 17:56:44 +01001462 // When profile owner sets restrictions it passes null global bundle and we
1463 // reset global restriction owner userId.
1464 // This means this user used to have DO, but now the DO is gone and the user
1465 // instead has PO.
Pavel Grafov6a40f092016-10-25 15:46:51 +01001466 mDeviceOwnerUserId = UserHandle.USER_NULL;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001467 }
1468 }
1469 }
1470 if (DBG) {
1471 Log.d(LOG_TAG, "setDevicePolicyUserRestrictions: userId=" + userId
1472 + " global=" + global + (globalChanged ? " (changed)" : "")
1473 + " local=" + local + (localChanged ? " (changed)" : "")
1474 );
1475 }
1476 // Don't call them within the mRestrictionsLock.
1477 synchronized (mPackagesLock) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001478 if (localChanged || globalChanged) {
Amith Yamasani12747872015-12-07 14:19:49 -08001479 writeUserLP(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001480 }
1481 }
1482
1483 synchronized (mRestrictionsLock) {
1484 if (globalChanged) {
1485 applyUserRestrictionsForAllUsersLR();
1486 } else if (localChanged) {
1487 applyUserRestrictionsLR(userId);
1488 }
1489 }
1490 }
1491
Pavel Grafov6a40f092016-10-25 15:46:51 +01001492 /**
1493 * Updates restriction bundle for a given user in a given restriction array. If new bundle is
1494 * empty, record is removed from the array.
1495 * @return whether restrictions bundle is different from the old one.
1496 */
1497 private boolean updateRestrictionsIfNeededLR(int userId, @Nullable Bundle restrictions,
1498 SparseArray<Bundle> restrictionsArray) {
1499 final boolean changed =
1500 !UserRestrictionsUtils.areEqual(restrictionsArray.get(userId), restrictions);
1501 if (changed) {
1502 if (!UserRestrictionsUtils.isEmpty(restrictions)) {
1503 restrictionsArray.put(userId, restrictions);
1504 } else {
1505 restrictionsArray.delete(userId);
1506 }
1507 }
1508 return changed;
1509 }
1510
Makoto Onuki068c54a2015-10-13 14:34:03 -07001511 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001512 private Bundle computeEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001513 final Bundle baseRestrictions =
1514 UserRestrictionsUtils.nonNull(mBaseUserRestrictions.get(userId));
Pavel Grafov6a40f092016-10-25 15:46:51 +01001515 final Bundle global = UserRestrictionsUtils.mergeAll(mDevicePolicyGlobalUserRestrictions);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001516 final Bundle local = mDevicePolicyLocalUserRestrictions.get(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001517
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001518 if (UserRestrictionsUtils.isEmpty(global) && UserRestrictionsUtils.isEmpty(local)) {
1519 // Common case first.
1520 return baseRestrictions;
Makoto Onuki068c54a2015-10-13 14:34:03 -07001521 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001522 final Bundle effective = UserRestrictionsUtils.clone(baseRestrictions);
1523 UserRestrictionsUtils.merge(effective, global);
1524 UserRestrictionsUtils.merge(effective, local);
1525
Makoto Onuki068c54a2015-10-13 14:34:03 -07001526 return effective;
1527 }
1528
1529 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001530 private void invalidateEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki068c54a2015-10-13 14:34:03 -07001531 if (DBG) {
1532 Log.d(LOG_TAG, "invalidateEffectiveUserRestrictions userId=" + userId);
1533 }
1534 mCachedEffectiveUserRestrictions.remove(userId);
1535 }
1536
1537 private Bundle getEffectiveUserRestrictions(int userId) {
1538 synchronized (mRestrictionsLock) {
1539 Bundle restrictions = mCachedEffectiveUserRestrictions.get(userId);
1540 if (restrictions == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001541 restrictions = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001542 mCachedEffectiveUserRestrictions.put(userId, restrictions);
1543 }
1544 return restrictions;
Amith Yamasani8cd28b52014-06-08 17:54:27 -07001545 }
1546 }
1547
Makoto Onuki068c54a2015-10-13 14:34:03 -07001548 /** @return a specific user restriction that's in effect currently. */
1549 @Override
1550 public boolean hasUserRestriction(String restrictionKey, int userId) {
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001551 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1552 return false;
1553 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001554 Bundle restrictions = getEffectiveUserRestrictions(userId);
1555 return restrictions != null && restrictions.getBoolean(restrictionKey);
1556 }
1557
Makoto Onukiacc50462018-02-14 14:13:49 -08001558 /** @return if any user has the given restriction. */
1559 @Override
1560 public boolean hasUserRestrictionOnAnyUser(String restrictionKey) {
1561 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1562 return false;
1563 }
1564 final List<UserInfo> users = getUsers(/* excludeDying= */ true);
1565 for (int i = 0; i < users.size(); i++) {
1566 final int userId = users.get(i).id;
1567 Bundle restrictions = getEffectiveUserRestrictions(userId);
1568 if (restrictions != null && restrictions.getBoolean(restrictionKey)) {
1569 return true;
1570 }
1571 }
1572 return false;
1573 }
1574
Makoto Onuki068c54a2015-10-13 14:34:03 -07001575 /**
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001576 * @hide
1577 *
1578 * Returns who set a user restriction on a user.
1579 * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
1580 * @param restrictionKey the string key representing the restriction
1581 * @param userId the id of the user for whom to retrieve the restrictions.
1582 * @return The source of user restriction. Any combination of
1583 * {@link UserManager#RESTRICTION_NOT_SET},
1584 * {@link UserManager#RESTRICTION_SOURCE_SYSTEM},
1585 * {@link UserManager#RESTRICTION_SOURCE_DEVICE_OWNER}
1586 * and {@link UserManager#RESTRICTION_SOURCE_PROFILE_OWNER}
1587 */
1588 @Override
1589 public int getUserRestrictionSource(String restrictionKey, int userId) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001590 List<EnforcingUser> enforcingUsers = getUserRestrictionSources(restrictionKey, userId);
1591 // Get "bitwise or" of restriction sources for all enforcing users.
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001592 int result = UserManager.RESTRICTION_NOT_SET;
Pavel Grafov6a40f092016-10-25 15:46:51 +01001593 for (int i = enforcingUsers.size() - 1; i >= 0; i--) {
1594 result |= enforcingUsers.get(i).getUserRestrictionSource();
1595 }
1596 return result;
1597 }
1598
1599 @Override
1600 public List<EnforcingUser> getUserRestrictionSources(
1601 String restrictionKey, @UserIdInt int userId) {
1602 checkManageUsersPermission("getUserRestrictionSource");
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001603
1604 // Shortcut for the most common case
1605 if (!hasUserRestriction(restrictionKey, userId)) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001606 return Collections.emptyList();
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001607 }
1608
Pavel Grafov6a40f092016-10-25 15:46:51 +01001609 final List<EnforcingUser> result = new ArrayList<>();
1610
1611 // Check if it is base restriction.
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001612 if (hasBaseUserRestriction(restrictionKey, userId)) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001613 result.add(new EnforcingUser(
1614 UserHandle.USER_NULL, UserManager.RESTRICTION_SOURCE_SYSTEM));
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001615 }
1616
Pavel Grafov6a40f092016-10-25 15:46:51 +01001617 synchronized (mRestrictionsLock) {
1618 // Check if it is set by profile owner.
1619 Bundle profileOwnerRestrictions = mDevicePolicyLocalUserRestrictions.get(userId);
1620 if (UserRestrictionsUtils.contains(profileOwnerRestrictions, restrictionKey)) {
1621 result.add(getEnforcingUserLocked(userId));
1622 }
1623
1624 // Iterate over all users who enforce global restrictions.
1625 for (int i = mDevicePolicyGlobalUserRestrictions.size() - 1; i >= 0; i--) {
1626 Bundle globalRestrictions = mDevicePolicyGlobalUserRestrictions.valueAt(i);
1627 int profileUserId = mDevicePolicyGlobalUserRestrictions.keyAt(i);
1628 if (UserRestrictionsUtils.contains(globalRestrictions, restrictionKey)) {
1629 result.add(getEnforcingUserLocked(profileUserId));
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001630 }
1631 }
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001632 }
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001633 return result;
1634 }
1635
Andreas Gampea36dc622018-02-05 17:19:22 -08001636 @GuardedBy("mRestrictionsLock")
Pavel Grafov6a40f092016-10-25 15:46:51 +01001637 private EnforcingUser getEnforcingUserLocked(@UserIdInt int userId) {
1638 int source = mDeviceOwnerUserId == userId ? UserManager.RESTRICTION_SOURCE_DEVICE_OWNER
1639 : UserManager.RESTRICTION_SOURCE_PROFILE_OWNER;
1640 return new EnforcingUser(userId, source);
1641 }
1642
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001643 /**
Makoto Onuki068c54a2015-10-13 14:34:03 -07001644 * @return UserRestrictions that are in effect currently. This always returns a new
1645 * {@link Bundle}.
1646 */
Amith Yamasani8cd28b52014-06-08 17:54:27 -07001647 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001648 public Bundle getUserRestrictions(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001649 return UserRestrictionsUtils.clone(getEffectiveUserRestrictions(userId));
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001650 }
1651
1652 @Override
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +00001653 public boolean hasBaseUserRestriction(String restrictionKey, int userId) {
1654 checkManageUsersPermission("hasBaseUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001655 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1656 return false;
1657 }
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +00001658 synchronized (mRestrictionsLock) {
1659 Bundle bundle = mBaseUserRestrictions.get(userId);
1660 return (bundle != null && bundle.getBoolean(restrictionKey, false));
1661 }
1662 }
1663
1664 @Override
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001665 public void setUserRestriction(String key, boolean value, int userId) {
Fyodor Kupolovd4b26042015-07-27 14:30:59 -07001666 checkManageUsersPermission("setUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001667 if (!UserRestrictionsUtils.isValidRestriction(key)) {
1668 return;
1669 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001670 synchronized (mRestrictionsLock) {
1671 // Note we can't modify Bundles stored in mBaseUserRestrictions directly, so create
1672 // a copy.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001673 final Bundle newRestrictions = UserRestrictionsUtils.clone(
1674 mBaseUserRestrictions.get(userId));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001675 newRestrictions.putBoolean(key, value);
1676
Fyodor Kupolov82402752015-10-28 14:54:51 -07001677 updateUserRestrictionsInternalLR(newRestrictions, userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001678 }
1679 }
1680
Makoto Onuki068c54a2015-10-13 14:34:03 -07001681 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001682 * Optionally updating user restrictions, calculate the effective user restrictions and also
1683 * propagate to other services and system settings.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001684 *
Pavel Grafov6a40f092016-10-25 15:46:51 +01001685 * @param newBaseRestrictions User restrictions to set.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001686 * If null, will not update user restrictions and only does the propagation.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001687 * @param userId target user ID.
1688 */
1689 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001690 private void updateUserRestrictionsInternalLR(
Pavel Grafov6a40f092016-10-25 15:46:51 +01001691 @Nullable Bundle newBaseRestrictions, int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001692 final Bundle prevAppliedRestrictions = UserRestrictionsUtils.nonNull(
1693 mAppliedUserRestrictions.get(userId));
1694
1695 // Update base restrictions.
Pavel Grafov6a40f092016-10-25 15:46:51 +01001696 if (newBaseRestrictions != null) {
1697 // If newBaseRestrictions == the current one, it's probably a bug.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001698 final Bundle prevBaseRestrictions = mBaseUserRestrictions.get(userId);
1699
Pavel Grafov6a40f092016-10-25 15:46:51 +01001700 Preconditions.checkState(prevBaseRestrictions != newBaseRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001701 Preconditions.checkState(mCachedEffectiveUserRestrictions.get(userId)
Pavel Grafov6a40f092016-10-25 15:46:51 +01001702 != newBaseRestrictions);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001703
Pavel Grafov6a40f092016-10-25 15:46:51 +01001704 if (updateRestrictionsIfNeededLR(userId, newBaseRestrictions, mBaseUserRestrictions)) {
Amith Yamasani12747872015-12-07 14:19:49 -08001705 scheduleWriteUser(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001706 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001707 }
1708
Fyodor Kupolov82402752015-10-28 14:54:51 -07001709 final Bundle effective = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001710
Makoto Onuki759a7632015-10-28 16:43:10 -07001711 mCachedEffectiveUserRestrictions.put(userId, effective);
1712
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001713 // Apply the new restrictions.
Makoto Onuki4f160732015-10-27 17:15:38 -07001714 if (DBG) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001715 debug("Applying user restrictions: userId=" + userId
1716 + " new=" + effective + " prev=" + prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001717 }
1718
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001719 if (mAppOpsService != null) { // We skip it until system-ready.
Fyodor Kupolovec30ca32016-06-16 15:09:29 -07001720 mHandler.post(new Runnable() {
1721 @Override
1722 public void run() {
1723 try {
1724 mAppOpsService.setUserRestrictions(effective, mUserRestriconToken, userId);
1725 } catch (RemoteException e) {
1726 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
1727 }
1728 }
1729 });
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001730 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001731
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001732 propagateUserRestrictionsLR(userId, effective, prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001733
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001734 mAppliedUserRestrictions.put(userId, new Bundle(effective));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001735 }
1736
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001737 private void propagateUserRestrictionsLR(final int userId,
Makoto Onukid45a4a22015-11-02 17:17:38 -08001738 Bundle newRestrictions, Bundle prevRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001739 // Note this method doesn't touch any state, meaning it doesn't require mRestrictionsLock
1740 // actually, but we still need some kind of synchronization otherwise we might end up
1741 // calling listeners out-of-order, thus "LR".
1742
1743 if (UserRestrictionsUtils.areEqual(newRestrictions, prevRestrictions)) {
1744 return;
1745 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08001746
1747 final Bundle newRestrictionsFinal = new Bundle(newRestrictions);
1748 final Bundle prevRestrictionsFinal = new Bundle(prevRestrictions);
1749
1750 mHandler.post(new Runnable() {
1751 @Override
1752 public void run() {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07001753 UserRestrictionsUtils.applyUserRestrictions(
1754 mContext, userId, newRestrictionsFinal, prevRestrictionsFinal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001755
Makoto Onukid45a4a22015-11-02 17:17:38 -08001756 final UserRestrictionsListener[] listeners;
1757 synchronized (mUserRestrictionsListeners) {
1758 listeners = new UserRestrictionsListener[mUserRestrictionsListeners.size()];
1759 mUserRestrictionsListeners.toArray(listeners);
1760 }
1761 for (int i = 0; i < listeners.length; i++) {
1762 listeners[i].onUserRestrictionsChanged(userId,
1763 newRestrictionsFinal, prevRestrictionsFinal);
1764 }
Makoto Onukie72f81b2017-03-16 14:08:19 -07001765
1766 final Intent broadcast = new Intent(UserManager.ACTION_USER_RESTRICTIONS_CHANGED)
1767 .setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
1768 mContext.sendBroadcastAsUser(broadcast, UserHandle.of(userId));
Makoto Onukid45a4a22015-11-02 17:17:38 -08001769 }
1770 });
1771 }
1772
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001773 // Package private for the inner class.
Andreas Gampe2e8c7672018-07-20 13:01:08 -07001774 @GuardedBy("mRestrictionsLock")
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001775 void applyUserRestrictionsLR(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001776 updateUserRestrictionsInternalLR(null, userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001777 }
1778
1779 @GuardedBy("mRestrictionsLock")
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001780 // Package private for the inner class.
1781 void applyUserRestrictionsForAllUsersLR() {
1782 if (DBG) {
1783 debug("applyUserRestrictionsForAllUsersLR");
1784 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001785 // First, invalidate all cached values.
Makoto Onuki4f160732015-10-27 17:15:38 -07001786 mCachedEffectiveUserRestrictions.clear();
1787
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001788 // We don't want to call into ActivityManagerService while taking a lock, so we'll call
Makoto Onuki068c54a2015-10-13 14:34:03 -07001789 // it on a handler.
1790 final Runnable r = new Runnable() {
1791 @Override
1792 public void run() {
1793 // Then get the list of running users.
1794 final int[] runningUsers;
1795 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001796 runningUsers = ActivityManager.getService().getRunningUserIds();
Makoto Onuki068c54a2015-10-13 14:34:03 -07001797 } catch (RemoteException e) {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001798 Log.w(LOG_TAG, "Unable to access ActivityManagerService");
Makoto Onuki068c54a2015-10-13 14:34:03 -07001799 return;
1800 }
1801 // Then re-calculate the effective restrictions and apply, only for running users.
1802 // It's okay if a new user has started after the getRunningUserIds() call,
1803 // because we'll do the same thing (re-calculate the restrictions and apply)
1804 // when we start a user.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001805 synchronized (mRestrictionsLock) {
1806 for (int i = 0; i < runningUsers.length; i++) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001807 applyUserRestrictionsLR(runningUsers[i]);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001808 }
1809 }
1810 }
1811 };
1812 mHandler.post(r);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001813 }
1814
Amith Yamasani258848d2012-08-10 17:06:33 -07001815 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001816 * Check if we've hit the limit of how many users can be created.
1817 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001818 private boolean isUserLimitReached() {
1819 int count;
1820 synchronized (mUsersLock) {
1821 count = getAliveUsersExcludingGuestsCountLU();
1822 }
1823 return count >= UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001824 }
1825
1826 @Override
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001827 public boolean canAddMoreManagedProfiles(int userId, boolean allowedToRemoveOne) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001828 checkManageUsersPermission("check if more managed profiles can be added.");
1829 if (ActivityManager.isLowRamDeviceStatic()) {
1830 return false;
1831 }
Fyodor Kupolovb6157992015-06-05 15:32:28 -07001832 if (!mContext.getPackageManager().hasSystemFeature(
1833 PackageManager.FEATURE_MANAGED_USERS)) {
1834 return false;
1835 }
Nicolas Prevotb8186812015-08-06 15:00:03 +01001836 // Limit number of managed profiles that can be created
Benjamin Franzc8776152017-01-06 14:16:41 +00001837 final int managedProfilesCount = getProfiles(userId, false).size() - 1;
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001838 final int profilesRemovedCount = managedProfilesCount > 0 && allowedToRemoveOne ? 1 : 0;
Kenny Guy02c89902016-11-15 19:36:38 +00001839 if (managedProfilesCount - profilesRemovedCount >= getMaxManagedProfiles()) {
Nicolas Prevotb8186812015-08-06 15:00:03 +01001840 return false;
1841 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001842 synchronized(mUsersLock) {
1843 UserInfo userInfo = getUserInfoLU(userId);
yuanhao47f9f7c2017-01-18 09:54:45 +08001844 if (userInfo == null || !userInfo.canHaveProfile()) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001845 return false;
1846 }
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001847 int usersCountAfterRemoving = getAliveUsersExcludingGuestsCountLU()
1848 - profilesRemovedCount;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001849 // We allow creating a managed profile in the special case where there is only one user.
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001850 return usersCountAfterRemoving == 1
1851 || usersCountAfterRemoving < UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001852 }
1853 }
1854
Andreas Gampe2e8c7672018-07-20 13:01:08 -07001855 @GuardedBy("mUsersLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001856 private int getAliveUsersExcludingGuestsCountLU() {
Amith Yamasanif584f012014-05-19 17:57:25 -07001857 int aliveUserCount = 0;
1858 final int totalUserCount = mUsers.size();
1859 // Skip over users being removed
1860 for (int i = 0; i < totalUserCount; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001861 UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov6e99d3f2016-11-01 17:18:41 -07001862 if (!mRemovingUserIds.get(user.id) && !user.isGuest()) {
Amith Yamasanif584f012014-05-19 17:57:25 -07001863 aliveUserCount++;
1864 }
1865 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001866 return aliveUserCount;
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001867 }
1868
1869 /**
Amith Yamasani195263742012-08-21 15:40:12 -07001870 * Enforces that only the system UID or root's UID or apps that have the
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001871 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} and
1872 * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL INTERACT_ACROSS_USERS_FULL}
1873 * permissions can make certain calls to the UserManager.
1874 *
1875 * @param message used as message if SecurityException is thrown
1876 * @throws SecurityException if the caller does not have enough privilege.
1877 */
1878 private static final void checkManageUserAndAcrossUsersFullPermission(String message) {
1879 final int uid = Binder.getCallingUid();
jovanakf24ad492018-05-18 12:15:59 -07001880
1881 if (uid == Process.SYSTEM_UID || uid == 0) {
1882 // System UID or root's UID are granted privilege.
1883 return;
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001884 }
jovanakf24ad492018-05-18 12:15:59 -07001885
1886 if (hasPermissionGranted(Manifest.permission.MANAGE_USERS, uid)
1887 && hasPermissionGranted(Manifest.permission.INTERACT_ACROSS_USERS_FULL, uid)) {
1888 // Apps with both permissions are granted privilege.
1889 return;
1890 }
1891
1892 throw new SecurityException(
1893 "You need MANAGE_USERS and INTERACT_ACROSS_USERS_FULL permission to: " + message);
1894 }
1895
1896 private static boolean hasPermissionGranted(String permission, int uid) {
1897 return ActivityManager.checkComponentPermission(
1898 permission, uid, /* owningUid = */-1, /* exported = */ true) ==
1899 PackageManager.PERMISSION_GRANTED;
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001900 }
1901
1902 /**
1903 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001904 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -07001905 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -07001906 *
1907 * @param message used as message if SecurityException is thrown
1908 * @throws SecurityException if the caller is not system or root
Tony Mak4dc008c2016-03-16 10:46:49 +00001909 * @see #hasManageUsersPermission()
Amith Yamasani258848d2012-08-10 17:06:33 -07001910 */
Amith Yamasanibe465322014-04-24 13:45:17 -07001911 private static final void checkManageUsersPermission(String message) {
Tony Mak4dc008c2016-03-16 10:46:49 +00001912 if (!hasManageUsersPermission()) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001913 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
1914 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -04001915 }
1916
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001917 /**
Sudheer Shankaf5cea032016-06-08 17:13:24 -07001918 * Enforces that only the system UID or root's UID or apps that have the
1919 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or
1920 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS}
1921 * can make certain calls to the UserManager.
1922 *
1923 * @param message used as message if SecurityException is thrown
1924 * @throws SecurityException if the caller is not system or root
1925 * @see #hasManageOrCreateUsersPermission()
1926 */
1927 private static final void checkManageOrCreateUsersPermission(String message) {
1928 if (!hasManageOrCreateUsersPermission()) {
1929 throw new SecurityException(
1930 "You either need MANAGE_USERS or CREATE_USERS permission to: " + message);
1931 }
1932 }
1933
1934 /**
1935 * Similar to {@link #checkManageOrCreateUsersPermission(String)} but when the caller is tries
1936 * to create user/profiles other than what is allowed for
1937 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS} permission, then it will only
1938 * allow callers with {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} permission.
1939 */
1940 private static final void checkManageOrCreateUsersPermission(int creationFlags) {
1941 if ((creationFlags & ~ALLOWED_FLAGS_FOR_CREATE_USERS_PERMISSION) == 0) {
1942 if (!hasManageOrCreateUsersPermission()) {
1943 throw new SecurityException("You either need MANAGE_USERS or CREATE_USERS "
1944 + "permission to create an user with flags: " + creationFlags);
1945 }
1946 } else if (!hasManageUsersPermission()) {
1947 throw new SecurityException("You need MANAGE_USERS permission to create an user "
1948 + " with flags: " + creationFlags);
1949 }
1950 }
1951
1952 /**
Tony Mak4dc008c2016-03-16 10:46:49 +00001953 * @return whether the calling UID is system UID or root's UID or the calling app has the
1954 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}.
1955 */
1956 private static final boolean hasManageUsersPermission() {
1957 final int callingUid = Binder.getCallingUid();
1958 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
1959 || callingUid == Process.ROOT_UID
jovanakf24ad492018-05-18 12:15:59 -07001960 || hasPermissionGranted(android.Manifest.permission.MANAGE_USERS, callingUid);
Tony Mak4dc008c2016-03-16 10:46:49 +00001961 }
1962
1963 /**
Sudheer Shankaf5cea032016-06-08 17:13:24 -07001964 * @return whether the calling UID is system UID or root's UID or the calling app has the
Bookatzcde3d922019-03-08 14:30:00 -08001965 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or the provided permission.
Sudheer Shankaf5cea032016-06-08 17:13:24 -07001966 */
Bookatzcde3d922019-03-08 14:30:00 -08001967 private static final boolean hasManageUsersOrPermission(String alternativePermission) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07001968 final int callingUid = Binder.getCallingUid();
1969 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
1970 || callingUid == Process.ROOT_UID
jovanakf24ad492018-05-18 12:15:59 -07001971 || hasPermissionGranted(android.Manifest.permission.MANAGE_USERS, callingUid)
Bookatzcde3d922019-03-08 14:30:00 -08001972 || hasPermissionGranted(alternativePermission, callingUid);
1973 }
1974
1975 /**
1976 * @return whether the calling UID is system UID or root's UID or the calling app has the
1977 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or
1978 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS}.
1979 */
1980 private static final boolean hasManageOrCreateUsersPermission() {
1981 return hasManageUsersOrPermission(android.Manifest.permission.CREATE_USERS);
Sudheer Shankaf5cea032016-06-08 17:13:24 -07001982 }
1983
1984 /**
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001985 * Enforces that only the system UID or root's UID (on any user) can make certain calls to the
1986 * UserManager.
1987 *
1988 * @param message used as message if SecurityException is thrown
1989 * @throws SecurityException if the caller is not system or root
1990 */
1991 private static void checkSystemOrRoot(String message) {
1992 final int uid = Binder.getCallingUid();
1993 if (!UserHandle.isSameApp(uid, Process.SYSTEM_UID) && uid != Process.ROOT_UID) {
1994 throw new SecurityException("Only system may: " + message);
1995 }
1996 }
1997
Fyodor Kupolov82402752015-10-28 14:54:51 -07001998 private void writeBitmapLP(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001999 try {
2000 File dir = new File(mUsersDir, Integer.toString(info.id));
2001 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +01002002 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002003 if (!dir.exists()) {
2004 dir.mkdir();
2005 FileUtils.setPermissions(
2006 dir.getPath(),
2007 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
2008 -1, -1);
2009 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07002010 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +01002011 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01002012 && tmp.renameTo(file) && SELinux.restorecon(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -07002013 info.iconPath = file.getAbsolutePath();
2014 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07002015 try {
2016 os.close();
2017 } catch (IOException ioe) {
2018 // What the ... !
2019 }
Adrian Roos1bdff912015-02-17 15:51:35 +01002020 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002021 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002022 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002023 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002024 }
2025
Amith Yamasani0b285492011-04-14 17:35:23 -07002026 /**
2027 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
2028 * cache it elsewhere.
2029 * @return the array of user ids.
2030 */
Dianne Hackborn1676c852012-09-10 14:52:30 -07002031 public int[] getUserIds() {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002032 synchronized (mUsersLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07002033 return mUserIds;
2034 }
Amith Yamasani0b285492011-04-14 17:35:23 -07002035 }
2036
Andreas Gampe2e8c7672018-07-20 13:01:08 -07002037 @GuardedBy({"mRestrictionsLock", "mPackagesLock"})
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002038 private void readUserListLP() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002039 if (!mUserListFile.exists()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002040 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002041 return;
2042 }
2043 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07002044 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002045 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07002046 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002047 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002048 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002049 int type;
2050 while ((type = parser.next()) != XmlPullParser.START_TAG
2051 && type != XmlPullParser.END_DOCUMENT) {
Amith Yamasani12747872015-12-07 14:19:49 -08002052 // Skip
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002053 }
2054
2055 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07002056 Slog.e(LOG_TAG, "Unable to read user list");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002057 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002058 return;
2059 }
2060
Amith Yamasani2a003292012-08-14 18:25:45 -07002061 mNextSerialNumber = -1;
2062 if (parser.getName().equals(TAG_USERS)) {
2063 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
2064 if (lastSerialNumber != null) {
2065 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
2066 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07002067 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
2068 if (versionNumber != null) {
2069 mUserVersion = Integer.parseInt(versionNumber);
2070 }
Amith Yamasani2a003292012-08-14 18:25:45 -07002071 }
2072
Pavel Grafov6a40f092016-10-25 15:46:51 +01002073 // Pre-O global user restriction were stored as a single bundle (as opposed to per-user
2074 // currently), take care of it in case of upgrade.
2075 Bundle oldDevicePolicyGlobalUserRestrictions = null;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002076
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002077 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05302078 if (type == XmlPullParser.START_TAG) {
2079 final String name = parser.getName();
2080 if (name.equals(TAG_USER)) {
2081 String id = parser.getAttributeValue(null, ATTR_ID);
Amith Yamasani6f34b412012-10-22 18:19:27 -07002082
Amith Yamasani12747872015-12-07 14:19:49 -08002083 UserData userData = readUserLP(Integer.parseInt(id));
2084
2085 if (userData != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002086 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002087 mUsers.put(userData.info.id, userData);
2088 if (mNextSerialNumber < 0
2089 || mNextSerialNumber <= userData.info.id) {
2090 mNextSerialNumber = userData.info.id + 1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002091 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05302092 }
Amith Yamasani2a003292012-08-14 18:25:45 -07002093 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05302094 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -08002095 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2096 && type != XmlPullParser.END_TAG) {
2097 if (type == XmlPullParser.START_TAG) {
2098 if (parser.getName().equals(TAG_RESTRICTIONS)) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002099 synchronized (mGuestRestrictions) {
Fyodor Kupoloveafee022017-03-15 17:09:04 -07002100 UserRestrictionsUtils
2101 .readRestrictions(parser, mGuestRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002102 }
Amith Yamasanida0b1682014-11-21 12:58:17 -08002103 }
2104 break;
2105 }
2106 }
Pavel Grafov6a40f092016-10-25 15:46:51 +01002107 } else if (name.equals(TAG_DEVICE_OWNER_USER_ID)
2108 // Legacy name, should only be encountered when upgrading from pre-O.
2109 || name.equals(TAG_GLOBAL_RESTRICTION_OWNER_ID)) {
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01002110 String ownerUserId = parser.getAttributeValue(null, ATTR_ID);
2111 if (ownerUserId != null) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01002112 mDeviceOwnerUserId = Integer.parseInt(ownerUserId);
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01002113 }
Pavel Grafov6a40f092016-10-25 15:46:51 +01002114 } else if (name.equals(TAG_DEVICE_POLICY_RESTRICTIONS)) {
2115 // Should only happen when upgrading from pre-O (version < 7).
2116 oldDevicePolicyGlobalUserRestrictions =
2117 UserRestrictionsUtils.readRestrictions(parser);
Amith Yamasani258848d2012-08-10 17:06:33 -07002118 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002119 }
2120 }
Pavel Grafov6a40f092016-10-25 15:46:51 +01002121
Fyodor Kupolov82402752015-10-28 14:54:51 -07002122 updateUserIds();
Pavel Grafov6a40f092016-10-25 15:46:51 +01002123 upgradeIfNecessaryLP(oldDevicePolicyGlobalUserRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002124 } catch (IOException | XmlPullParserException e) {
2125 fallbackToSingleUserLP();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08002126 } finally {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002127 IoUtils.closeQuietly(fis);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002128 }
2129 }
2130
Amith Yamasani6f34b412012-10-22 18:19:27 -07002131 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -08002132 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Pavel Grafov6a40f092016-10-25 15:46:51 +01002133 * @param oldGlobalUserRestrictions Pre-O global device policy restrictions.
Amith Yamasani6f34b412012-10-22 18:19:27 -07002134 */
Andreas Gampe2e8c7672018-07-20 13:01:08 -07002135 @GuardedBy({"mRestrictionsLock", "mPackagesLock"})
Pavel Grafov6a40f092016-10-25 15:46:51 +01002136 private void upgradeIfNecessaryLP(Bundle oldGlobalUserRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002137 final int originalVersion = mUserVersion;
Amith Yamasani6f34b412012-10-22 18:19:27 -07002138 int userVersion = mUserVersion;
2139 if (userVersion < 1) {
2140 // Assign a proper name for the owner, if not initialized correctly before
Amith Yamasani12747872015-12-07 14:19:49 -08002141 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
2142 if ("Primary".equals(userData.info.name)) {
2143 userData.info.name =
2144 mContext.getResources().getString(com.android.internal.R.string.owner_name);
2145 scheduleWriteUser(userData);
Amith Yamasani6f34b412012-10-22 18:19:27 -07002146 }
2147 userVersion = 1;
2148 }
2149
Amith Yamasanibc9625052012-11-15 14:39:18 -08002150 if (userVersion < 2) {
2151 // Owner should be marked as initialized
Amith Yamasani12747872015-12-07 14:19:49 -08002152 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
2153 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
2154 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
2155 scheduleWriteUser(userData);
Amith Yamasanibc9625052012-11-15 14:39:18 -08002156 }
2157 userVersion = 2;
2158 }
2159
Amith Yamasani350962c2013-08-06 11:18:53 -07002160
Amith Yamasani5e486f52013-08-07 11:06:44 -07002161 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -07002162 userVersion = 4;
2163 }
2164
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07002165 if (userVersion < 5) {
2166 initDefaultGuestRestrictions();
2167 userVersion = 5;
2168 }
2169
Fyodor Kupolov1c363152015-09-02 13:27:21 -07002170 if (userVersion < 6) {
2171 final boolean splitSystemUser = UserManager.isSplitSystemUser();
Fyodor Kupolov82402752015-10-28 14:54:51 -07002172 synchronized (mUsersLock) {
2173 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002174 UserData userData = mUsers.valueAt(i);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002175 // In non-split mode, only user 0 can have restricted profiles
Amith Yamasani12747872015-12-07 14:19:49 -08002176 if (!splitSystemUser && userData.info.isRestricted()
2177 && (userData.info.restrictedProfileParentId
2178 == UserInfo.NO_PROFILE_GROUP_ID)) {
2179 userData.info.restrictedProfileParentId = UserHandle.USER_SYSTEM;
2180 scheduleWriteUser(userData);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002181 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07002182 }
2183 }
2184 userVersion = 6;
2185 }
2186
Pavel Grafov6a40f092016-10-25 15:46:51 +01002187 if (userVersion < 7) {
2188 // Previously only one user could enforce global restrictions, now it is per-user.
2189 synchronized (mRestrictionsLock) {
2190 if (!UserRestrictionsUtils.isEmpty(oldGlobalUserRestrictions)
2191 && mDeviceOwnerUserId != UserHandle.USER_NULL) {
2192 mDevicePolicyGlobalUserRestrictions.put(
2193 mDeviceOwnerUserId, oldGlobalUserRestrictions);
2194 }
2195 // ENSURE_VERIFY_APPS is now enforced globally even if put by profile owner, so move
2196 // it from local to global bundle for all users who set it.
2197 UserRestrictionsUtils.moveRestriction(UserManager.ENSURE_VERIFY_APPS,
2198 mDevicePolicyLocalUserRestrictions, mDevicePolicyGlobalUserRestrictions
2199 );
2200 }
2201 userVersion = 7;
2202 }
2203
Amith Yamasani6f34b412012-10-22 18:19:27 -07002204 if (userVersion < USER_VERSION) {
2205 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
2206 + USER_VERSION);
2207 } else {
2208 mUserVersion = userVersion;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002209
2210 if (originalVersion < mUserVersion) {
2211 writeUserListLP();
2212 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07002213 }
2214 }
2215
Andreas Gampe2e8c7672018-07-20 13:01:08 -07002216 @GuardedBy({"mPackagesLock", "mRestrictionsLock"})
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002217 private void fallbackToSingleUserLP() {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07002218 int flags = UserInfo.FLAG_INITIALIZED;
2219 // In split system user mode, the admin and primary flags are assigned to the first human
2220 // user.
2221 if (!UserManager.isSplitSystemUser()) {
2222 flags |= UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY;
2223 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -07002224 // Create the system user
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07002225 UserInfo system = new UserInfo(UserHandle.USER_SYSTEM, null, null, flags);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002226 UserData userData = putUserInfo(system);
Amith Yamasani634cf312012-10-04 17:34:21 -07002227 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -04002228 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -08002229
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05002230 Bundle restrictions = new Bundle();
Mahaver Chopra3d9805d2016-07-07 16:25:05 +01002231 try {
2232 final String[] defaultFirstUserRestrictions = mContext.getResources().getStringArray(
2233 com.android.internal.R.array.config_defaultFirstUserRestrictions);
2234 for (String userRestriction : defaultFirstUserRestrictions) {
2235 if (UserRestrictionsUtils.isValidRestriction(userRestriction)) {
2236 restrictions.putBoolean(userRestriction, true);
2237 }
2238 }
2239 } catch (Resources.NotFoundException e) {
2240 Log.e(LOG_TAG, "Couldn't find resource: config_defaultFirstUserRestrictions", e);
2241 }
2242
Pavel Grafov6a40f092016-10-25 15:46:51 +01002243 if (!restrictions.isEmpty()) {
2244 synchronized (mRestrictionsLock) {
2245 mBaseUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions);
2246 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07002247 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08002248
Fyodor Kupolov82402752015-10-28 14:54:51 -07002249 updateUserIds();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07002250 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002251
Amith Yamasani12747872015-12-07 14:19:49 -08002252 writeUserLP(userData);
Jeff Sharkeycd575992016-03-29 14:12:49 -06002253 writeUserListLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002254 }
2255
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07002256 private String getOwnerName() {
2257 return mContext.getResources().getString(com.android.internal.R.string.owner_name);
2258 }
2259
Amith Yamasani12747872015-12-07 14:19:49 -08002260 private void scheduleWriteUser(UserData UserData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002261 if (DBG) {
2262 debug("scheduleWriteUser");
2263 }
Makoto Onuki9e935a32015-11-06 14:24:24 -08002264 // No need to wrap it within a lock -- worst case, we'll just post the same message
2265 // twice.
Amith Yamasani12747872015-12-07 14:19:49 -08002266 if (!mHandler.hasMessages(WRITE_USER_MSG, UserData)) {
2267 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, UserData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002268 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
2269 }
2270 }
2271
Amith Yamasani12747872015-12-07 14:19:49 -08002272 private void writeUserLP(UserData userData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002273 if (DBG) {
Amith Yamasani12747872015-12-07 14:19:49 -08002274 debug("writeUserLP " + userData);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002275 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002276 FileOutputStream fos = null;
Amith Yamasani12747872015-12-07 14:19:49 -08002277 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userData.info.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002278 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07002279 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002280 final BufferedOutputStream bos = new BufferedOutputStream(fos);
Kenny Guy02c89902016-11-15 19:36:38 +00002281 writeUserLP(userData, bos);
Amith Yamasani2a003292012-08-14 18:25:45 -07002282 userFile.finishWrite(fos);
2283 } catch (Exception ioe) {
Jeff Sharkeycd575992016-03-29 14:12:49 -06002284 Slog.e(LOG_TAG, "Error writing user info " + userData.info.id, ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -07002285 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002286 }
2287 }
2288
2289 /*
Kenny Guy02c89902016-11-15 19:36:38 +00002290 * Writes the user file in this format:
2291 *
2292 * <user flags="20039023" id="0">
2293 * <name>Primary</name>
2294 * </user>
2295 */
2296 @VisibleForTesting
2297 void writeUserLP(UserData userData, OutputStream os)
2298 throws IOException, XmlPullParserException {
2299 // XmlSerializer serializer = XmlUtils.serializerInstance();
2300 final XmlSerializer serializer = new FastXmlSerializer();
2301 serializer.setOutput(os, StandardCharsets.UTF_8.name());
2302 serializer.startDocument(null, true);
2303 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2304
2305 final UserInfo userInfo = userData.info;
2306 serializer.startTag(null, TAG_USER);
2307 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
2308 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
2309 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
2310 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
2311 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
2312 Long.toString(userInfo.lastLoggedInTime));
2313 if (userInfo.lastLoggedInFingerprint != null) {
2314 serializer.attribute(null, ATTR_LAST_LOGGED_IN_FINGERPRINT,
2315 userInfo.lastLoggedInFingerprint);
2316 }
2317 if (userInfo.iconPath != null) {
2318 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
2319 }
2320 if (userInfo.partial) {
2321 serializer.attribute(null, ATTR_PARTIAL, "true");
2322 }
2323 if (userInfo.guestToRemove) {
2324 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
2325 }
2326 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
2327 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
2328 Integer.toString(userInfo.profileGroupId));
2329 }
2330 serializer.attribute(null, ATTR_PROFILE_BADGE,
2331 Integer.toString(userInfo.profileBadge));
2332 if (userInfo.restrictedProfileParentId != UserInfo.NO_PROFILE_GROUP_ID) {
2333 serializer.attribute(null, ATTR_RESTRICTED_PROFILE_PARENT_ID,
2334 Integer.toString(userInfo.restrictedProfileParentId));
2335 }
2336 // Write seed data
2337 if (userData.persistSeedData) {
2338 if (userData.seedAccountName != null) {
2339 serializer.attribute(null, ATTR_SEED_ACCOUNT_NAME, userData.seedAccountName);
2340 }
2341 if (userData.seedAccountType != null) {
2342 serializer.attribute(null, ATTR_SEED_ACCOUNT_TYPE, userData.seedAccountType);
2343 }
2344 }
2345 if (userInfo.name != null) {
2346 serializer.startTag(null, TAG_NAME);
2347 serializer.text(userInfo.name);
2348 serializer.endTag(null, TAG_NAME);
2349 }
2350 synchronized (mRestrictionsLock) {
2351 UserRestrictionsUtils.writeRestrictions(serializer,
2352 mBaseUserRestrictions.get(userInfo.id), TAG_RESTRICTIONS);
2353 UserRestrictionsUtils.writeRestrictions(serializer,
2354 mDevicePolicyLocalUserRestrictions.get(userInfo.id),
2355 TAG_DEVICE_POLICY_RESTRICTIONS);
Pavel Grafov6a40f092016-10-25 15:46:51 +01002356 UserRestrictionsUtils.writeRestrictions(serializer,
2357 mDevicePolicyGlobalUserRestrictions.get(userInfo.id),
2358 TAG_DEVICE_POLICY_GLOBAL_RESTRICTIONS);
Kenny Guy02c89902016-11-15 19:36:38 +00002359 }
2360
2361 if (userData.account != null) {
2362 serializer.startTag(null, TAG_ACCOUNT);
2363 serializer.text(userData.account);
2364 serializer.endTag(null, TAG_ACCOUNT);
2365 }
2366
2367 if (userData.persistSeedData && userData.seedAccountOptions != null) {
2368 serializer.startTag(null, TAG_SEED_ACCOUNT_OPTIONS);
2369 userData.seedAccountOptions.saveToXml(serializer);
2370 serializer.endTag(null, TAG_SEED_ACCOUNT_OPTIONS);
2371 }
2372
arangelov9b632d72018-12-07 23:21:22 +00002373 if (userData.getLastRequestQuietModeEnabledMillis() != 0L) {
2374 serializer.startTag(/* namespace */ null, TAG_LAST_REQUEST_QUIET_MODE_ENABLED_CALL);
2375 serializer.text(String.valueOf(userData.getLastRequestQuietModeEnabledMillis()));
2376 serializer.endTag(/* namespace */ null, TAG_LAST_REQUEST_QUIET_MODE_ENABLED_CALL);
2377 }
2378
Kenny Guy02c89902016-11-15 19:36:38 +00002379 serializer.endTag(null, TAG_USER);
2380
2381 serializer.endDocument();
2382 }
2383
2384 /*
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002385 * Writes the user list file in this format:
2386 *
Amith Yamasani2a003292012-08-14 18:25:45 -07002387 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002388 * <user id="0"></user>
2389 * <user id="2"></user>
2390 * </users>
2391 */
Andreas Gampe2e8c7672018-07-20 13:01:08 -07002392 @GuardedBy({"mRestrictionsLock", "mPackagesLock"})
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002393 private void writeUserListLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002394 if (DBG) {
2395 debug("writeUserList");
2396 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002397 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07002398 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002399 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07002400 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002401 final BufferedOutputStream bos = new BufferedOutputStream(fos);
2402
2403 // XmlSerializer serializer = XmlUtils.serializerInstance();
2404 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002405 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002406 serializer.startDocument(null, true);
2407 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2408
2409 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -07002410 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -07002411 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002412
Adam Lesinskieddeb492014-09-08 17:50:03 -07002413 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002414 synchronized (mGuestRestrictions) {
2415 UserRestrictionsUtils
2416 .writeRestrictions(serializer, mGuestRestrictions, TAG_RESTRICTIONS);
2417 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05302418 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Pavel Grafov6a40f092016-10-25 15:46:51 +01002419 serializer.startTag(null, TAG_DEVICE_OWNER_USER_ID);
2420 serializer.attribute(null, ATTR_ID, Integer.toString(mDeviceOwnerUserId));
2421 serializer.endTag(null, TAG_DEVICE_OWNER_USER_ID);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002422 int[] userIdsToWrite;
2423 synchronized (mUsersLock) {
2424 userIdsToWrite = new int[mUsers.size()];
2425 for (int i = 0; i < userIdsToWrite.length; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002426 UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002427 userIdsToWrite[i] = user.id;
2428 }
2429 }
2430 for (int id : userIdsToWrite) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002431 serializer.startTag(null, TAG_USER);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002432 serializer.attribute(null, ATTR_ID, Integer.toString(id));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002433 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002434 }
2435
2436 serializer.endTag(null, TAG_USERS);
2437
2438 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07002439 userListFile.finishWrite(fos);
2440 } catch (Exception e) {
2441 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -07002442 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002443 }
2444 }
2445
Amith Yamasani12747872015-12-07 14:19:49 -08002446 private UserData readUserLP(int id) {
Kenny Guy02c89902016-11-15 19:36:38 +00002447 FileInputStream fis = null;
2448 try {
2449 AtomicFile userFile =
2450 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
2451 fis = userFile.openRead();
2452 return readUserLP(id, fis);
2453 } catch (IOException ioe) {
2454 Slog.e(LOG_TAG, "Error reading user list");
2455 } catch (XmlPullParserException pe) {
2456 Slog.e(LOG_TAG, "Error reading user list");
2457 } finally {
2458 IoUtils.closeQuietly(fis);
2459 }
2460 return null;
2461 }
2462
2463 @VisibleForTesting
2464 UserData readUserLP(int id, InputStream is) throws IOException,
2465 XmlPullParserException {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002466 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -07002467 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002468 String name = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -08002469 String account = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002470 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -07002471 long creationTime = 0L;
2472 long lastLoggedInTime = 0L;
arangelov9b632d72018-12-07 23:21:22 +00002473 long lastRequestQuietModeEnabledTimestamp = 0L;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002474 String lastLoggedInFingerprint = null;
Kenny Guy2a764942014-04-02 13:29:20 +01002475 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Kenny Guy02c89902016-11-15 19:36:38 +00002476 int profileBadge = 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002477 int restrictedProfileParentId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002478 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -07002479 boolean guestToRemove = false;
Amith Yamasani12747872015-12-07 14:19:49 -08002480 boolean persistSeedData = false;
2481 String seedAccountName = null;
2482 String seedAccountType = null;
2483 PersistableBundle seedAccountOptions = null;
Pavel Grafov6a40f092016-10-25 15:46:51 +01002484 Bundle baseRestrictions = null;
2485 Bundle localRestrictions = null;
2486 Bundle globalRestrictions = null;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002487
Kenny Guy02c89902016-11-15 19:36:38 +00002488 XmlPullParser parser = Xml.newPullParser();
2489 parser.setInput(is, StandardCharsets.UTF_8.name());
2490 int type;
2491 while ((type = parser.next()) != XmlPullParser.START_TAG
2492 && type != XmlPullParser.END_DOCUMENT) {
2493 // Skip
2494 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002495
Kenny Guy02c89902016-11-15 19:36:38 +00002496 if (type != XmlPullParser.START_TAG) {
2497 Slog.e(LOG_TAG, "Unable to read user " + id);
2498 return null;
2499 }
2500
2501 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
2502 int storedId = readIntAttribute(parser, ATTR_ID, -1);
2503 if (storedId != id) {
2504 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002505 return null;
2506 }
Kenny Guy02c89902016-11-15 19:36:38 +00002507 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
2508 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
2509 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
2510 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
2511 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
2512 lastLoggedInFingerprint = parser.getAttributeValue(null,
2513 ATTR_LAST_LOGGED_IN_FINGERPRINT);
2514 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
2515 UserInfo.NO_PROFILE_GROUP_ID);
2516 profileBadge = readIntAttribute(parser, ATTR_PROFILE_BADGE, 0);
2517 restrictedProfileParentId = readIntAttribute(parser,
2518 ATTR_RESTRICTED_PROFILE_PARENT_ID, UserInfo.NO_PROFILE_GROUP_ID);
2519 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
2520 if ("true".equals(valueString)) {
2521 partial = true;
2522 }
2523 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
2524 if ("true".equals(valueString)) {
2525 guestToRemove = true;
2526 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002527
Kenny Guy02c89902016-11-15 19:36:38 +00002528 seedAccountName = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_NAME);
2529 seedAccountType = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_TYPE);
2530 if (seedAccountName != null || seedAccountType != null) {
2531 persistSeedData = true;
2532 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002533
Kenny Guy02c89902016-11-15 19:36:38 +00002534 int outerDepth = parser.getDepth();
2535 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2536 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2537 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2538 continue;
2539 }
2540 String tag = parser.getName();
2541 if (TAG_NAME.equals(tag)) {
2542 type = parser.next();
2543 if (type == XmlPullParser.TEXT) {
2544 name = parser.getText();
2545 }
2546 } else if (TAG_RESTRICTIONS.equals(tag)) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01002547 baseRestrictions = UserRestrictionsUtils.readRestrictions(parser);
Kenny Guy02c89902016-11-15 19:36:38 +00002548 } else if (TAG_DEVICE_POLICY_RESTRICTIONS.equals(tag)) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01002549 localRestrictions = UserRestrictionsUtils.readRestrictions(parser);
2550 } else if (TAG_DEVICE_POLICY_GLOBAL_RESTRICTIONS.equals(tag)) {
2551 globalRestrictions = UserRestrictionsUtils.readRestrictions(parser);
Kenny Guy02c89902016-11-15 19:36:38 +00002552 } else if (TAG_ACCOUNT.equals(tag)) {
2553 type = parser.next();
2554 if (type == XmlPullParser.TEXT) {
2555 account = parser.getText();
2556 }
2557 } else if (TAG_SEED_ACCOUNT_OPTIONS.equals(tag)) {
2558 seedAccountOptions = PersistableBundle.restoreFromXml(parser);
Amith Yamasani12747872015-12-07 14:19:49 -08002559 persistSeedData = true;
arangelov9b632d72018-12-07 23:21:22 +00002560 } else if (TAG_LAST_REQUEST_QUIET_MODE_ENABLED_CALL.equals(tag)) {
2561 type = parser.next();
2562 if (type == XmlPullParser.TEXT) {
2563 lastRequestQuietModeEnabledTimestamp = Long.parseLong(parser.getText());
2564 }
Amith Yamasani12747872015-12-07 14:19:49 -08002565 }
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08002566 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002567 }
Kenny Guy02c89902016-11-15 19:36:38 +00002568
2569 // Create the UserInfo object that gets passed around
2570 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
2571 userInfo.serialNumber = serialNumber;
2572 userInfo.creationTime = creationTime;
2573 userInfo.lastLoggedInTime = lastLoggedInTime;
2574 userInfo.lastLoggedInFingerprint = lastLoggedInFingerprint;
2575 userInfo.partial = partial;
2576 userInfo.guestToRemove = guestToRemove;
2577 userInfo.profileGroupId = profileGroupId;
2578 userInfo.profileBadge = profileBadge;
2579 userInfo.restrictedProfileParentId = restrictedProfileParentId;
2580
2581 // Create the UserData object that's internal to this class
2582 UserData userData = new UserData();
2583 userData.info = userInfo;
2584 userData.account = account;
2585 userData.seedAccountName = seedAccountName;
2586 userData.seedAccountType = seedAccountType;
2587 userData.persistSeedData = persistSeedData;
2588 userData.seedAccountOptions = seedAccountOptions;
arangelov9b632d72018-12-07 23:21:22 +00002589 userData.setLastRequestQuietModeEnabledMillis(lastRequestQuietModeEnabledTimestamp);
Kenny Guy02c89902016-11-15 19:36:38 +00002590
2591 synchronized (mRestrictionsLock) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01002592 if (baseRestrictions != null) {
2593 mBaseUserRestrictions.put(id, baseRestrictions);
2594 }
2595 if (localRestrictions != null) {
2596 mDevicePolicyLocalUserRestrictions.put(id, localRestrictions);
2597 }
2598 if (globalRestrictions != null) {
2599 mDevicePolicyGlobalUserRestrictions.put(id, globalRestrictions);
2600 }
Kenny Guy02c89902016-11-15 19:36:38 +00002601 }
2602 return userData;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002603 }
2604
Amith Yamasani920ace02012-09-20 22:15:37 -07002605 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
2606 String valueString = parser.getAttributeValue(null, attr);
2607 if (valueString == null) return defaultValue;
2608 try {
2609 return Integer.parseInt(valueString);
2610 } catch (NumberFormatException nfe) {
2611 return defaultValue;
2612 }
2613 }
2614
2615 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
2616 String valueString = parser.getAttributeValue(null, attr);
2617 if (valueString == null) return defaultValue;
2618 try {
2619 return Long.parseLong(valueString);
2620 } catch (NumberFormatException nfe) {
2621 return defaultValue;
2622 }
2623 }
2624
Amith Yamasanib82add22013-07-09 11:24:44 -07002625 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002626 * Removes the app restrictions file for a specific package and user id, if it exists.
2627 */
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07002628 private static void cleanAppRestrictionsForPackageLAr(String pkg, int userId) {
2629 File dir = Environment.getUserSystemDirectory(userId);
2630 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
2631 if (resFile.exists()) {
2632 resFile.delete();
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002633 }
2634 }
2635
Kenny Guya52dc3e2014-02-11 15:33:14 +00002636 @Override
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002637 public UserInfo createProfileForUser(String name, int flags, int userId,
2638 String[] disallowedPackages) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002639 checkManageOrCreateUsersPermission(flags);
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002640 return createUserInternal(name, flags, userId, disallowedPackages);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002641 }
2642
Amith Yamasani258848d2012-08-10 17:06:33 -07002643 @Override
Tony Mak6dc428f2016-10-10 15:48:27 +01002644 public UserInfo createProfileForUserEvenWhenDisallowed(String name, int flags, int userId,
2645 String[] disallowedPackages) {
2646 checkManageOrCreateUsersPermission(flags);
2647 return createUserInternalUnchecked(name, flags, userId, disallowedPackages);
2648 }
2649
2650 @Override
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00002651 public boolean removeUserEvenWhenDisallowed(@UserIdInt int userHandle) {
2652 checkManageOrCreateUsersPermission("Only the system can remove users");
2653 return removeUserUnchecked(userHandle);
2654 }
2655
2656 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07002657 public UserInfo createUser(String name, int flags) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002658 checkManageOrCreateUsersPermission(flags);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00002659 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002660 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07002661
Jessica Hummelbe81c802014-04-22 15:49:22 +01002662 private UserInfo createUserInternal(String name, int flags, int parentId) {
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002663 return createUserInternal(name, flags, parentId, null);
2664 }
2665
2666 private UserInfo createUserInternal(String name, int flags, int parentId,
2667 String[] disallowedPackages) {
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002668 String restriction = ((flags & UserInfo.FLAG_MANAGED_PROFILE) != 0)
2669 ? UserManager.DISALLOW_ADD_MANAGED_PROFILE
2670 : UserManager.DISALLOW_ADD_USER;
2671 if (hasUserRestriction(restriction, UserHandle.getCallingUserId())) {
2672 Log.w(LOG_TAG, "Cannot add user. " + restriction + " is enabled.");
Julia Reynolds75175022014-06-26 16:35:00 -04002673 return null;
2674 }
Tony Mak6dc428f2016-10-10 15:48:27 +01002675 return createUserInternalUnchecked(name, flags, parentId, disallowedPackages);
2676 }
2677
2678 private UserInfo createUserInternalUnchecked(String name, int flags, int parentId,
2679 String[] disallowedPackages) {
Suprabh Shuklac5e057c2016-08-08 16:22:44 -07002680 DeviceStorageMonitorInternal dsm = LocalServices
2681 .getService(DeviceStorageMonitorInternal.class);
2682 if (dsm.isMemoryLow()) {
2683 Log.w(LOG_TAG, "Cannot add user. Not enough space on disk.");
2684 return null;
2685 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07002686 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Nicolas Prevot12678a92015-05-13 12:15:03 -07002687 final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002688 final boolean isRestricted = (flags & UserInfo.FLAG_RESTRICTED) != 0;
Amith Yamasani52c21e32016-05-31 09:12:20 -07002689 final boolean isDemo = (flags & UserInfo.FLAG_DEMO) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002690 final long ident = Binder.clearCallingIdentity();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002691 UserInfo userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08002692 UserData userData;
Amith Yamasanibb054c92015-07-09 14:16:27 -07002693 final int userId;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002694 try {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002695 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002696 UserData parent = null;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002697 if (parentId != UserHandle.USER_NULL) {
2698 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002699 parent = getUserDataLU(parentId);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00002700 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002701 if (parent == null) return null;
2702 }
2703 if (isManagedProfile && !canAddMoreManagedProfiles(parentId, false)) {
2704 Log.e(LOG_TAG, "Cannot add more managed profiles for user " + parentId);
2705 return null;
2706 }
Amith Yamasani52c21e32016-05-31 09:12:20 -07002707 if (!isGuest && !isManagedProfile && !isDemo && isUserLimitReached()) {
2708 // If we're not adding a guest/demo user or a managed profile and the limit has
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002709 // been reached, cannot add a user.
jovanaka6763a32018-12-03 17:23:20 -08002710 Log.e(LOG_TAG, "Cannot add user. Maximum user limit is reached.");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002711 return null;
2712 }
2713 // If we're adding a guest and there already exists one, bail.
2714 if (isGuest && findCurrentGuestUser() != null) {
jovanaka6763a32018-12-03 17:23:20 -08002715 Log.e(LOG_TAG, "Cannot add guest user. Guest user already exists.");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002716 return null;
2717 }
2718 // In legacy mode, restricted profile's parent can only be the owner user
2719 if (isRestricted && !UserManager.isSplitSystemUser()
2720 && (parentId != UserHandle.USER_SYSTEM)) {
2721 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
2722 return null;
2723 }
2724 if (isRestricted && UserManager.isSplitSystemUser()) {
2725 if (parent == null) {
2726 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be "
2727 + "specified");
Nicolas Prevot12678a92015-05-13 12:15:03 -07002728 return null;
2729 }
Amith Yamasani12747872015-12-07 14:19:49 -08002730 if (!parent.info.canHaveProfile()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002731 Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be "
2732 + "created for the specified parent user id " + parentId);
Amith Yamasani95ab7842014-08-11 17:09:26 -07002733 return null;
2734 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002735 }
2736 // In split system user mode, we assign the first human user the primary flag.
2737 // And if there is no device owner, we also assign the admin flag to primary user.
2738 if (UserManager.isSplitSystemUser()
2739 && !isGuest && !isManagedProfile && getPrimaryUser() == null) {
2740 flags |= UserInfo.FLAG_PRIMARY;
Makoto Onukie7927da2015-11-25 10:05:17 -08002741 synchronized (mUsersLock) {
2742 if (!mIsDeviceManaged) {
2743 flags |= UserInfo.FLAG_ADMIN;
2744 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07002745 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002746 }
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002747
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002748 userId = getNextAvailableId();
2749 Environment.getUserSystemDirectory(userId).mkdirs();
Lenka Trochtova02fee152015-12-22 14:26:18 +01002750 boolean ephemeralGuests = Resources.getSystem()
2751 .getBoolean(com.android.internal.R.bool.config_guestUserEphemeral);
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002752
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002753 synchronized (mUsersLock) {
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002754 // Add ephemeral flag to guests/users if required. Also inherit it from parent.
2755 if ((isGuest && ephemeralGuests) || mForceEphemeralUsers
2756 || (parent != null && parent.info.isEphemeral())) {
2757 flags |= UserInfo.FLAG_EPHEMERAL;
2758 }
2759
2760 userInfo = new UserInfo(userId, name, null, flags);
2761 userInfo.serialNumber = mNextSerialNumber++;
2762 long now = System.currentTimeMillis();
2763 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
2764 userInfo.partial = true;
Fyodor Kupolov83c24242016-03-31 13:30:42 -07002765 userInfo.lastLoggedInFingerprint = Build.FINGERPRINT;
Kenny Guy02c89902016-11-15 19:36:38 +00002766 if (isManagedProfile && parentId != UserHandle.USER_NULL) {
2767 userInfo.profileBadge = getFreeProfileBadgeLU(parentId);
2768 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002769 userData = new UserData();
2770 userData.info = userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08002771 mUsers.put(userId, userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002772 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06002773 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002774 writeUserListLP();
2775 if (parent != null) {
2776 if (isManagedProfile) {
Amith Yamasani12747872015-12-07 14:19:49 -08002777 if (parent.info.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
2778 parent.info.profileGroupId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002779 writeUserLP(parent);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002780 }
Amith Yamasani12747872015-12-07 14:19:49 -08002781 userInfo.profileGroupId = parent.info.profileGroupId;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002782 } else if (isRestricted) {
Amith Yamasani12747872015-12-07 14:19:49 -08002783 if (parent.info.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) {
2784 parent.info.restrictedProfileParentId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002785 writeUserLP(parent);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002786 }
Amith Yamasani12747872015-12-07 14:19:49 -08002787 userInfo.restrictedProfileParentId = parent.info.restrictedProfileParentId;
Makoto Onuki068c54a2015-10-13 14:34:03 -07002788 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002789 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07002790 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002791 final StorageManager storage = mContext.getSystemService(StorageManager.class);
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002792 storage.createUserKey(userId, userInfo.serialNumber, userInfo.isEphemeral());
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -08002793 mUserDataPreparer.prepareUserData(userId, userInfo.serialNumber,
Jeff Sharkey47f71082016-02-01 17:03:54 -07002794 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002795 mPm.createNewUser(userId, disallowedPackages);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002796 userInfo.partial = false;
2797 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002798 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002799 }
2800 updateUserIds();
2801 Bundle restrictions = new Bundle();
Fyodor Kupolove04462c2015-11-30 15:02:53 -08002802 if (isGuest) {
2803 synchronized (mGuestRestrictions) {
2804 restrictions.putAll(mGuestRestrictions);
2805 }
2806 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002807 synchronized (mRestrictionsLock) {
2808 mBaseUserRestrictions.append(userId, restrictions);
2809 }
Fyodor Kupolov5fd967d2016-07-12 14:46:19 -07002810 mPm.onNewUserCreated(userId);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002811 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
2812 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
2813 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
2814 android.Manifest.permission.MANAGE_USERS);
Christine Franks88220562017-05-24 11:11:21 -07002815 MetricsLogger.count(mContext, isGuest ? TRON_GUEST_CREATED
2816 : (isDemo ? TRON_DEMO_CREATED : TRON_USER_CREATED), 1);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002817 } finally {
2818 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07002819 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002820 return userInfo;
2821 }
2822
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002823 @VisibleForTesting
2824 UserData putUserInfo(UserInfo userInfo) {
2825 final UserData userData = new UserData();
2826 userData.info = userInfo;
2827 synchronized (mUsers) {
2828 mUsers.put(userInfo.id, userData);
2829 }
2830 return userData;
2831 }
2832
2833 @VisibleForTesting
2834 void removeUserInfo(int userId) {
2835 synchronized (mUsers) {
2836 mUsers.remove(userId);
2837 }
2838 }
2839
Amith Yamasani0b285492011-04-14 17:35:23 -07002840 /**
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002841 * @hide
2842 */
Amith Yamasani12747872015-12-07 14:19:49 -08002843 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002844 public UserInfo createRestrictedProfile(String name, int parentUserId) {
Sudheer Shanka53d41472016-06-16 09:11:08 -07002845 checkManageOrCreateUsersPermission("setupRestrictedProfile");
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002846 final UserInfo user = createProfileForUser(
2847 name, UserInfo.FLAG_RESTRICTED, parentUserId, null);
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002848 if (user == null) {
2849 return null;
2850 }
Fyodor Kupolov9e912ba2016-02-09 18:29:43 -08002851 long identity = Binder.clearCallingIdentity();
2852 try {
2853 setUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, true, user.id);
2854 // Change the setting before applying the DISALLOW_SHARE_LOCATION restriction, otherwise
2855 // the putIntForUser() will fail.
2856 android.provider.Settings.Secure.putIntForUser(mContext.getContentResolver(),
2857 android.provider.Settings.Secure.LOCATION_MODE,
2858 android.provider.Settings.Secure.LOCATION_MODE_OFF, user.id);
2859 setUserRestriction(UserManager.DISALLOW_SHARE_LOCATION, true, user.id);
2860 } finally {
2861 Binder.restoreCallingIdentity(identity);
2862 }
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002863 return user;
2864 }
2865
2866 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07002867 * Find the current guest user. If the Guest user is partial,
2868 * then do not include it in the results as it is about to die.
Adam Lesinskieddeb492014-09-08 17:50:03 -07002869 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002870 private UserInfo findCurrentGuestUser() {
2871 synchronized (mUsersLock) {
2872 final int size = mUsers.size();
2873 for (int i = 0; i < size; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002874 final UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002875 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
2876 return user;
2877 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002878 }
2879 }
2880 return null;
2881 }
2882
2883 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07002884 * Mark this guest user for deletion to allow us to create another guest
2885 * and switch to that user before actually removing this guest.
2886 * @param userHandle the userid of the current guest
2887 * @return whether the user could be marked for deletion
2888 */
Amith Yamasani12747872015-12-07 14:19:49 -08002889 @Override
Amith Yamasani1df14732014-08-29 21:37:27 -07002890 public boolean markGuestForDeletion(int userHandle) {
2891 checkManageUsersPermission("Only the system can remove users");
2892 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
2893 UserManager.DISALLOW_REMOVE_USER, false)) {
2894 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
2895 return false;
2896 }
2897
2898 long ident = Binder.clearCallingIdentity();
2899 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002900 final UserData userData;
Amith Yamasani1df14732014-08-29 21:37:27 -07002901 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002902 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002903 userData = mUsers.get(userHandle);
2904 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002905 return false;
2906 }
Amith Yamasani1df14732014-08-29 21:37:27 -07002907 }
Amith Yamasani12747872015-12-07 14:19:49 -08002908 if (!userData.info.isGuest()) {
Amith Yamasani1df14732014-08-29 21:37:27 -07002909 return false;
2910 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002911 // We set this to a guest user that is to be removed. This is a temporary state
2912 // where we are allowed to add new Guest users, even if this one is still not
2913 // removed. This user will still show up in getUserInfo() calls.
2914 // If we don't get around to removing this Guest user, it will be purged on next
2915 // startup.
Amith Yamasani12747872015-12-07 14:19:49 -08002916 userData.info.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07002917 // Mark it as disabled, so that it isn't returned any more when
2918 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002919 userData.info.flags |= UserInfo.FLAG_DISABLED;
2920 writeUserLP(userData);
Amith Yamasani1df14732014-08-29 21:37:27 -07002921 }
2922 } finally {
2923 Binder.restoreCallingIdentity(ident);
2924 }
2925 return true;
2926 }
2927
2928 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002929 * Removes a user and all data directories created for that user. This method should be called
2930 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07002931 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07002932 */
Amith Yamasani12747872015-12-07 14:19:49 -08002933 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -07002934 public boolean removeUser(int userHandle) {
Fyodor Kupolov4593e422016-10-27 11:00:29 -07002935 Slog.i(LOG_TAG, "removeUser u" + userHandle);
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002936 checkManageOrCreateUsersPermission("Only the system can remove users");
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002937
2938 final boolean isManagedProfile;
2939 synchronized (mUsersLock) {
2940 UserInfo userInfo = getUserInfoLU(userHandle);
2941 isManagedProfile = userInfo != null && userInfo.isManagedProfile();
2942 }
2943 String restriction = isManagedProfile
2944 ? UserManager.DISALLOW_REMOVE_MANAGED_PROFILE : UserManager.DISALLOW_REMOVE_USER;
2945 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(restriction, false)) {
2946 Log.w(LOG_TAG, "Cannot remove user. " + restriction + " is enabled.");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04002947 return false;
2948 }
Nicolas Prevotdf1b87d2016-10-25 13:57:08 +01002949 return removeUserUnchecked(userHandle);
2950 }
Julia Reynolds4ac5f852014-06-23 17:38:51 -04002951
Nicolas Prevotdf1b87d2016-10-25 13:57:08 +01002952 private boolean removeUserUnchecked(int userHandle) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002953 long ident = Binder.clearCallingIdentity();
2954 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002955 final UserData userData;
Fyodor Kupolov0df68cd2015-10-01 13:54:22 -07002956 int currentUser = ActivityManager.getCurrentUser();
2957 if (currentUser == userHandle) {
jovanaka6763a32018-12-03 17:23:20 -08002958 Log.w(LOG_TAG, "Current user cannot be removed.");
Fyodor Kupolov0df68cd2015-10-01 13:54:22 -07002959 return false;
2960 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002961 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002962 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002963 userData = mUsers.get(userHandle);
jovanaka6763a32018-12-03 17:23:20 -08002964 if (userHandle == UserHandle.USER_SYSTEM) {
2965 Log.e(LOG_TAG, "System user cannot be removed.");
2966 return false;
2967 }
2968
2969 if (userData == null) {
2970 Log.e(LOG_TAG, String.format(
2971 "Cannot remove user %d, invalid user id provided.", userHandle));
2972 return false;
2973 }
2974
2975 if (mRemovingUserIds.get(userHandle)) {
2976 Log.e(LOG_TAG, String.format(
2977 "User %d is already scheduled for removal.", userHandle));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002978 return false;
2979 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002980
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002981 addRemovingUserIdLocked(userHandle);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002982 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002983
Kenny Guyee58b4f2014-05-23 15:19:53 +01002984 // Set this to a partially created user, so that the user will be purged
2985 // on next startup, in case the runtime stops now before stopping and
2986 // removing the user completely.
Amith Yamasani12747872015-12-07 14:19:49 -08002987 userData.info.partial = true;
Kenny Guyee58b4f2014-05-23 15:19:53 +01002988 // Mark it as disabled, so that it isn't returned any more when
2989 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002990 userData.info.flags |= UserInfo.FLAG_DISABLED;
2991 writeUserLP(userData);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002992 }
Fyodor Kupolov6c96f7f2017-06-28 18:22:59 -07002993 try {
2994 mAppOpsService.removeUser(userHandle);
2995 } catch (RemoteException e) {
jovanaka6763a32018-12-03 17:23:20 -08002996 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user.", e);
Fyodor Kupolov6c96f7f2017-06-28 18:22:59 -07002997 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002998
Amith Yamasani12747872015-12-07 14:19:49 -08002999 if (userData.info.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
3000 && userData.info.isManagedProfile()) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01003001 // Send broadcast to notify system that the user removed was a
3002 // managed user.
Amith Yamasani12747872015-12-07 14:19:49 -08003003 sendProfileRemovedBroadcast(userData.info.profileGroupId, userData.info.id);
Kenny Guyee58b4f2014-05-23 15:19:53 +01003004 }
3005
3006 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
3007 int res;
3008 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003009 res = ActivityManager.getService().stopUser(userHandle, /* force= */ true,
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07003010 new IStopUserCallback.Stub() {
Kenny Guyee58b4f2014-05-23 15:19:53 +01003011 @Override
3012 public void userStopped(int userId) {
3013 finishRemoveUser(userId);
3014 }
3015 @Override
3016 public void userStopAborted(int userId) {
3017 }
3018 });
3019 } catch (RemoteException e) {
jovanaka6763a32018-12-03 17:23:20 -08003020 Log.w(LOG_TAG, "Failed to stop user during removal.", e);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003021 return false;
3022 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01003023 return res == ActivityManager.USER_OP_SUCCESS;
3024 } finally {
3025 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003026 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003027 }
3028
Andreas Gampea36dc622018-02-05 17:19:22 -08003029 @GuardedBy("mUsersLock")
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003030 @VisibleForTesting
3031 void addRemovingUserIdLocked(int userId) {
3032 // We remember deleted user IDs to prevent them from being
3033 // reused during the current boot; they can still be reused
3034 // after a reboot or recycling of userIds.
3035 mRemovingUserIds.put(userId, true);
3036 mRecentlyRemovedIds.add(userId);
3037 // Keep LRU queue of recently removed IDs for recycling
3038 if (mRecentlyRemovedIds.size() > MAX_RECENTLY_REMOVED_IDS_SIZE) {
3039 mRecentlyRemovedIds.removeFirst();
3040 }
3041 }
3042
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07003043 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07003044 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07003045 // Let other services shutdown any activity and clean up their state before completely
3046 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07003047 long ident = Binder.clearCallingIdentity();
3048 try {
3049 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
3050 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07003051 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
3052 android.Manifest.permission.MANAGE_USERS,
3053
3054 new BroadcastReceiver() {
3055 @Override
3056 public void onReceive(Context context, Intent intent) {
3057 if (DBG) {
3058 Slog.i(LOG_TAG,
3059 "USER_REMOVED broadcast sent, cleaning up user data "
3060 + userHandle);
3061 }
3062 new Thread() {
Amith Yamasani12747872015-12-07 14:19:49 -08003063 @Override
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07003064 public void run() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003065 // Clean up any ActivityTaskManager state
3066 LocalServices.getService(ActivityTaskManagerInternal.class)
3067 .onUserStopped(userHandle);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003068 removeUserState(userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07003069 }
3070 }.start();
3071 }
3072 },
3073
3074 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07003075 } finally {
3076 Binder.restoreCallingIdentity(ident);
3077 }
Amith Yamasani2a003292012-08-14 18:25:45 -07003078 }
3079
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003080 private void removeUserState(final int userHandle) {
Paul Crowley91293792016-03-25 15:23:07 -07003081 try {
3082 mContext.getSystemService(StorageManager.class).destroyUserKey(userHandle);
3083 } catch (IllegalStateException e) {
3084 // This may be simply because the user was partially created.
3085 Slog.i(LOG_TAG,
3086 "Destroying key for user " + userHandle + " failed, continuing anyway", e);
3087 }
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06003088
Amith Yamasanid04aaa32016-06-13 12:09:36 -07003089 // Cleanup gatekeeper secure user id
3090 try {
3091 final IGateKeeperService gk = GateKeeper.getService();
3092 if (gk != null) {
3093 gk.clearSecureUserId(userHandle);
3094 }
3095 } catch (Exception ex) {
3096 Slog.w(LOG_TAG, "unable to clear GK secure user id");
3097 }
3098
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003099 // Cleanup package manager settings
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003100 mPm.cleanUpUser(this, userHandle);
Amith Yamasanid04aaa32016-06-13 12:09:36 -07003101
3102 // Clean up all data before removing metadata
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -08003103 mUserDataPreparer.destroyUserData(userHandle,
Amith Yamasanid04aaa32016-06-13 12:09:36 -07003104 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
3105
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003106 // Remove this user from the list
Fyodor Kupolov82402752015-10-28 14:54:51 -07003107 synchronized (mUsersLock) {
3108 mUsers.remove(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08003109 mIsUserManaged.delete(userHandle);
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003110 }
3111 synchronized (mUserStates) {
3112 mUserStates.delete(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08003113 }
3114 synchronized (mRestrictionsLock) {
3115 mBaseUserRestrictions.remove(userHandle);
3116 mAppliedUserRestrictions.remove(userHandle);
3117 mCachedEffectiveUserRestrictions.remove(userHandle);
3118 mDevicePolicyLocalUserRestrictions.remove(userHandle);
Pavel Grafov6a40f092016-10-25 15:46:51 +01003119 if (mDevicePolicyGlobalUserRestrictions.get(userHandle) != null) {
3120 mDevicePolicyGlobalUserRestrictions.remove(userHandle);
3121 applyUserRestrictionsForAllUsersLR();
3122 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07003123 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003124 // Update the user list
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003125 synchronized (mPackagesLock) {
3126 writeUserListLP();
3127 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06003128 // Remove user file
3129 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
3130 userFile.delete();
Fyodor Kupolov82402752015-10-28 14:54:51 -07003131 updateUserIds();
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003132 if (RELEASE_DELETED_USER_ID) {
3133 synchronized (mUsers) {
3134 mRemovingUserIds.delete(userHandle);
3135 }
3136 }
Amith Yamasani61f57372012-08-31 12:12:28 -07003137 }
3138
Kenny Guyf8d3a232014-05-15 16:09:52 +01003139 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01003140 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01003141 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
3142 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01003143 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
Jeff Sharkeyaf6ec292015-12-17 11:19:00 -07003144 managedProfileIntent.putExtra(Intent.EXTRA_USER_HANDLE, removedUserId);
Kenny Guyf8d3a232014-05-15 16:09:52 +01003145 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01003146 }
3147
Amith Yamasani2a003292012-08-14 18:25:45 -07003148 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07003149 public Bundle getApplicationRestrictions(String packageName) {
3150 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
3151 }
3152
3153 @Override
3154 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003155 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07003156 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07003157 checkSystemOrRoot("get application restrictions for other user/app " + packageName);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003158 }
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003159 synchronized (mAppRestrictionsLock) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003160 // Read the restrictions from XML
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003161 return readApplicationRestrictionsLAr(packageName, userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003162 }
3163 }
3164
3165 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07003166 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003167 int userId) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00003168 checkSystemOrRoot("set application restrictions");
Fyodor Kupolov0d88d542016-04-19 11:37:22 -07003169 if (restrictions != null) {
3170 restrictions.setDefusable(true);
3171 }
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003172 synchronized (mAppRestrictionsLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01003173 if (restrictions == null || restrictions.isEmpty()) {
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003174 cleanAppRestrictionsForPackageLAr(packageName, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01003175 } else {
3176 // Write the restrictions to XML
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003177 writeApplicationRestrictionsLAr(packageName, restrictions, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01003178 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003179 }
Robin Lee66e5d962014-04-09 16:44:21 +01003180
Fyodor Kupolovd2846122016-02-11 18:06:34 -08003181 // Notify package of changes via an intent - only sent to explicitly registered receivers.
3182 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
3183 changeIntent.setPackage(packageName);
3184 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3185 mContext.sendBroadcastAsUser(changeIntent, UserHandle.of(userId));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003186 }
3187
3188 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07003189 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003190 try {
3191 return mContext.getPackageManager().getApplicationInfo(packageName,
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07003192 PackageManager.MATCH_ANY_USER).uid;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003193 } catch (NameNotFoundException nnfe) {
3194 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07003195 } finally {
3196 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003197 }
3198 }
3199
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003200 @GuardedBy("mAppRestrictionsLock")
3201 private static Bundle readApplicationRestrictionsLAr(String packageName, int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003202 AtomicFile restrictionsFile =
3203 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
3204 packageToRestrictionsFileName(packageName)));
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003205 return readApplicationRestrictionsLAr(restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003206 }
3207
3208 @VisibleForTesting
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003209 @GuardedBy("mAppRestrictionsLock")
3210 static Bundle readApplicationRestrictionsLAr(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07003211 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003212 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07003213 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07003214 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07003215 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003216
3217 FileInputStream fis = null;
3218 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003219 fis = restrictionsFile.openRead();
3220 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01003221 parser.setInput(fis, StandardCharsets.UTF_8.name());
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003222 XmlUtils.nextElement(parser);
3223 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003224 Slog.e(LOG_TAG, "Unable to read restrictions file "
3225 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07003226 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003227 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003228 while (parser.next() != XmlPullParser.END_DOCUMENT) {
3229 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003230 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003231 } catch (IOException|XmlPullParserException e) {
3232 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003233 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003234 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003235 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07003236 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003237 }
3238
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003239 private static void readEntry(Bundle restrictions, ArrayList<String> values,
3240 XmlPullParser parser) throws XmlPullParserException, IOException {
3241 int type = parser.getEventType();
3242 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
3243 String key = parser.getAttributeValue(null, ATTR_KEY);
3244 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
3245 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
3246 if (multiple != null) {
3247 values.clear();
3248 int count = Integer.parseInt(multiple);
3249 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
3250 if (type == XmlPullParser.START_TAG
3251 && parser.getName().equals(TAG_VALUE)) {
3252 values.add(parser.nextText().trim());
3253 count--;
3254 }
3255 }
3256 String [] valueStrings = new String[values.size()];
3257 values.toArray(valueStrings);
3258 restrictions.putStringArray(key, valueStrings);
3259 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
3260 restrictions.putBundle(key, readBundleEntry(parser, values));
3261 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
3262 final int outerDepth = parser.getDepth();
3263 ArrayList<Bundle> bundleList = new ArrayList<>();
3264 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
3265 Bundle childBundle = readBundleEntry(parser, values);
3266 bundleList.add(childBundle);
3267 }
3268 restrictions.putParcelableArray(key,
3269 bundleList.toArray(new Bundle[bundleList.size()]));
3270 } else {
3271 String value = parser.nextText().trim();
3272 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
3273 restrictions.putBoolean(key, Boolean.parseBoolean(value));
3274 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
3275 restrictions.putInt(key, Integer.parseInt(value));
3276 } else {
3277 restrictions.putString(key, value);
3278 }
3279 }
3280 }
3281 }
3282
3283 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
3284 throws IOException, XmlPullParserException {
3285 Bundle childBundle = new Bundle();
3286 final int outerDepth = parser.getDepth();
3287 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
3288 readEntry(childBundle, values, parser);
3289 }
3290 return childBundle;
3291 }
3292
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003293 @GuardedBy("mAppRestrictionsLock")
3294 private static void writeApplicationRestrictionsLAr(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07003295 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003296 AtomicFile restrictionsFile = new AtomicFile(
3297 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07003298 packageToRestrictionsFileName(packageName)));
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003299 writeApplicationRestrictionsLAr(restrictions, restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003300 }
3301
3302 @VisibleForTesting
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003303 @GuardedBy("mAppRestrictionsLock")
3304 static void writeApplicationRestrictionsLAr(Bundle restrictions, AtomicFile restrictionsFile) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003305 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003306 try {
3307 fos = restrictionsFile.startWrite();
3308 final BufferedOutputStream bos = new BufferedOutputStream(fos);
3309
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003310 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01003311 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003312 serializer.startDocument(null, true);
3313 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
3314
3315 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003316 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003317 serializer.endTag(null, TAG_RESTRICTIONS);
3318
3319 serializer.endDocument();
3320 restrictionsFile.finishWrite(fos);
3321 } catch (Exception e) {
3322 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003323 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
3324 }
3325 }
3326
3327 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
3328 throws IOException {
3329 for (String key : restrictions.keySet()) {
3330 Object value = restrictions.get(key);
3331 serializer.startTag(null, TAG_ENTRY);
3332 serializer.attribute(null, ATTR_KEY, key);
3333
3334 if (value instanceof Boolean) {
3335 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
3336 serializer.text(value.toString());
3337 } else if (value instanceof Integer) {
3338 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
3339 serializer.text(value.toString());
3340 } else if (value == null || value instanceof String) {
3341 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
3342 serializer.text(value != null ? (String) value : "");
3343 } else if (value instanceof Bundle) {
3344 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
3345 writeBundle((Bundle) value, serializer);
3346 } else if (value instanceof Parcelable[]) {
3347 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
3348 Parcelable[] array = (Parcelable[]) value;
3349 for (Parcelable parcelable : array) {
3350 if (!(parcelable instanceof Bundle)) {
3351 throw new IllegalArgumentException("bundle-array can only hold Bundles");
3352 }
3353 serializer.startTag(null, TAG_ENTRY);
3354 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
3355 writeBundle((Bundle) parcelable, serializer);
3356 serializer.endTag(null, TAG_ENTRY);
3357 }
3358 } else {
3359 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
3360 String[] values = (String[]) value;
3361 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
3362 for (String choice : values) {
3363 serializer.startTag(null, TAG_VALUE);
3364 serializer.text(choice != null ? choice : "");
3365 serializer.endTag(null, TAG_VALUE);
3366 }
3367 }
3368 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003369 }
3370 }
3371
3372 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07003373 public int getUserSerialNumber(int userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003374 synchronized (mUsersLock) {
Pavel Grafov9c295d42019-03-26 19:42:08 +00003375 final UserInfo userInfo = getUserInfoLU(userHandle);
3376 return userInfo != null ? userInfo.serialNumber : -1;
Amith Yamasani2a003292012-08-14 18:25:45 -07003377 }
3378 }
3379
3380 @Override
Fyodor Kupolov605b12a2017-05-10 15:58:09 -07003381 public boolean isUserNameSet(int userHandle) {
3382 synchronized (mUsersLock) {
Pavel Grafov9c295d42019-03-26 19:42:08 +00003383 final UserInfo userInfo = getUserInfoLU(userHandle);
Fyodor Kupolov605b12a2017-05-10 15:58:09 -07003384 return userInfo != null && userInfo.name != null;
3385 }
3386 }
3387
3388 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07003389 public int getUserHandle(int userSerialNumber) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003390 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07003391 for (int userId : mUserIds) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003392 UserInfo info = getUserInfoLU(userId);
Kenny Guy945f8832015-02-10 15:17:26 +00003393 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07003394 }
3395 // Not found
3396 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07003397 }
3398 }
3399
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003400 @Override
3401 public long getUserCreationTime(int userHandle) {
3402 int callingUserId = UserHandle.getCallingUserId();
3403 UserInfo userInfo = null;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003404 synchronized (mUsersLock) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003405 if (callingUserId == userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003406 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003407 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003408 UserInfo parent = getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003409 if (parent != null && parent.id == callingUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003410 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003411 }
3412 }
3413 }
3414 if (userInfo == null) {
3415 throw new SecurityException("userHandle can only be the calling user or a managed "
3416 + "profile associated with this user");
3417 }
3418 return userInfo.creationTime;
3419 }
3420
Amith Yamasani0b285492011-04-14 17:35:23 -07003421 /**
3422 * Caches the list of user ids in an array, adjusting the array size when necessary.
3423 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07003424 private void updateUserIds() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003425 int num = 0;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003426 synchronized (mUsersLock) {
3427 final int userSize = mUsers.size();
3428 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003429 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003430 num++;
3431 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003432 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07003433 final int[] newUsers = new int[num];
3434 int n = 0;
3435 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003436 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003437 newUsers[n++] = mUsers.keyAt(i);
3438 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003439 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07003440 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07003441 }
3442 }
3443
3444 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003445 * Called right before a user is started. This gives us a chance to prepare
3446 * app storage and apply any user restrictions.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003447 */
3448 public void onBeforeStartUser(int userId) {
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003449 UserInfo userInfo = getUserInfo(userId);
3450 if (userInfo == null) {
3451 return;
3452 }
3453 final int userSerial = userInfo.serialNumber;
3454 // Migrate only if build fingerprints mismatch
3455 boolean migrateAppsData = !Build.FINGERPRINT.equals(userInfo.lastLoggedInFingerprint);
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -08003456 mUserDataPreparer.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_DE);
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003457 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_DE, migrateAppsData);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003458
3459 if (userId != UserHandle.USER_SYSTEM) {
3460 synchronized (mRestrictionsLock) {
3461 applyUserRestrictionsLR(userId);
3462 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003463 }
3464 }
3465
3466 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003467 * Called right before a user is unlocked. This gives us a chance to prepare
3468 * app storage.
3469 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003470 public void onBeforeUnlockUser(@UserIdInt int userId) {
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003471 UserInfo userInfo = getUserInfo(userId);
3472 if (userInfo == null) {
3473 return;
3474 }
3475 final int userSerial = userInfo.serialNumber;
3476 // Migrate only if build fingerprints mismatch
3477 boolean migrateAppsData = !Build.FINGERPRINT.equals(userInfo.lastLoggedInFingerprint);
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -08003478 mUserDataPreparer.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_CE);
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003479 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_CE, migrateAppsData);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003480 }
3481
3482 /**
Fyodor Kupolov50979d12017-01-27 17:36:32 -08003483 * Examine all users present on given mounted volume, and destroy data
3484 * belonging to users that are no longer valid, or whose user ID has been
3485 * recycled.
3486 */
3487 void reconcileUsers(String volumeUuid) {
3488 mUserDataPreparer.reconcileUsers(volumeUuid, getUsers(true /* excludeDying */));
3489 }
3490
3491 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07003492 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasanieb437d42016-04-29 09:31:25 -07003493 * This is called with ActivityManagerService lock held.
Amith Yamasani920ace02012-09-20 22:15:37 -07003494 * @param userId the user that was just foregrounded
3495 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003496 public void onUserLoggedIn(@UserIdInt int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -08003497 UserData userData = getUserDataNoChecks(userId);
3498 if (userData == null || userData.info.partial) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003499 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
3500 return;
3501 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003502
3503 final long now = System.currentTimeMillis();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003504 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani12747872015-12-07 14:19:49 -08003505 userData.info.lastLoggedInTime = now;
Amith Yamasani920ace02012-09-20 22:15:37 -07003506 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003507 userData.info.lastLoggedInFingerprint = Build.FINGERPRINT;
3508 scheduleWriteUser(userData);
Amith Yamasani920ace02012-09-20 22:15:37 -07003509 }
3510
3511 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07003512 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani0b285492011-04-14 17:35:23 -07003513 */
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003514 @VisibleForTesting
3515 int getNextAvailableId() {
3516 int nextId;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003517 synchronized (mUsersLock) {
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003518 nextId = scanNextAvailableIdLocked();
3519 if (nextId >= 0) {
3520 return nextId;
3521 }
3522 // All ids up to MAX_USER_ID were used. Remove all mRemovingUserIds,
3523 // except most recently removed
3524 if (mRemovingUserIds.size() > 0) {
3525 Slog.i(LOG_TAG, "All available IDs are used. Recycling LRU ids.");
3526 mRemovingUserIds.clear();
3527 for (Integer recentlyRemovedId : mRecentlyRemovedIds) {
3528 mRemovingUserIds.put(recentlyRemovedId, true);
Amith Yamasani195263742012-08-21 15:40:12 -07003529 }
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003530 nextId = scanNextAvailableIdLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003531 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003532 }
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003533 if (nextId < 0) {
3534 throw new IllegalStateException("No user id available!");
3535 }
3536 return nextId;
3537 }
3538
Andreas Gampea36dc622018-02-05 17:19:22 -08003539 @GuardedBy("mUsersLock")
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003540 private int scanNextAvailableIdLocked() {
3541 for (int i = MIN_USER_ID; i < MAX_USER_ID; i++) {
3542 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
3543 return i;
3544 }
3545 }
3546 return -1;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003547 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003548
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003549 private static String packageToRestrictionsFileName(String packageName) {
Amith Yamasanifc95e702013-09-26 13:20:17 -07003550 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
3551 }
3552
Amith Yamasani920ace02012-09-20 22:15:37 -07003553 @Override
Amith Yamasani12747872015-12-07 14:19:49 -08003554 public void setSeedAccountData(int userId, String accountName, String accountType,
3555 PersistableBundle accountOptions, boolean persist) {
3556 checkManageUsersPermission("Require MANAGE_USERS permission to set user seed data");
3557 synchronized (mPackagesLock) {
3558 final UserData userData;
3559 synchronized (mUsersLock) {
3560 userData = getUserDataLU(userId);
3561 if (userData == null) {
3562 Slog.e(LOG_TAG, "No such user for settings seed data u=" + userId);
3563 return;
3564 }
3565 userData.seedAccountName = accountName;
3566 userData.seedAccountType = accountType;
3567 userData.seedAccountOptions = accountOptions;
3568 userData.persistSeedData = persist;
3569 }
3570 if (persist) {
3571 writeUserLP(userData);
3572 }
3573 }
3574 }
3575
3576 @Override
3577 public String getSeedAccountName() throws RemoteException {
3578 checkManageUsersPermission("Cannot get seed account information");
3579 synchronized (mUsersLock) {
3580 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3581 return userData.seedAccountName;
3582 }
3583 }
3584
3585 @Override
3586 public String getSeedAccountType() throws RemoteException {
3587 checkManageUsersPermission("Cannot get seed account information");
3588 synchronized (mUsersLock) {
3589 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3590 return userData.seedAccountType;
3591 }
3592 }
3593
3594 @Override
3595 public PersistableBundle getSeedAccountOptions() throws RemoteException {
3596 checkManageUsersPermission("Cannot get seed account information");
3597 synchronized (mUsersLock) {
3598 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3599 return userData.seedAccountOptions;
3600 }
3601 }
3602
3603 @Override
3604 public void clearSeedAccountData() throws RemoteException {
3605 checkManageUsersPermission("Cannot clear seed account information");
3606 synchronized (mPackagesLock) {
3607 UserData userData;
3608 synchronized (mUsersLock) {
3609 userData = getUserDataLU(UserHandle.getCallingUserId());
3610 if (userData == null) return;
3611 userData.clearSeedAccountData();
3612 }
3613 writeUserLP(userData);
3614 }
3615 }
3616
3617 @Override
3618 public boolean someUserHasSeedAccount(String accountName, String accountType)
3619 throws RemoteException {
3620 checkManageUsersPermission("Cannot check seed account information");
3621 synchronized (mUsersLock) {
3622 final int userSize = mUsers.size();
3623 for (int i = 0; i < userSize; i++) {
3624 final UserData data = mUsers.valueAt(i);
3625 if (data.info.isInitialized()) continue;
3626 if (data.seedAccountName == null || !data.seedAccountName.equals(accountName)) {
3627 continue;
3628 }
3629 if (data.seedAccountType == null || !data.seedAccountType.equals(accountType)) {
3630 continue;
3631 }
3632 return true;
3633 }
3634 }
3635 return false;
3636 }
3637
3638 @Override
Todd Kennedy60459ab2015-10-30 11:32:16 -07003639 public void onShellCommand(FileDescriptor in, FileDescriptor out,
Dianne Hackborn354736e2016-08-22 17:00:05 -07003640 FileDescriptor err, String[] args, ShellCallback callback,
3641 ResultReceiver resultReceiver) {
3642 (new Shell()).exec(this, in, out, err, args, callback, resultReceiver);
Todd Kennedy60459ab2015-10-30 11:32:16 -07003643 }
3644
3645 int onShellCommand(Shell shell, String cmd) {
3646 if (cmd == null) {
3647 return shell.handleDefaultCommands(cmd);
3648 }
3649
3650 final PrintWriter pw = shell.getOutPrintWriter();
3651 try {
3652 switch(cmd) {
3653 case "list":
3654 return runList(pw);
Hui Yu8ba65972018-04-16 18:45:48 -07003655 default:
3656 return shell.handleDefaultCommands(cmd);
Todd Kennedy60459ab2015-10-30 11:32:16 -07003657 }
3658 } catch (RemoteException e) {
3659 pw.println("Remote exception: " + e);
3660 }
3661 return -1;
3662 }
3663
3664 private int runList(PrintWriter pw) throws RemoteException {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003665 final IActivityManager am = ActivityManager.getService();
Todd Kennedy60459ab2015-10-30 11:32:16 -07003666 final List<UserInfo> users = getUsers(false);
3667 if (users == null) {
3668 pw.println("Error: couldn't get users");
3669 return 1;
3670 } else {
3671 pw.println("Users:");
3672 for (int i = 0; i < users.size(); i++) {
Jeff Sharkeye17ac152015-11-06 22:40:29 -08003673 String running = am.isUserRunning(users.get(i).id, 0) ? " running" : "";
Todd Kennedy60459ab2015-10-30 11:32:16 -07003674 pw.println("\t" + users.get(i).toString() + running);
3675 }
3676 return 0;
3677 }
3678 }
3679
3680 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -07003681 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06003682 if (!DumpUtils.checkDumpPermission(mContext, LOG_TAG, pw)) return;
Amith Yamasani920ace02012-09-20 22:15:37 -07003683
3684 long now = System.currentTimeMillis();
Makoto Onuki73dded22017-12-20 13:14:48 +09003685 final long nowRealtime = SystemClock.elapsedRealtime();
Felipe Leme3c5e8862019-06-12 17:40:53 -07003686
3687 final int currentUser = LocalServices.getService(ActivityManagerInternal.class)
3688 .getCurrentUserId();
3689 pw.print("Current user: "); pw.println(currentUser);
3690
Amith Yamasani920ace02012-09-20 22:15:37 -07003691 StringBuilder sb = new StringBuilder();
3692 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003693 synchronized (mUsersLock) {
3694 pw.println("Users:");
3695 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003696 UserData userData = mUsers.valueAt(i);
3697 if (userData == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003698 continue;
3699 }
Amith Yamasani12747872015-12-07 14:19:49 -08003700 UserInfo userInfo = userData.info;
3701 final int userId = userInfo.id;
3702 pw.print(" "); pw.print(userInfo);
3703 pw.print(" serialNo="); pw.print(userInfo.serialNumber);
Felipe Leme3c5e8862019-06-12 17:40:53 -07003704 pw.print(" isPrimary="); pw.print(userInfo.isPrimary());
Makoto Onukie7927da2015-11-25 10:05:17 -08003705 if (mRemovingUserIds.get(userId)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003706 pw.print(" <removing> ");
3707 }
Amith Yamasani12747872015-12-07 14:19:49 -08003708 if (userInfo.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003709 pw.print(" <partial>");
3710 }
3711 pw.println();
Makoto Onuki88aef752017-03-29 16:52:03 -07003712 pw.print(" State: ");
3713 final int state;
3714 synchronized (mUserStates) {
3715 state = mUserStates.get(userId, -1);
3716 }
3717 pw.println(UserState.stateToString(state));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003718 pw.print(" Created: ");
Makoto Onuki73dded22017-12-20 13:14:48 +09003719 dumpTimeAgo(pw, sb, now, userInfo.creationTime);
3720
Fyodor Kupolov82402752015-10-28 14:54:51 -07003721 pw.print(" Last logged in: ");
Makoto Onuki73dded22017-12-20 13:14:48 +09003722 dumpTimeAgo(pw, sb, now, userInfo.lastLoggedInTime);
3723
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003724 pw.print(" Last logged in fingerprint: ");
3725 pw.println(userInfo.lastLoggedInFingerprint);
Makoto Onuki73dded22017-12-20 13:14:48 +09003726
3727 pw.print(" Start time: ");
3728 dumpTimeAgo(pw, sb, nowRealtime, userData.startRealtime);
3729
3730 pw.print(" Unlock time: ");
3731 dumpTimeAgo(pw, sb, nowRealtime, userData.unlockRealtime);
3732
Makoto Onukie7927da2015-11-25 10:05:17 -08003733 pw.print(" Has profile owner: ");
3734 pw.println(mIsUserManaged.get(userId));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003735 pw.println(" Restrictions:");
3736 synchronized (mRestrictionsLock) {
3737 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003738 pw, " ", mBaseUserRestrictions.get(userInfo.id));
Pavel Grafov6a40f092016-10-25 15:46:51 +01003739 pw.println(" Device policy global restrictions:");
3740 UserRestrictionsUtils.dumpRestrictions(
3741 pw, " ", mDevicePolicyGlobalUserRestrictions.get(userInfo.id));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003742 pw.println(" Device policy local restrictions:");
3743 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003744 pw, " ", mDevicePolicyLocalUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003745 pw.println(" Effective restrictions:");
3746 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003747 pw, " ", mCachedEffectiveUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003748 }
Amith Yamasani12747872015-12-07 14:19:49 -08003749
3750 if (userData.account != null) {
3751 pw.print(" Account name: " + userData.account);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08003752 pw.println();
3753 }
Amith Yamasani12747872015-12-07 14:19:49 -08003754
3755 if (userData.seedAccountName != null) {
3756 pw.print(" Seed account name: " + userData.seedAccountName);
3757 pw.println();
3758 if (userData.seedAccountType != null) {
3759 pw.print(" account type: " + userData.seedAccountType);
3760 pw.println();
3761 }
3762 if (userData.seedAccountOptions != null) {
3763 pw.print(" account options exist");
3764 pw.println();
3765 }
3766 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003767 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003768 }
Amith Yamasani12747872015-12-07 14:19:49 -08003769 pw.println();
Pavel Grafov6a40f092016-10-25 15:46:51 +01003770 pw.println(" Device owner id:" + mDeviceOwnerUserId);
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01003771 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003772 pw.println(" Guest restrictions:");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003773 synchronized (mGuestRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003774 UserRestrictionsUtils.dumpRestrictions(pw, " ", mGuestRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003775 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003776 synchronized (mUsersLock) {
3777 pw.println();
3778 pw.println(" Device managed: " + mIsDeviceManaged);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003779 if (mRemovingUserIds.size() > 0) {
3780 pw.println();
3781 pw.println(" Recently removed userIds: " + mRecentlyRemovedIds);
3782 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003783 }
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003784 synchronized (mUserStates) {
3785 pw.println(" Started users state: " + mUserStates);
3786 }
Felipe Leme3c5e8862019-06-12 17:40:53 -07003787 } // synchronized (mPackagesLock)
3788
3789 // Dump some capabilities
3790 pw.println();
3791 pw.println(" Max users: " + UserManager.getMaxSupportedUsers());
3792 pw.println(" Supports switchable users: " + UserManager.supportsMultipleUsers());
3793 pw.println(" All guests ephemeral: " + Resources.getSystem().getBoolean(
3794 com.android.internal.R.bool.config_guestUserEphemeral));
3795 pw.println(" Is split-system user: " + UserManager.isSplitSystemUser());
Amith Yamasani920ace02012-09-20 22:15:37 -07003796 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08003797
Makoto Onuki73dded22017-12-20 13:14:48 +09003798 private static void dumpTimeAgo(PrintWriter pw, StringBuilder sb, long nowTime, long time) {
3799 if (time == 0) {
3800 pw.println("<unknown>");
3801 } else {
3802 sb.setLength(0);
3803 TimeUtils.formatDuration(nowTime - time, sb);
3804 sb.append(" ago");
3805 pw.println(sb);
3806 }
3807 }
3808
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08003809 final class MainHandler extends Handler {
3810
3811 @Override
3812 public void handleMessage(Message msg) {
3813 switch (msg.what) {
3814 case WRITE_USER_MSG:
3815 removeMessages(WRITE_USER_MSG, msg.obj);
3816 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08003817 int userId = ((UserData) msg.obj).info.id;
3818 UserData userData = getUserDataNoChecks(userId);
3819 if (userData != null) {
3820 writeUserLP(userData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08003821 }
3822 }
3823 }
3824 }
3825 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07003826
3827 /**
3828 * @param userId
3829 * @return whether the user has been initialized yet
3830 */
Todd Kennedy0eb97382017-10-03 16:57:22 -07003831 boolean isUserInitialized(int userId) {
3832 return mLocalService.isUserInitialized(userId);
Amith Yamasanibb054c92015-07-09 14:16:27 -07003833 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003834
3835 private class LocalService extends UserManagerInternal {
Makoto Onuki068c54a2015-10-13 14:34:03 -07003836 @Override
Pavel Grafov6a40f092016-10-25 15:46:51 +01003837 public void setDevicePolicyUserRestrictions(int userId, @Nullable Bundle restrictions,
3838 boolean isDeviceOwner, int cameraRestrictionScope) {
3839 UserManagerService.this.setDevicePolicyUserRestrictionsInner(userId, restrictions,
3840 isDeviceOwner, cameraRestrictionScope);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003841 }
3842
3843 @Override
3844 public Bundle getBaseUserRestrictions(int userId) {
3845 synchronized (mRestrictionsLock) {
3846 return mBaseUserRestrictions.get(userId);
3847 }
3848 }
3849
3850 @Override
3851 public void setBaseUserRestrictionsByDpmsForMigration(
3852 int userId, Bundle baseRestrictions) {
3853 synchronized (mRestrictionsLock) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01003854 if (updateRestrictionsIfNeededLR(
3855 userId, new Bundle(baseRestrictions), mBaseUserRestrictions)) {
3856 invalidateEffectiveUserRestrictionsLR(userId);
3857 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003858 }
3859
Amith Yamasani12747872015-12-07 14:19:49 -08003860 final UserData userData = getUserDataNoChecks(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003861 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08003862 if (userData != null) {
3863 writeUserLP(userData);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003864 } else {
3865 Slog.w(LOG_TAG, "UserInfo not found for " + userId);
3866 }
3867 }
3868 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08003869
3870 @Override
3871 public boolean getUserRestriction(int userId, String key) {
3872 return getUserRestrictions(userId).getBoolean(key);
3873 }
3874
3875 @Override
3876 public void addUserRestrictionsListener(UserRestrictionsListener listener) {
3877 synchronized (mUserRestrictionsListeners) {
3878 mUserRestrictionsListeners.add(listener);
3879 }
3880 }
3881
3882 @Override
3883 public void removeUserRestrictionsListener(UserRestrictionsListener listener) {
3884 synchronized (mUserRestrictionsListeners) {
3885 mUserRestrictionsListeners.remove(listener);
3886 }
3887 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003888
3889 @Override
3890 public void setDeviceManaged(boolean isManaged) {
3891 synchronized (mUsersLock) {
3892 mIsDeviceManaged = isManaged;
3893 }
3894 }
3895
3896 @Override
3897 public void setUserManaged(int userId, boolean isManaged) {
3898 synchronized (mUsersLock) {
3899 mIsUserManaged.put(userId, isManaged);
3900 }
3901 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01003902
3903 @Override
3904 public void setUserIcon(int userId, Bitmap bitmap) {
3905 long ident = Binder.clearCallingIdentity();
3906 try {
3907 synchronized (mPackagesLock) {
3908 UserData userData = getUserDataNoChecks(userId);
3909 if (userData == null || userData.info.partial) {
3910 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
3911 return;
3912 }
3913 writeBitmapLP(userData.info, bitmap);
3914 writeUserLP(userData);
3915 }
3916 sendUserInfoChangedBroadcast(userId);
3917 } finally {
3918 Binder.restoreCallingIdentity(ident);
3919 }
3920 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01003921
3922 @Override
3923 public void setForceEphemeralUsers(boolean forceEphemeralUsers) {
3924 synchronized (mUsersLock) {
3925 mForceEphemeralUsers = forceEphemeralUsers;
3926 }
3927 }
3928
3929 @Override
3930 public void removeAllUsers() {
3931 if (UserHandle.USER_SYSTEM == ActivityManager.getCurrentUser()) {
3932 // Remove the non-system users straight away.
3933 removeNonSystemUsers();
3934 } else {
3935 // Switch to the system user first and then remove the other users.
3936 BroadcastReceiver userSwitchedReceiver = new BroadcastReceiver() {
3937 @Override
3938 public void onReceive(Context context, Intent intent) {
3939 int userId =
3940 intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3941 if (userId != UserHandle.USER_SYSTEM) {
3942 return;
3943 }
3944 mContext.unregisterReceiver(this);
3945 removeNonSystemUsers();
3946 }
3947 };
3948 IntentFilter userSwitchedFilter = new IntentFilter();
3949 userSwitchedFilter.addAction(Intent.ACTION_USER_SWITCHED);
3950 mContext.registerReceiver(
3951 userSwitchedReceiver, userSwitchedFilter, null, mHandler);
3952
3953 // Switch to the system user.
3954 ActivityManager am =
3955 (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
3956 am.switchUser(UserHandle.USER_SYSTEM);
3957 }
3958 }
phweisse9c44062016-02-10 12:57:38 +01003959
3960 @Override
Lenka Trochtova1ddda472016-02-12 10:42:12 +01003961 public void onEphemeralUserStop(int userId) {
3962 synchronized (mUsersLock) {
3963 UserInfo userInfo = getUserInfoLU(userId);
3964 if (userInfo != null && userInfo.isEphemeral()) {
3965 // Do not allow switching back to the ephemeral user again as the user is going
3966 // to be deleted.
3967 userInfo.flags |= UserInfo.FLAG_DISABLED;
3968 if (userInfo.isGuest()) {
3969 // Indicate that the guest will be deleted after it stops.
3970 userInfo.guestToRemove = true;
3971 }
3972 }
3973 }
3974 }
3975
3976 @Override
Alex Chaub6a9f942017-11-07 11:28:56 +08003977 public UserInfo createUserEvenWhenDisallowed(String name, int flags,
3978 String[] disallowedPackages) {
3979 UserInfo user = createUserInternalUnchecked(name, flags, UserHandle.USER_NULL,
3980 disallowedPackages);
phweisse9c44062016-02-10 12:57:38 +01003981 // Keep this in sync with UserManager.createUser
Christine Franks97a54802017-08-09 10:06:43 -07003982 if (user != null && !user.isAdmin() && !user.isDemo()) {
phweisse9c44062016-02-10 12:57:38 +01003983 setUserRestriction(UserManager.DISALLOW_SMS, true, user.id);
3984 setUserRestriction(UserManager.DISALLOW_OUTGOING_CALLS, true, user.id);
3985 }
3986 return user;
3987 }
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003988
3989 @Override
Nicolas Prevotdf1b87d2016-10-25 13:57:08 +01003990 public boolean removeUserEvenWhenDisallowed(int userId) {
3991 return removeUserUnchecked(userId);
3992 }
3993
3994 @Override
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003995 public boolean isUserRunning(int userId) {
3996 synchronized (mUserStates) {
3997 return mUserStates.get(userId, -1) >= 0;
3998 }
3999 }
4000
4001 @Override
4002 public void setUserState(int userId, int userState) {
4003 synchronized (mUserStates) {
4004 mUserStates.put(userId, userState);
4005 }
4006 }
4007
4008 @Override
4009 public void removeUserState(int userId) {
4010 synchronized (mUserStates) {
4011 mUserStates.delete(userId);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07004012 }
4013 }
4014
4015 @Override
Michael Wachenschwanz3f2b6552017-05-15 13:53:09 -07004016 public int[] getUserIds() {
4017 return UserManagerService.this.getUserIds();
4018 }
4019
4020 @Override
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07004021 public boolean isUserUnlockingOrUnlocked(int userId) {
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07004022 int state;
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00004023 synchronized (mUserStates) {
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07004024 state = mUserStates.get(userId, -1);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07004025 }
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07004026 // Special case, in the stopping/shutdown state user key can still be unlocked
4027 if (state == UserState.STATE_STOPPING || state == UserState.STATE_SHUTDOWN) {
4028 return StorageManager.isUserKeyUnlocked(userId);
4029 }
4030 return (state == UserState.STATE_RUNNING_UNLOCKING)
4031 || (state == UserState.STATE_RUNNING_UNLOCKED);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07004032 }
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08004033
4034 @Override
4035 public boolean isUserUnlocked(int userId) {
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07004036 int state;
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08004037 synchronized (mUserStates) {
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07004038 state = mUserStates.get(userId, -1);
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08004039 }
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07004040 // Special case, in the stopping/shutdown state user key can still be unlocked
4041 if (state == UserState.STATE_STOPPING || state == UserState.STATE_SHUTDOWN) {
4042 return StorageManager.isUserKeyUnlocked(userId);
4043 }
4044 return state == UserState.STATE_RUNNING_UNLOCKED;
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08004045 }
Todd Kennedy0eb97382017-10-03 16:57:22 -07004046
4047 @Override
4048 public boolean isUserInitialized(int userId) {
4049 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
4050 }
4051
4052 @Override
4053 public boolean exists(int userId) {
4054 return getUserInfoNoChecks(userId) != null;
4055 }
Sunny Goyal145c8f82018-02-15 14:27:09 -08004056
4057 @Override
4058 public boolean isProfileAccessible(int callingUserId, int targetUserId, String debugMsg,
4059 boolean throwSecurityException) {
4060 if (targetUserId == callingUserId) {
4061 return true;
4062 }
4063 synchronized (mUsersLock) {
4064 UserInfo callingUserInfo = getUserInfoLU(callingUserId);
4065 if (callingUserInfo == null || callingUserInfo.isManagedProfile()) {
4066 if (throwSecurityException) {
4067 throw new SecurityException(
4068 debugMsg + " for another profile "
4069 + targetUserId + " from " + callingUserId);
4070 }
4071 }
4072
4073 UserInfo targetUserInfo = getUserInfoLU(targetUserId);
4074 if (targetUserInfo == null || !targetUserInfo.isEnabled()) {
4075 // Do not throw any exception here as this could happen due to race conditions
4076 // between the system updating its state and the client getting notified.
4077 if (throwSecurityException) {
4078 Slog.w(LOG_TAG, debugMsg + " for disabled profile "
4079 + targetUserId + " from " + callingUserId);
4080 }
4081 return false;
4082 }
4083
4084 if (targetUserInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID ||
4085 targetUserInfo.profileGroupId != callingUserInfo.profileGroupId) {
4086 if (throwSecurityException) {
4087 throw new SecurityException(
4088 debugMsg + " for unrelated profile " + targetUserId);
4089 }
4090 return false;
4091 }
4092 }
4093 return true;
4094 }
4095
4096 @Override
4097 public int getProfileParentId(int userId) {
4098 synchronized (mUsersLock) {
4099 UserInfo profileParent = getProfileParentLU(userId);
4100 if (profileParent == null) {
4101 return userId;
4102 }
4103 return profileParent.id;
4104 }
4105 }
yuemingw1d13eae2018-01-30 17:27:54 +00004106
4107 @Override
4108 public boolean isSettingRestrictedForUser(String setting, @UserIdInt int userId,
4109 String value, int callingUid) {
4110 return UserRestrictionsUtils.isSettingRestrictedForUser(mContext, setting, userId,
4111 value, callingUid);
4112 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01004113 }
4114
4115 /* Remove all the users except of the system one. */
4116 private void removeNonSystemUsers() {
4117 ArrayList<UserInfo> usersToRemove = new ArrayList<>();
4118 synchronized (mUsersLock) {
4119 final int userSize = mUsers.size();
4120 for (int i = 0; i < userSize; i++) {
4121 UserInfo ui = mUsers.valueAt(i).info;
4122 if (ui.id != UserHandle.USER_SYSTEM) {
4123 usersToRemove.add(ui);
4124 }
4125 }
4126 }
4127 for (UserInfo ui: usersToRemove) {
4128 removeUser(ui.id);
4129 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07004130 }
Todd Kennedy60459ab2015-10-30 11:32:16 -07004131
4132 private class Shell extends ShellCommand {
4133 @Override
4134 public int onCommand(String cmd) {
4135 return onShellCommand(this, cmd);
4136 }
4137
4138 @Override
4139 public void onHelp() {
4140 final PrintWriter pw = getOutPrintWriter();
4141 pw.println("User manager (user) commands:");
4142 pw.println(" help");
4143 pw.println(" Print this help text.");
4144 pw.println("");
4145 pw.println(" list");
4146 pw.println(" Prints all users on the system.");
4147 }
4148 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08004149
4150 private static void debug(String message) {
4151 Log.d(LOG_TAG, message +
4152 (DBG_WITH_STACKTRACE ? " called at\n" + Debug.getCallers(10, " ") : ""));
4153 }
Kenny Guy02c89902016-11-15 19:36:38 +00004154
4155 @VisibleForTesting
4156 static int getMaxManagedProfiles() {
4157 // Allow overriding max managed profiles on debuggable builds for testing
4158 // of multiple profiles.
4159 if (!Build.IS_DEBUGGABLE) {
4160 return MAX_MANAGED_PROFILES;
4161 } else {
4162 return SystemProperties.getInt("persist.sys.max_profiles",
4163 MAX_MANAGED_PROFILES);
4164 }
4165 }
4166
Andreas Gampe2e8c7672018-07-20 13:01:08 -07004167 @GuardedBy("mUsersLock")
Kenny Guy02c89902016-11-15 19:36:38 +00004168 @VisibleForTesting
4169 int getFreeProfileBadgeLU(int parentUserId) {
4170 int maxManagedProfiles = getMaxManagedProfiles();
4171 boolean[] usedBadges = new boolean[maxManagedProfiles];
4172 final int userSize = mUsers.size();
4173 for (int i = 0; i < userSize; i++) {
4174 UserInfo ui = mUsers.valueAt(i).info;
4175 // Check which badge indexes are already used by this profile group.
4176 if (ui.isManagedProfile()
4177 && ui.profileGroupId == parentUserId
4178 && !mRemovingUserIds.get(ui.id)
4179 && ui.profileBadge < maxManagedProfiles) {
4180 usedBadges[ui.profileBadge] = true;
4181 }
4182 }
4183 for (int i = 0; i < maxManagedProfiles; i++) {
4184 if (!usedBadges[i]) {
4185 return i;
4186 }
4187 }
4188 return 0;
4189 }
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07004190
4191 /**
4192 * Checks if the given user has a managed profile associated with it.
4193 * @param userId The parent user
4194 * @return
4195 */
4196 boolean hasManagedProfile(int userId) {
4197 synchronized (mUsersLock) {
4198 UserInfo userInfo = getUserInfoLU(userId);
4199 final int userSize = mUsers.size();
4200 for (int i = 0; i < userSize; i++) {
4201 UserInfo profile = mUsers.valueAt(i).info;
4202 if (userId != profile.id && isProfileOf(userInfo, profile)) {
4203 return true;
4204 }
4205 }
4206 return false;
4207 }
4208 }
Tony Makd390ae92017-12-28 13:23:10 +00004209
4210 /**
4211 * Check if the calling package name matches with the calling UID, throw
4212 * {@link SecurityException} if not.
4213 */
4214 private void verifyCallingPackage(String callingPackage, int callingUid) {
4215 int packageUid = mPm.getPackageUid(callingPackage, 0, UserHandle.getUserId(callingUid));
4216 if (packageUid != callingUid) {
4217 throw new SecurityException("Specified package " + callingPackage
4218 + " does not match the calling uid " + callingUid);
4219 }
4220 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07004221}