blob: 768eb8f37549bcc9f5adb481fce43eb5b640db45 [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;
Tony Make3d1f652017-12-12 11:00:37 +000030import android.app.AppOpsManager;
Todd Kennedy60459ab2015-10-30 11:32:16 -070031import android.app.IActivityManager;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070032import android.app.IStopUserCallback;
Benjamin Franzf02420c2016-04-04 18:52:21 +010033import android.app.KeyguardManager;
Ricky Waib1dd80b2016-06-07 18:00:55 +010034import android.app.PendingIntent;
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;
Kenny Guy02c89902016-11-15 19:36:38 +000067import android.os.SystemProperties;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070068import android.os.UserHandle;
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070069import android.os.UserManager;
Pavel Grafov6a40f092016-10-25 15:46:51 +010070import android.os.UserManager.EnforcingUser;
Makoto Onuki068c54a2015-10-13 14:34:03 -070071import android.os.UserManagerInternal;
Makoto Onukid45a4a22015-11-02 17:17:38 -080072import android.os.UserManagerInternal.UserRestrictionsListener;
Paul Crowley85e4e812015-05-19 12:42:00 +010073import android.os.storage.StorageManager;
Amith Yamasanid04aaa32016-06-13 12:09:36 -070074import android.security.GateKeeper;
75import android.service.gatekeeper.IGateKeeperService;
Amith Yamasani2a003292012-08-14 18:25:45 -070076import android.util.AtomicFile;
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -070077import android.util.IntArray;
Amith Yamasani655d0e22013-06-12 14:19:10 -070078import android.util.Log;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070079import android.util.Slog;
80import android.util.SparseArray;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080081import android.util.SparseBooleanArray;
Amith Yamasaniea1b9d72016-05-27 15:57:38 +000082import android.util.SparseIntArray;
Amith Yamasani920ace02012-09-20 22:15:37 -070083import android.util.TimeUtils;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070084import android.util.Xml;
85
Makoto Onuki068c54a2015-10-13 14:34:03 -070086import com.android.internal.annotations.GuardedBy;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070087import com.android.internal.annotations.VisibleForTesting;
Jason Monk62062992014-05-06 09:55:28 -040088import com.android.internal.app.IAppOpsService;
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -080089import com.android.internal.logging.MetricsLogger;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -060090import com.android.internal.util.DumpUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080091import com.android.internal.util.FastXmlSerializer;
Makoto Onuki068c54a2015-10-13 14:34:03 -070092import com.android.internal.util.Preconditions;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070093import com.android.internal.util.XmlUtils;
Clara Bayarri10ad84a2015-12-01 17:38:05 +000094import com.android.internal.widget.LockPatternUtils;
Amith Yamasani515d4062015-09-28 11:30:06 -070095import com.android.server.LocalServices;
Jeff Sharkey5f3e9342017-03-13 14:53:11 -060096import com.android.server.LockGuard;
Amith Yamasanid04aaa32016-06-13 12:09:36 -070097import com.android.server.SystemService;
Amith Yamasaniea1b9d72016-05-27 15:57:38 +000098import com.android.server.am.UserState;
Suprabh Shuklac5e057c2016-08-08 16:22:44 -070099import com.android.server.storage.DeviceStorageMonitorInternal;
Tony Mak6dc428f2016-10-10 15:48:27 +0100100
Jeff Sharkey47f71082016-02-01 17:03:54 -0700101import libcore.io.IoUtils;
102import libcore.util.Objects;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800103
104import org.xmlpull.v1.XmlPullParser;
105import org.xmlpull.v1.XmlPullParserException;
106import org.xmlpull.v1.XmlSerializer;
107
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700108import java.io.BufferedOutputStream;
109import java.io.File;
Amith Yamasani920ace02012-09-20 22:15:37 -0700110import java.io.FileDescriptor;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700111import java.io.FileInputStream;
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700112import java.io.FileNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700113import java.io.FileOutputStream;
Tony Mak64fd8c02017-12-01 19:11:59 +0000114import java.io.IOException;
Kenny Guy02c89902016-11-15 19:36:38 +0000115import java.io.InputStream;
116import java.io.OutputStream;
Amith Yamasani920ace02012-09-20 22:15:37 -0700117import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100118import java.nio.charset.StandardCharsets;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700119import java.util.ArrayList;
Pavel Grafov6a40f092016-10-25 15:46:51 +0100120import java.util.Collections;
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700121import java.util.LinkedList;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700122import java.util.List;
123
Makoto Onuki068c54a2015-10-13 14:34:03 -0700124/**
125 * Service for {@link UserManager}.
126 *
127 * Method naming convention:
Fyodor Kupolov82402752015-10-28 14:54:51 -0700128 * <ul>
Fyodor Kupolovd31cee92017-09-05 16:31:08 -0700129 * <li> Methods suffixed with "LAr" should be called within the {@link #mAppRestrictionsLock} lock.
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800130 * <li> Methods suffixed with "LP" should be called within the {@link #mPackagesLock} lock.
Fyodor Kupolov82402752015-10-28 14:54:51 -0700131 * <li> Methods suffixed with "LR" should be called within the {@link #mRestrictionsLock} lock.
132 * <li> Methods suffixed with "LU" should be called within the {@link #mUsersLock} lock.
133 * </ul>
Makoto Onuki068c54a2015-10-13 14:34:03 -0700134 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700135public class UserManagerService extends IUserManager.Stub {
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700136
Amith Yamasani2a003292012-08-14 18:25:45 -0700137 private static final String LOG_TAG = "UserManagerService";
Makoto Onuki81c61ea2016-01-22 11:22:26 -0800138 static final boolean DBG = false; // DO NOT SUBMIT WITH TRUE
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800139 private static final boolean DBG_WITH_STACKTRACE = false; // DO NOT SUBMIT WITH TRUE
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700140 // Can be used for manual testing of id recycling
141 private static final boolean RELEASE_DELETED_USER_ID = false; // DO NOT SUBMIT WITH TRUE
Amith Yamasani16389312012-10-17 21:20:14 -0700142
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700143 private static final String TAG_NAME = "name";
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800144 private static final String TAG_ACCOUNT = "account";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700145 private static final String ATTR_FLAGS = "flags";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700146 private static final String ATTR_ICON_PATH = "icon";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700147 private static final String ATTR_ID = "id";
Amith Yamasani920ace02012-09-20 22:15:37 -0700148 private static final String ATTR_CREATION_TIME = "created";
149 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -0600150 private static final String ATTR_LAST_LOGGED_IN_FINGERPRINT = "lastLoggedInFingerprint";
Amith Yamasani2a003292012-08-14 18:25:45 -0700151 private static final String ATTR_SERIAL_NO = "serialNumber";
152 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700153 private static final String ATTR_PARTIAL = "partial";
Adam Lesinskieddeb492014-09-08 17:50:03 -0700154 private static final String ATTR_GUEST_TO_REMOVE = "guestToRemove";
Amith Yamasani6f34b412012-10-22 18:19:27 -0700155 private static final String ATTR_USER_VERSION = "version";
Kenny Guy2a764942014-04-02 13:29:20 +0100156 private static final String ATTR_PROFILE_GROUP_ID = "profileGroupId";
Kenny Guy02c89902016-11-15 19:36:38 +0000157 private static final String ATTR_PROFILE_BADGE = "profileBadge";
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700158 private static final String ATTR_RESTRICTED_PROFILE_PARENT_ID = "restrictedProfileParentId";
Amith Yamasani12747872015-12-07 14:19:49 -0800159 private static final String ATTR_SEED_ACCOUNT_NAME = "seedAccountName";
160 private static final String ATTR_SEED_ACCOUNT_TYPE = "seedAccountType";
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530161 private static final String TAG_GUEST_RESTRICTIONS = "guestRestrictions";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700162 private static final String TAG_USERS = "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700163 private static final String TAG_USER = "user";
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800164 private static final String TAG_RESTRICTIONS = "restrictions";
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800165 private static final String TAG_DEVICE_POLICY_RESTRICTIONS = "device_policy_restrictions";
Pavel Grafov6a40f092016-10-25 15:46:51 +0100166 private static final String TAG_DEVICE_POLICY_GLOBAL_RESTRICTIONS =
167 "device_policy_global_restrictions";
168 /** Legacy name for device owner id tag. */
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +0100169 private static final String TAG_GLOBAL_RESTRICTION_OWNER_ID = "globalRestrictionOwnerUserId";
Pavel Grafov6a40f092016-10-25 15:46:51 +0100170 private static final String TAG_DEVICE_OWNER_USER_ID = "deviceOwnerUserId";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800171 private static final String TAG_ENTRY = "entry";
172 private static final String TAG_VALUE = "value";
Amith Yamasani12747872015-12-07 14:19:49 -0800173 private static final String TAG_SEED_ACCOUNT_OPTIONS = "seedAccountOptions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800174 private static final String ATTR_KEY = "key";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700175 private static final String ATTR_VALUE_TYPE = "type";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800176 private static final String ATTR_MULTIPLE = "m";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700177
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700178 private static final String ATTR_TYPE_STRING_ARRAY = "sa";
179 private static final String ATTR_TYPE_STRING = "s";
180 private static final String ATTR_TYPE_BOOLEAN = "b";
Amith Yamasani5b5aa402014-06-01 20:10:14 -0700181 private static final String ATTR_TYPE_INTEGER = "i";
Fyodor Kupolov262f9952015-03-23 18:55:11 -0700182 private static final String ATTR_TYPE_BUNDLE = "B";
183 private static final String ATTR_TYPE_BUNDLE_ARRAY = "BA";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700184
Amith Yamasani0b285492011-04-14 17:35:23 -0700185 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700186 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700187 private static final String USER_PHOTO_FILENAME = "photo.png";
Adrian Roos1bdff912015-02-17 15:51:35 +0100188 private static final String USER_PHOTO_FILENAME_TMP = USER_PHOTO_FILENAME + ".tmp";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700189
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800190 private static final String RESTRICTIONS_FILE_PREFIX = "res_";
Amith Yamasanifc95e702013-09-26 13:20:17 -0700191 private static final String XML_SUFFIX = ".xml";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800192
Sudheer Shankaf5cea032016-06-08 17:13:24 -0700193 private static final int ALLOWED_FLAGS_FOR_CREATE_USERS_PERMISSION =
194 UserInfo.FLAG_MANAGED_PROFILE
195 | UserInfo.FLAG_EPHEMERAL
196 | UserInfo.FLAG_RESTRICTED
Sudheer Shanka234d1af2016-08-26 15:42:53 -0700197 | UserInfo.FLAG_GUEST
198 | UserInfo.FLAG_DEMO;
Sudheer Shankaf5cea032016-06-08 17:13:24 -0700199
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700200 @VisibleForTesting
201 static final int MIN_USER_ID = 10;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700202 // We need to keep process uid within Integer.MAX_VALUE.
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700203 @VisibleForTesting
204 static final int MAX_USER_ID = Integer.MAX_VALUE / UserHandle.PER_USER_RANGE;
205
206 // Max size of the queue of recently removed users
207 @VisibleForTesting
208 static final int MAX_RECENTLY_REMOVED_IDS_SIZE = 100;
Amith Yamasani634cf312012-10-04 17:34:21 -0700209
Pavel Grafov6a40f092016-10-25 15:46:51 +0100210 private static final int USER_VERSION = 7;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700211
Amith Yamasani920ace02012-09-20 22:15:37 -0700212 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
213
Nicolas Prevotb8186812015-08-06 15:00:03 +0100214 // Maximum number of managed profiles permitted per user is 1. This cannot be increased
Amith Yamasani95ab7842014-08-11 17:09:26 -0700215 // without first making sure that the rest of the framework is prepared for it.
Kenny Guy02c89902016-11-15 19:36:38 +0000216 @VisibleForTesting
217 static final int MAX_MANAGED_PROFILES = 1;
Amith Yamasani95ab7842014-08-11 17:09:26 -0700218
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800219 static final int WRITE_USER_MSG = 1;
220 static final int WRITE_USER_DELAY = 2*1000; // 2 seconds
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530221
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -0800222 // Tron counters
223 private static final String TRON_GUEST_CREATED = "users_guest_created";
224 private static final String TRON_USER_CREATED = "users_user_created";
Christine Franks88220562017-05-24 11:11:21 -0700225 private static final String TRON_DEMO_CREATED = "users_demo_created";
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -0800226
Dianne Hackborn4428e172012-08-24 17:43:05 -0700227 private final Context mContext;
228 private final PackageManagerService mPm;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700229 private final Object mPackagesLock;
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800230 private final UserDataPreparer mUserDataPreparer;
Fyodor Kupolov82402752015-10-28 14:54:51 -0700231 // Short-term lock for internal state, when interaction/sync with PM is not required
Jeff Sharkey5f3e9342017-03-13 14:53:11 -0600232 private final Object mUsersLock = LockGuard.installNewLock(LockGuard.INDEX_USER);
Fyodor Kupolov82402752015-10-28 14:54:51 -0700233 private final Object mRestrictionsLock = new Object();
Fyodor Kupolovd31cee92017-09-05 16:31:08 -0700234 // Used for serializing access to app restriction files
235 private final Object mAppRestrictionsLock = new Object();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700236
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800237 private final Handler mHandler;
238
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700239 private final File mUsersDir;
240 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700241
Svet Ganov9cea80cd2016-02-16 11:47:00 -0800242 private static final IBinder mUserRestriconToken = new Binder();
243
Makoto Onuki068c54a2015-10-13 14:34:03 -0700244 /**
Amith Yamasani12747872015-12-07 14:19:49 -0800245 * User-related information that is used for persisting to flash. Only UserInfo is
246 * directly exposed to other system apps.
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800247 */
Kenny Guy02c89902016-11-15 19:36:38 +0000248 @VisibleForTesting
249 static class UserData {
Amith Yamasani12747872015-12-07 14:19:49 -0800250 // Basic user information and properties
251 UserInfo info;
252 // Account name used when there is a strong association between a user and an account
253 String account;
254 // Account information for seeding into a newly created user. This could also be
255 // used for login validation for an existing user, for updating their credentials.
256 // In the latter case, data may not need to be persisted as it is only valid for the
257 // current login session.
258 String seedAccountName;
259 String seedAccountType;
260 PersistableBundle seedAccountOptions;
261 // Whether to perist the seed account information to be available after a boot
262 boolean persistSeedData;
263
264 void clearSeedAccountData() {
265 seedAccountName = null;
266 seedAccountType = null;
267 seedAccountOptions = null;
268 persistSeedData = false;
269 }
270 }
271
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800272 @GuardedBy("mUsersLock")
Amith Yamasani12747872015-12-07 14:19:49 -0800273 private final SparseArray<UserData> mUsers = new SparseArray<>();
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800274
275 /**
Makoto Onuki068c54a2015-10-13 14:34:03 -0700276 * User restrictions set via UserManager. This doesn't include restrictions set by
Pavel Grafov6a40f092016-10-25 15:46:51 +0100277 * device owner / profile owners. Only non-empty restriction bundles are stored.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700278 *
279 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
280 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
281 * maybe shared between {@link #mBaseUserRestrictions} and
282 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
283 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700284 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700285 */
286 @GuardedBy("mRestrictionsLock")
287 private final SparseArray<Bundle> mBaseUserRestrictions = new SparseArray<>();
288
289 /**
290 * Cached user restrictions that are in effect -- i.e. {@link #mBaseUserRestrictions} combined
291 * with device / profile owner restrictions. We'll initialize it lazily; use
292 * {@link #getEffectiveUserRestrictions} to access it.
293 *
294 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
295 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
296 * maybe shared between {@link #mBaseUserRestrictions} and
297 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
298 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700299 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700300 */
301 @GuardedBy("mRestrictionsLock")
302 private final SparseArray<Bundle> mCachedEffectiveUserRestrictions = new SparseArray<>();
303
Makoto Onuki4f160732015-10-27 17:15:38 -0700304 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800305 * User restrictions that have already been applied in
306 * {@link #updateUserRestrictionsInternalLR(Bundle, int)}. We use it to detect restrictions
307 * that have changed since the last
308 * {@link #updateUserRestrictionsInternalLR(Bundle, int)} call.
Makoto Onuki4f160732015-10-27 17:15:38 -0700309 */
310 @GuardedBy("mRestrictionsLock")
311 private final SparseArray<Bundle> mAppliedUserRestrictions = new SparseArray<>();
312
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800313 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800314 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
Pavel Grafov6a40f092016-10-25 15:46:51 +0100315 * that should be applied to all users, including guests. Only non-empty restriction bundles are
316 * stored.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800317 */
318 @GuardedBy("mRestrictionsLock")
Pavel Grafov6a40f092016-10-25 15:46:51 +0100319 private final SparseArray<Bundle> mDevicePolicyGlobalUserRestrictions = new SparseArray<>();
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800320
321 /**
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +0100322 * Id of the user that set global restrictions.
323 */
324 @GuardedBy("mRestrictionsLock")
Pavel Grafov6a40f092016-10-25 15:46:51 +0100325 private int mDeviceOwnerUserId = UserHandle.USER_NULL;
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +0100326
327 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800328 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
Pavel Grafov6a40f092016-10-25 15:46:51 +0100329 * for each user. Only non-empty restriction bundles are stored.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800330 */
331 @GuardedBy("mRestrictionsLock")
332 private final SparseArray<Bundle> mDevicePolicyLocalUserRestrictions = new SparseArray<>();
333
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800334 @GuardedBy("mGuestRestrictions")
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530335 private final Bundle mGuestRestrictions = new Bundle();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800336
337 /**
338 * Set of user IDs being actively removed. Removed IDs linger in this set
339 * for several seconds to work around a VFS caching issue.
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700340 * Use {@link #addRemovingUserIdLocked(int)} to add elements to this array
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800341 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700342 @GuardedBy("mUsersLock")
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800343 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700344
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700345 /**
346 * Queue of recently removed userIds. Used for recycling of userIds
347 */
348 @GuardedBy("mUsersLock")
349 private final LinkedList<Integer> mRecentlyRemovedIds = new LinkedList<>();
350
Fyodor Kupolov82402752015-10-28 14:54:51 -0700351 @GuardedBy("mUsersLock")
Amith Yamasani0b285492011-04-14 17:35:23 -0700352 private int[] mUserIds;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800353 @GuardedBy("mPackagesLock")
Amith Yamasani2a003292012-08-14 18:25:45 -0700354 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700355 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700356
Jason Monk62062992014-05-06 09:55:28 -0400357 private IAppOpsService mAppOpsService;
358
Makoto Onuki068c54a2015-10-13 14:34:03 -0700359 private final LocalService mLocalService;
360
Makoto Onukie7927da2015-11-25 10:05:17 -0800361 @GuardedBy("mUsersLock")
362 private boolean mIsDeviceManaged;
363
364 @GuardedBy("mUsersLock")
365 private final SparseBooleanArray mIsUserManaged = new SparseBooleanArray();
366
Makoto Onukid45a4a22015-11-02 17:17:38 -0800367 @GuardedBy("mUserRestrictionsListeners")
368 private final ArrayList<UserRestrictionsListener> mUserRestrictionsListeners =
369 new ArrayList<>();
370
Clara Bayarria1771112015-12-18 16:29:18 +0000371 private final LockPatternUtils mLockPatternUtils;
372
Ricky Waib1dd80b2016-06-07 18:00:55 +0100373 private final String ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK =
374 "com.android.server.pm.DISABLE_QUIET_MODE_AFTER_UNLOCK";
375
376 private final BroadcastReceiver mDisableQuietModeCallback = new BroadcastReceiver() {
377 @Override
378 public void onReceive(Context context, Intent intent) {
Tony Mak64fd8c02017-12-01 19:11:59 +0000379 if (!ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK.equals(intent.getAction())) {
380 return;
Ricky Waib1dd80b2016-06-07 18:00:55 +0100381 }
Tony Mak64fd8c02017-12-01 19:11:59 +0000382 final IntentSender target = intent.getParcelableExtra(Intent.EXTRA_INTENT);
383 final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_ID, UserHandle.USER_NULL);
384 setQuietModeEnabled(userHandle, false, target);
Ricky Waib1dd80b2016-06-07 18:00:55 +0100385 }
386 };
387
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +0100388 /**
Tony Mak64fd8c02017-12-01 19:11:59 +0000389 * Start an {@link IntentSender} when user is unlocked after disabling quiet mode.
390 *
Tony Make3d1f652017-12-12 11:00:37 +0000391 * @see {@link #trySetQuietModeEnabled(String, boolean, int, IntentSender)}
Tony Mak64fd8c02017-12-01 19:11:59 +0000392 */
393 private class DisableQuietModeUserUnlockedCallback extends IProgressListener.Stub {
394 private final IntentSender mTarget;
395
396 public DisableQuietModeUserUnlockedCallback(IntentSender target) {
397 Preconditions.checkNotNull(target);
398 mTarget = target;
399 }
400
401 @Override
402 public void onStarted(int id, Bundle extras) {}
403
404 @Override
405 public void onProgress(int id, int progress, Bundle extras) {}
406
407 @Override
408 public void onFinished(int id, Bundle extras) {
409 try {
410 mContext.startIntentSender(mTarget, null, 0, 0, 0);
411 } catch (IntentSender.SendIntentException e) {
412 Slog.e(LOG_TAG, "Failed to start the target in the callback", e);
413 }
414 }
415 }
416
417 /**
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +0100418 * Whether all users should be created ephemeral.
419 */
420 @GuardedBy("mUsersLock")
421 private boolean mForceEphemeralUsers;
422
Amith Yamasaniea1b9d72016-05-27 15:57:38 +0000423 @GuardedBy("mUserStates")
424 private final SparseIntArray mUserStates = new SparseIntArray();
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -0700425
Amith Yamasani258848d2012-08-10 17:06:33 -0700426 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700427
Dianne Hackborn4428e172012-08-24 17:43:05 -0700428 public static UserManagerService getInstance() {
429 synchronized (UserManagerService.class) {
430 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700431 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700432 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700433
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700434 public static class LifeCycle extends SystemService {
435
436 private UserManagerService mUms;
437
438 /**
439 * @param context
440 */
441 public LifeCycle(Context context) {
442 super(context);
443 }
444
445 @Override
446 public void onStart() {
447 mUms = UserManagerService.getInstance();
448 publishBinderService(Context.USER_SERVICE, mUms);
449 }
450
451 @Override
452 public void onBootPhase(int phase) {
453 if (phase == SystemService.PHASE_ACTIVITY_MANAGER_READY) {
454 mUms.cleanupPartialUsers();
455 }
456 }
457 }
458
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700459 // TODO b/28848102 Add support for test dependencies injection
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800460 @VisibleForTesting
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700461 UserManagerService(Context context) {
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800462 this(context, null, null, new Object(), context.getCacheDir());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700463 }
464
Dianne Hackborn4428e172012-08-24 17:43:05 -0700465 /**
466 * Called by package manager to create the service. This is closely
467 * associated with the package manager, and the given lock is the
468 * package manager's own lock.
469 */
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800470 UserManagerService(Context context, PackageManagerService pm, UserDataPreparer userDataPreparer,
471 Object packagesLock) {
472 this(context, pm, userDataPreparer, packagesLock, Environment.getDataDirectory());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700473 }
474
Dianne Hackborn4428e172012-08-24 17:43:05 -0700475 private UserManagerService(Context context, PackageManagerService pm,
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800476 UserDataPreparer userDataPreparer, Object packagesLock, File dataDir) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700477 mContext = context;
478 mPm = pm;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700479 mPackagesLock = packagesLock;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800480 mHandler = new MainHandler();
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800481 mUserDataPreparer = userDataPreparer;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800482 synchronized (mPackagesLock) {
483 mUsersDir = new File(dataDir, USER_INFO_DIR);
484 mUsersDir.mkdirs();
485 // Make zeroth user directory, for services to migrate their files to that location
486 File userZeroDir = new File(mUsersDir, String.valueOf(UserHandle.USER_SYSTEM));
487 userZeroDir.mkdirs();
488 FileUtils.setPermissions(mUsersDir.toString(),
489 FileUtils.S_IRWXU | FileUtils.S_IRWXG | FileUtils.S_IROTH | FileUtils.S_IXOTH,
490 -1, -1);
491 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
492 initDefaultGuestRestrictions();
493 readUserListLP();
494 sInstance = this;
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700495 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700496 mLocalService = new LocalService();
497 LocalServices.addService(UserManagerInternal.class, mLocalService);
Clara Bayarria1771112015-12-18 16:29:18 +0000498 mLockPatternUtils = new LockPatternUtils(mContext);
Amith Yamasaniea1b9d72016-05-27 15:57:38 +0000499 mUserStates.put(UserHandle.USER_SYSTEM, UserState.STATE_BOOTING);
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700500 }
501
502 void systemReady() {
Jason Monk62062992014-05-06 09:55:28 -0400503 mAppOpsService = IAppOpsService.Stub.asInterface(
504 ServiceManager.getService(Context.APP_OPS_SERVICE));
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800505
506 synchronized (mRestrictionsLock) {
507 applyUserRestrictionsLR(UserHandle.USER_SYSTEM);
Jason Monk62062992014-05-06 09:55:28 -0400508 }
Samuel Tand9453b82016-03-14 15:57:02 -0700509
510 UserInfo currentGuestUser = findCurrentGuestUser();
511 if (currentGuestUser != null && !hasUserRestriction(
512 UserManager.DISALLOW_CONFIG_WIFI, currentGuestUser.id)) {
513 // If a guest user currently exists, apply the DISALLOW_CONFIG_WIFI option
514 // to it, in case this guest was created in a previous version where this
515 // user restriction was not a default guest restriction.
516 setUserRestriction(UserManager.DISALLOW_CONFIG_WIFI, true, currentGuestUser.id);
517 }
Amith Yamasanieb437d42016-04-29 09:31:25 -0700518
Ricky Waib1dd80b2016-06-07 18:00:55 +0100519 mContext.registerReceiver(mDisableQuietModeCallback,
520 new IntentFilter(ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK),
521 null, mHandler);
Amith Yamasani258848d2012-08-10 17:06:33 -0700522 }
523
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700524 void cleanupPartialUsers() {
525 // Prune out any partially created, partially removed and ephemeral users.
526 ArrayList<UserInfo> partials = new ArrayList<>();
527 synchronized (mUsersLock) {
528 final int userSize = mUsers.size();
529 for (int i = 0; i < userSize; i++) {
530 UserInfo ui = mUsers.valueAt(i).info;
531 if ((ui.partial || ui.guestToRemove || ui.isEphemeral()) && i != 0) {
532 partials.add(ui);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700533 addRemovingUserIdLocked(ui.id);
Amith Yamasaniae261892016-06-27 10:40:09 -0700534 ui.partial = true;
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700535 }
536 }
537 }
538 final int partialsSize = partials.size();
539 for (int i = 0; i < partialsSize; i++) {
540 UserInfo ui = partials.get(i);
541 Slog.w(LOG_TAG, "Removing partially created user " + ui.id
542 + " (name=" + ui.name + ")");
543 removeUserState(ui.id);
544 }
545 }
546
Amith Yamasani258848d2012-08-10 17:06:33 -0700547 @Override
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800548 public String getUserAccount(int userId) {
549 checkManageUserAndAcrossUsersFullPermission("get user account");
550 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800551 return mUsers.get(userId).account;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800552 }
553 }
554
555 @Override
556 public void setUserAccount(int userId, String accountName) {
557 checkManageUserAndAcrossUsersFullPermission("set user account");
Amith Yamasani12747872015-12-07 14:19:49 -0800558 UserData userToUpdate = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800559 synchronized (mPackagesLock) {
560 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800561 final UserData userData = mUsers.get(userId);
562 if (userData == null) {
563 Slog.e(LOG_TAG, "User not found for setting user account: u" + userId);
564 return;
565 }
566 String currentAccount = userData.account;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800567 if (!Objects.equal(currentAccount, accountName)) {
Amith Yamasani12747872015-12-07 14:19:49 -0800568 userData.account = accountName;
569 userToUpdate = userData;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800570 }
571 }
572
573 if (userToUpdate != null) {
574 writeUserLP(userToUpdate);
575 }
576 }
577 }
578
579 @Override
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700580 public UserInfo getPrimaryUser() {
581 checkManageUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700582 synchronized (mUsersLock) {
Amith Yamasani515d4062015-09-28 11:30:06 -0700583 final int userSize = mUsers.size();
584 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800585 UserInfo ui = mUsers.valueAt(i).info;
Xiaohui Chend3e9e182015-11-18 13:37:32 -0800586 if (ui.isPrimary() && !mRemovingUserIds.get(ui.id)) {
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700587 return ui;
588 }
589 }
590 }
591 return null;
592 }
593
594 @Override
Xiaohui Chen594f2082015-08-18 11:04:20 -0700595 public @NonNull List<UserInfo> getUsers(boolean excludeDying) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -0700596 checkManageOrCreateUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700597 synchronized (mUsersLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700598 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasani515d4062015-09-28 11:30:06 -0700599 final int userSize = mUsers.size();
600 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800601 UserInfo ui = mUsers.valueAt(i).info;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700602 if (ui.partial) {
603 continue;
604 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800605 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Amith Yamasani6f48d6e2016-03-23 14:28:25 -0700606 users.add(userWithName(ui));
Amith Yamasani920ace02012-09-20 22:15:37 -0700607 }
Amith Yamasani13593602012-03-22 16:16:17 -0700608 }
609 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700610 }
Amith Yamasani13593602012-03-22 16:16:17 -0700611 }
612
Amith Yamasani258848d2012-08-10 17:06:33 -0700613 @Override
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100614 public List<UserInfo> getProfiles(int userId, boolean enabledOnly) {
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700615 boolean returnFullInfo = true;
Amith Yamasani4f582632014-02-19 14:31:52 -0800616 if (userId != UserHandle.getCallingUserId()) {
Sudheer Shanka74680912016-07-29 11:03:37 -0700617 checkManageOrCreateUsersPermission("getting profiles related to user " + userId);
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700618 } else {
619 returnFullInfo = hasManageUsersPermission();
Amith Yamasani4f582632014-02-19 14:31:52 -0800620 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700621 final long ident = Binder.clearCallingIdentity();
622 try {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700623 synchronized (mUsersLock) {
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700624 return getProfilesLU(userId, enabledOnly, returnFullInfo);
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100625 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700626 } finally {
627 Binder.restoreCallingIdentity(ident);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000628 }
629 }
630
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700631 @Override
632 public int[] getProfileIds(int userId, boolean enabledOnly) {
633 if (userId != UserHandle.getCallingUserId()) {
bohu12d23a12016-09-26 16:20:07 -0700634 checkManageOrCreateUsersPermission("getting profiles related to user " + userId);
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700635 }
636 final long ident = Binder.clearCallingIdentity();
637 try {
638 synchronized (mUsersLock) {
639 return getProfileIdsLU(userId, enabledOnly).toArray();
640 }
641 } finally {
642 Binder.restoreCallingIdentity(ident);
643 }
644 }
645
Amith Yamasanibe465322014-04-24 13:45:17 -0700646 /** Assume permissions already checked and caller's identity cleared */
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700647 private List<UserInfo> getProfilesLU(int userId, boolean enabledOnly, boolean fullInfo) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700648 IntArray profileIds = getProfileIdsLU(userId, enabledOnly);
649 ArrayList<UserInfo> users = new ArrayList<>(profileIds.size());
650 for (int i = 0; i < profileIds.size(); i++) {
651 int profileId = profileIds.get(i);
652 UserInfo userInfo = mUsers.get(profileId).info;
653 // If full info is not required - clear PII data to prevent 3P apps from reading it
654 if (!fullInfo) {
655 userInfo = new UserInfo(userInfo);
656 userInfo.name = null;
657 userInfo.iconPath = null;
658 } else {
659 userInfo = userWithName(userInfo);
660 }
661 users.add(userInfo);
662 }
663 return users;
664 }
665
666 /**
667 * Assume permissions already checked and caller's identity cleared
668 */
669 private IntArray getProfileIdsLU(int userId, boolean enabledOnly) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700670 UserInfo user = getUserInfoLU(userId);
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700671 IntArray result = new IntArray(mUsers.size());
Amith Yamasanidda003f2014-08-28 18:06:51 -0700672 if (user == null) {
673 // Probably a dying user
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700674 return result;
Amith Yamasanidda003f2014-08-28 18:06:51 -0700675 }
Amith Yamasani515d4062015-09-28 11:30:06 -0700676 final int userSize = mUsers.size();
677 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800678 UserInfo profile = mUsers.valueAt(i).info;
Amith Yamasanibe465322014-04-24 13:45:17 -0700679 if (!isProfileOf(user, profile)) {
680 continue;
681 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100682 if (enabledOnly && !profile.isEnabled()) {
683 continue;
Amith Yamasanibe465322014-04-24 13:45:17 -0700684 }
Amith Yamasani70fcf0c2014-07-11 08:40:19 -0700685 if (mRemovingUserIds.get(profile.id)) {
686 continue;
687 }
Tony Mak80189cd2016-04-05 17:21:42 +0100688 if (profile.partial) {
689 continue;
690 }
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700691 result.add(profile.id);
Amith Yamasanibe465322014-04-24 13:45:17 -0700692 }
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700693 return result;
Amith Yamasanibe465322014-04-24 13:45:17 -0700694 }
695
Jessica Hummelbe81c802014-04-22 15:49:22 +0100696 @Override
Andres Moralesc5548c02015-08-05 10:23:12 -0700697 public int getCredentialOwnerProfile(int userHandle) {
698 checkManageUsersPermission("get the credential owner");
Clara Bayarria1771112015-12-18 16:29:18 +0000699 if (!mLockPatternUtils.isSeparateProfileChallengeEnabled(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700700 synchronized (mUsersLock) {
701 UserInfo profileParent = getProfileParentLU(userHandle);
Andres Moralesc5548c02015-08-05 10:23:12 -0700702 if (profileParent != null) {
703 return profileParent.id;
704 }
705 }
706 }
707
708 return userHandle;
709 }
710
711 @Override
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700712 public boolean isSameProfileGroup(int userId, int otherUserId) {
713 if (userId == otherUserId) return true;
714 checkManageUsersPermission("check if in the same profile group");
Fyodor Kupolov0fb772e2016-10-13 16:27:34 -0700715 return isSameProfileGroupNoChecks(userId, otherUserId);
716 }
717
718 private boolean isSameProfileGroupNoChecks(int userId, int otherUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700719 synchronized (mUsersLock) {
720 UserInfo userInfo = getUserInfoLU(userId);
721 if (userInfo == null || userInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
722 return false;
723 }
724 UserInfo otherUserInfo = getUserInfoLU(otherUserId);
725 if (otherUserInfo == null
726 || otherUserInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
727 return false;
728 }
729 return userInfo.profileGroupId == otherUserInfo.profileGroupId;
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700730 }
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700731 }
732
733 @Override
Jessica Hummelbe81c802014-04-22 15:49:22 +0100734 public UserInfo getProfileParent(int userHandle) {
735 checkManageUsersPermission("get the profile parent");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700736 synchronized (mUsersLock) {
737 return getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700738 }
739 }
740
Jakub Pawlowski0f1f5b72017-11-15 14:50:43 -0800741 @Override
742 public int getProfileParentId(int userHandle) {
743 checkManageUsersPermission("get the profile parent");
744 synchronized (mUsersLock) {
745 UserInfo profileParent = getProfileParentLU(userHandle);
746 if (profileParent == null) {
747 return userHandle;
748 }
749
750 return profileParent.id;
751 }
752 }
753
Fyodor Kupolov82402752015-10-28 14:54:51 -0700754 private UserInfo getProfileParentLU(int userHandle) {
755 UserInfo profile = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700756 if (profile == null) {
757 return null;
758 }
759 int parentUserId = profile.profileGroupId;
Amith Yamasani801e3422017-01-25 11:35:44 -0800760 if (parentUserId == userHandle || parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700761 return null;
762 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700763 return getUserInfoLU(parentUserId);
Jessica Hummelbe81c802014-04-22 15:49:22 +0100764 }
765 }
766
Fyodor Kupolov82402752015-10-28 14:54:51 -0700767 private static boolean isProfileOf(UserInfo user, UserInfo profile) {
Kenny Guy2a764942014-04-02 13:29:20 +0100768 return user.id == profile.id ||
769 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
770 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000771 }
772
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000773 private void broadcastProfileAvailabilityChanges(UserHandle profileHandle,
Rubin Xuf13c9802016-01-21 18:06:00 +0000774 UserHandle parentHandle, boolean inQuietMode) {
Rubin Xue95057a2016-04-01 16:49:25 +0100775 Intent intent = new Intent();
776 if (inQuietMode) {
777 intent.setAction(Intent.ACTION_MANAGED_PROFILE_UNAVAILABLE);
778 } else {
779 intent.setAction(Intent.ACTION_MANAGED_PROFILE_AVAILABLE);
780 }
Rubin Xuf13c9802016-01-21 18:06:00 +0000781 intent.putExtra(Intent.EXTRA_QUIET_MODE, inQuietMode);
782 intent.putExtra(Intent.EXTRA_USER, profileHandle);
783 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileHandle.getIdentifier());
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000784 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Rubin Xuf13c9802016-01-21 18:06:00 +0000785 mContext.sendBroadcastAsUser(intent, parentHandle);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000786 }
787
788 @Override
Tony Make3d1f652017-12-12 11:00:37 +0000789 public boolean trySetQuietModeEnabled(@NonNull String callingPackage, boolean enableQuietMode,
790 int userHandle, @Nullable IntentSender target) {
791 Preconditions.checkNotNull(callingPackage);
792
Tony Makb7e6fd42017-12-05 19:40:28 +0000793 if (enableQuietMode && target != null) {
794 throw new IllegalArgumentException(
795 "target should only be specified when we are disabling quiet mode.");
796 }
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000797
Tony Make3d1f652017-12-12 11:00:37 +0000798 if (!isAllowedToSetWorkMode(callingPackage, Binder.getCallingUid())) {
799 throw new SecurityException("Not allowed to call trySetQuietModeEnabled, "
800 + "caller is foreground default launcher "
801 + "nor with MANAGE_USERS/MODIFY_QUIET_MODE permission");
802 }
Tony Makb7e6fd42017-12-05 19:40:28 +0000803
804 final long identity = Binder.clearCallingIdentity();
805 try {
806 if (enableQuietMode) {
807 setQuietModeEnabled(userHandle, true /* enableQuietMode */, target);
808 return true;
809 } else {
810 boolean needToShowConfirmCredential =
811 mLockPatternUtils.isSecure(userHandle)
812 && !StorageManager.isUserKeyUnlocked(userHandle);
813 if (needToShowConfirmCredential) {
814 showConfirmCredentialToDisableQuietMode(userHandle, target);
815 return false;
816 } else {
817 setQuietModeEnabled(userHandle, false /* enableQuietMode */, target);
818 return true;
819 }
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000820 }
Tony Makb7e6fd42017-12-05 19:40:28 +0000821 } finally {
822 Binder.restoreCallingIdentity(identity);
823 }
824 }
825
Tony Make3d1f652017-12-12 11:00:37 +0000826 /**
827 * An app can modify quiet mode if the caller meets one of the condition:
828 * <ul>
829 * <li>Has system UID or root UID</li>
830 * <li>Has {@link Manifest.permission#MODIFY_QUIET_MODE}</li>
831 * <li>Has {@link Manifest.permission#MANAGE_USERS}</li>
832 * </ul>
833 */
834 private boolean isAllowedToSetWorkMode(String callingPackage, int callingUid) {
835 if (hasManageUsersPermission()) {
836 return true;
837 }
838
839 final boolean hasModifyQuietModePermission = ActivityManager.checkComponentPermission(
840 Manifest.permission.MODIFY_QUIET_MODE,
841 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED;
842 if (hasModifyQuietModePermission) {
843 return true;
844 }
845
846 final ShortcutServiceInternal shortcutInternal =
847 LocalServices.getService(ShortcutServiceInternal.class);
848 if (shortcutInternal != null) {
849 boolean isForegroundLauncher =
850 shortcutInternal.isForegroundDefaultLauncher(callingPackage, callingUid);
851 if (isForegroundLauncher) {
852 return true;
853 }
854 }
855 return false;
856 }
857
Tony Makb7e6fd42017-12-05 19:40:28 +0000858 private void setQuietModeEnabled(
859 int userHandle, boolean enableQuietMode, IntentSender target) {
860 final UserInfo profile, parent;
861 final UserData profileUserData;
862 synchronized (mUsersLock) {
863 profile = getUserInfoLU(userHandle);
864 parent = getProfileParentLU(userHandle);
865
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000866 if (profile == null || !profile.isManagedProfile()) {
867 throw new IllegalArgumentException("User " + userHandle + " is not a profile");
868 }
Tony Makb7e6fd42017-12-05 19:40:28 +0000869 if (profile.isQuietModeEnabled() == enableQuietMode) {
870 Slog.i(LOG_TAG, "Quiet mode is already " + enableQuietMode);
871 return;
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000872 }
Tony Makb7e6fd42017-12-05 19:40:28 +0000873 profile.flags ^= UserInfo.FLAG_QUIET_MODE;
874 profileUserData = getUserDataLU(profile.id);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000875 }
Tony Makb7e6fd42017-12-05 19:40:28 +0000876 synchronized (mPackagesLock) {
877 writeUserLP(profileUserData);
878 }
879 try {
880 if (enableQuietMode) {
881 ActivityManager.getService().stopUser(userHandle, /* force */true, null);
882 LocalServices.getService(ActivityManagerInternal.class)
883 .killForegroundAppsForUser(userHandle);
884 } else {
885 IProgressListener callback = target != null
886 ? new DisableQuietModeUserUnlockedCallback(target)
887 : null;
888 ActivityManager.getService().startUserInBackgroundWithListener(
889 userHandle, callback);
Rubin Xuf13c9802016-01-21 18:06:00 +0000890 }
Tony Makb7e6fd42017-12-05 19:40:28 +0000891 } catch (RemoteException e) {
892 // Should not happen, same process.
893 e.rethrowAsRuntimeException();
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000894 }
Tony Makb7e6fd42017-12-05 19:40:28 +0000895 broadcastProfileAvailabilityChanges(profile.getUserHandle(), parent.getUserHandle(),
896 enableQuietMode);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000897 }
898
899 @Override
900 public boolean isQuietModeEnabled(int userHandle) {
901 synchronized (mPackagesLock) {
902 UserInfo info;
903 synchronized (mUsersLock) {
904 info = getUserInfoLU(userHandle);
905 }
906 if (info == null || !info.isManagedProfile()) {
Rubin Xuf13c9802016-01-21 18:06:00 +0000907 return false;
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000908 }
909 return info.isQuietModeEnabled();
910 }
911 }
912
Tony Makb7e6fd42017-12-05 19:40:28 +0000913 /**
914 * Show confirm credential screen to unlock user in order to turn off quiet mode.
915 */
916 private void showConfirmCredentialToDisableQuietMode(
Tony Mak64fd8c02017-12-01 19:11:59 +0000917 @UserIdInt int userHandle, @Nullable IntentSender target) {
Tony Makb7e6fd42017-12-05 19:40:28 +0000918 // otherwise, we show a profile challenge to trigger decryption of the user
919 final KeyguardManager km = (KeyguardManager) mContext.getSystemService(
920 Context.KEYGUARD_SERVICE);
921 // We should use userHandle not credentialOwnerUserId here, as even if it is unified
922 // lock, confirm screenlock page will know and show personal challenge, and unlock
923 // work profile when personal challenge is correct
924 final Intent unlockIntent = km.createConfirmDeviceCredentialIntent(null, null,
925 userHandle);
926 if (unlockIntent == null) {
927 return;
Benjamin Franzf02420c2016-04-04 18:52:21 +0100928 }
Tony Makb7e6fd42017-12-05 19:40:28 +0000929 final Intent callBackIntent = new Intent(
930 ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK);
931 if (target != null) {
932 callBackIntent.putExtra(Intent.EXTRA_INTENT, target);
Benjamin Franzf02420c2016-04-04 18:52:21 +0100933 }
Tony Makb7e6fd42017-12-05 19:40:28 +0000934 callBackIntent.putExtra(Intent.EXTRA_USER_ID, userHandle);
935 callBackIntent.setPackage(mContext.getPackageName());
936 callBackIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
937 final PendingIntent pendingIntent = PendingIntent.getBroadcast(
938 mContext,
939 0,
940 callBackIntent,
941 PendingIntent.FLAG_CANCEL_CURRENT |
942 PendingIntent.FLAG_ONE_SHOT |
943 PendingIntent.FLAG_IMMUTABLE);
944 // After unlocking the challenge, it will disable quiet mode and run the original
945 // intentSender
946 unlockIntent.putExtra(Intent.EXTRA_INTENT, pendingIntent.getIntentSender());
947 unlockIntent.setFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
948 mContext.startActivity(unlockIntent);
Benjamin Franzf02420c2016-04-04 18:52:21 +0100949 }
950
951 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100952 public void setUserEnabled(int userId) {
953 checkManageUsersPermission("enable user");
954 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700955 UserInfo info;
956 synchronized (mUsersLock) {
957 info = getUserInfoLU(userId);
958 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100959 if (info != null && !info.isEnabled()) {
960 info.flags ^= UserInfo.FLAG_DISABLED;
Amith Yamasani12747872015-12-07 14:19:49 -0800961 writeUserLP(getUserDataLU(info.id));
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100962 }
963 }
964 }
965
Andrew Scull85a63bc2016-10-24 13:47:47 +0100966 /**
967 * Evicts a user's CE key by stopping and restarting the user.
968 *
969 * The key is evicted automatically by the user controller when the user has stopped.
970 */
971 @Override
972 public void evictCredentialEncryptionKey(@UserIdInt int userId) {
973 checkManageUsersPermission("evict CE key");
974 final IActivityManager am = ActivityManagerNative.getDefault();
975 final long identity = Binder.clearCallingIdentity();
976 try {
977 am.restartUserInBackground(userId);
978 } catch (RemoteException re) {
979 throw re.rethrowAsRuntimeException();
980 } finally {
981 Binder.restoreCallingIdentity(identity);
982 }
983 }
984
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100985 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700986 public UserInfo getUserInfo(int userId) {
Sudheer Shankaaccaa082016-06-14 16:22:57 -0700987 checkManageOrCreateUsersPermission("query user");
Tony Mak8673b282016-03-21 21:10:59 +0000988 synchronized (mUsersLock) {
Amith Yamasani6f48d6e2016-03-23 14:28:25 -0700989 return userWithName(getUserInfoLU(userId));
990 }
991 }
992
993 /**
994 * Returns a UserInfo object with the name filled in, for Owner, or the original
995 * if the name is already set.
996 */
997 private UserInfo userWithName(UserInfo orig) {
998 if (orig != null && orig.name == null && orig.id == UserHandle.USER_SYSTEM) {
999 UserInfo withName = new UserInfo(orig);
1000 withName.name = getOwnerName();
1001 return withName;
1002 } else {
1003 return orig;
Tony Mak8673b282016-03-21 21:10:59 +00001004 }
1005 }
1006
1007 @Override
Kenny Guy02c89902016-11-15 19:36:38 +00001008 public int getManagedProfileBadge(@UserIdInt int userId) {
1009 int callingUserId = UserHandle.getCallingUserId();
1010 if (callingUserId != userId && !hasManageUsersPermission()) {
1011 if (!isSameProfileGroupNoChecks(callingUserId, userId)) {
1012 throw new SecurityException(
1013 "You need MANAGE_USERS permission to: check if specified user a " +
1014 "managed profile outside your profile group");
1015 }
1016 }
1017 synchronized (mUsersLock) {
1018 UserInfo userInfo = getUserInfoLU(userId);
1019 return userInfo != null ? userInfo.profileBadge : 0;
1020 }
1021 }
1022
1023 @Override
Tony Mak8673b282016-03-21 21:10:59 +00001024 public boolean isManagedProfile(int userId) {
Tony Makb531d082016-03-16 14:49:52 +00001025 int callingUserId = UserHandle.getCallingUserId();
1026 if (callingUserId != userId && !hasManageUsersPermission()) {
Fyodor Kupolov0fb772e2016-10-13 16:27:34 -07001027 if (!isSameProfileGroupNoChecks(callingUserId, userId)) {
Fyodor Kupolovc413f702016-10-06 17:11:14 -07001028 throw new SecurityException(
1029 "You need MANAGE_USERS permission to: check if specified user a " +
1030 "managed profile outside your profile group");
Tony Makb531d082016-03-16 14:49:52 +00001031 }
Tony Mak4dc008c2016-03-16 10:46:49 +00001032 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001033 synchronized (mUsersLock) {
Amith Yamasani1c41dc82016-06-28 16:13:15 -07001034 UserInfo userInfo = getUserInfoLU(userId);
Tony Mak8673b282016-03-21 21:10:59 +00001035 return userInfo != null && userInfo.isManagedProfile();
Amith Yamasani13593602012-03-22 16:16:17 -07001036 }
1037 }
1038
Amith Yamasani71e6c692013-03-24 17:39:28 -07001039 @Override
Fyodor Kupolovc413f702016-10-06 17:11:14 -07001040 public boolean isUserUnlockingOrUnlocked(int userId) {
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08001041 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isUserUnlockingOrUnlocked");
Fyodor Kupolovc413f702016-10-06 17:11:14 -07001042 return mLocalService.isUserUnlockingOrUnlocked(userId);
1043 }
1044
1045 @Override
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08001046 public boolean isUserUnlocked(int userId) {
1047 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isUserUnlocked");
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07001048 return mLocalService.isUserUnlocked(userId);
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08001049 }
1050
1051 @Override
1052 public boolean isUserRunning(int userId) {
1053 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isUserRunning");
1054 return mLocalService.isUserRunning(userId);
1055 }
1056
1057 private void checkManageOrInteractPermIfCallerInOtherProfileGroup(int userId, String name) {
1058 int callingUserId = UserHandle.getCallingUserId();
1059 if (callingUserId == userId || isSameProfileGroupNoChecks(callingUserId, userId) ||
1060 hasManageUsersPermission()) {
1061 return;
1062 }
1063 if (ActivityManager.checkComponentPermission(Manifest.permission.INTERACT_ACROSS_USERS,
1064 Binder.getCallingUid(), -1, true) != PackageManager.PERMISSION_GRANTED) {
1065 throw new SecurityException("You need INTERACT_ACROSS_USERS or MANAGE_USERS permission "
1066 + "to: check " + name);
1067 }
1068 }
1069
1070 @Override
Amith Yamasani1c41dc82016-06-28 16:13:15 -07001071 public boolean isDemoUser(int userId) {
1072 int callingUserId = UserHandle.getCallingUserId();
1073 if (callingUserId != userId && !hasManageUsersPermission()) {
1074 throw new SecurityException("You need MANAGE_USERS permission to query if u=" + userId
1075 + " is a demo user");
1076 }
1077 synchronized (mUsersLock) {
1078 UserInfo userInfo = getUserInfoLU(userId);
1079 return userInfo != null && userInfo.isDemo();
1080 }
1081 }
1082
1083 @Override
Amith Yamasani71e6c692013-03-24 17:39:28 -07001084 public boolean isRestricted() {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001085 synchronized (mUsersLock) {
1086 return getUserInfoLU(UserHandle.getCallingUserId()).isRestricted();
Amith Yamasani71e6c692013-03-24 17:39:28 -07001087 }
1088 }
1089
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001090 @Override
1091 public boolean canHaveRestrictedProfile(int userId) {
1092 checkManageUsersPermission("canHaveRestrictedProfile");
Fyodor Kupolov82402752015-10-28 14:54:51 -07001093 synchronized (mUsersLock) {
1094 final UserInfo userInfo = getUserInfoLU(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001095 if (userInfo == null || !userInfo.canHaveProfile()) {
1096 return false;
1097 }
1098 if (!userInfo.isAdmin()) {
1099 return false;
1100 }
Makoto Onukie7927da2015-11-25 10:05:17 -08001101 // restricted profile can be created if there is no DO set and the admin user has no PO;
1102 return !mIsDeviceManaged && !mIsUserManaged.get(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001103 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001104 }
1105
Fyodor Kupolovca177562017-11-09 17:43:01 -08001106 @Override
1107 public boolean hasRestrictedProfiles() {
1108 checkManageUsersPermission("hasRestrictedProfiles");
1109 final int callingUserId = UserHandle.getCallingUserId();
1110 synchronized (mUsersLock) {
1111 final int userSize = mUsers.size();
1112 for (int i = 0; i < userSize; i++) {
1113 UserInfo profile = mUsers.valueAt(i).info;
1114 if (callingUserId != profile.id
1115 && profile.restrictedProfileParentId == callingUserId) {
1116 return true;
1117 }
1118 }
1119 return false;
1120 }
1121 }
1122
Amith Yamasani195263742012-08-21 15:40:12 -07001123 /*
1124 * Should be locked on mUsers before calling this.
1125 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001126 private UserInfo getUserInfoLU(int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -08001127 final UserData userData = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -07001128 // If it is partial and not in the process of being removed, return as unknown user.
Amith Yamasani12747872015-12-07 14:19:49 -08001129 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001130 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
1131 return null;
1132 }
Amith Yamasani12747872015-12-07 14:19:49 -08001133 return userData != null ? userData.info : null;
1134 }
1135
1136 private UserData getUserDataLU(int userId) {
1137 final UserData userData = mUsers.get(userId);
1138 // If it is partial and not in the process of being removed, return as unknown user.
1139 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
1140 return null;
1141 }
1142 return userData;
Amith Yamasani195263742012-08-21 15:40:12 -07001143 }
1144
Fyodor Kupolov82402752015-10-28 14:54:51 -07001145 /**
1146 * Obtains {@link #mUsersLock} and return UserInfo from mUsers.
1147 * <p>No permissions checking or any addition checks are made</p>
1148 */
1149 private UserInfo getUserInfoNoChecks(int userId) {
1150 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001151 final UserData userData = mUsers.get(userId);
1152 return userData != null ? userData.info : null;
1153 }
1154 }
1155
1156 /**
1157 * Obtains {@link #mUsersLock} and return UserData from mUsers.
1158 * <p>No permissions checking or any addition checks are made</p>
1159 */
1160 private UserData getUserDataNoChecks(int userId) {
1161 synchronized (mUsersLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001162 return mUsers.get(userId);
1163 }
1164 }
1165
Amith Yamasani236b2b52015-08-18 14:32:14 -07001166 /** Called by PackageManagerService */
Amith Yamasani13593602012-03-22 16:16:17 -07001167 public boolean exists(int userId) {
Todd Kennedy0eb97382017-10-03 16:57:22 -07001168 return mLocalService.exists(userId);
Amith Yamasani13593602012-03-22 16:16:17 -07001169 }
1170
Amith Yamasani258848d2012-08-10 17:06:33 -07001171 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001172 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001173 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001174 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -07001175 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001176 UserData userData = getUserDataNoChecks(userId);
1177 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001178 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
1179 return;
1180 }
Amith Yamasani12747872015-12-07 14:19:49 -08001181 if (name != null && !name.equals(userData.info.name)) {
1182 userData.info.name = name;
1183 writeUserLP(userData);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001184 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -07001185 }
1186 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001187 if (changed) {
1188 sendUserInfoChangedBroadcast(userId);
1189 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001190 }
1191
Amith Yamasani258848d2012-08-10 17:06:33 -07001192 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001193 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001194 checkManageUsersPermission("update users");
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01001195 if (hasUserRestriction(UserManager.DISALLOW_SET_USER_ICON, userId)) {
1196 Log.w(LOG_TAG, "Cannot set user icon. DISALLOW_SET_USER_ICON is enabled.");
1197 return;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001198 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01001199 mLocalService.setUserIcon(userId, bitmap);
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001200 }
1201
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01001202
1203
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001204 private void sendUserInfoChangedBroadcast(int userId) {
1205 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
1206 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
1207 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -07001208 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001209 }
1210
Amith Yamasani258848d2012-08-10 17:06:33 -07001211 @Override
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001212 public ParcelFileDescriptor getUserIcon(int targetUserId) {
Adrian Roos1bdff912015-02-17 15:51:35 +01001213 String iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001214 synchronized (mPackagesLock) {
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001215 UserInfo targetUserInfo = getUserInfoNoChecks(targetUserId);
1216 if (targetUserInfo == null || targetUserInfo.partial) {
1217 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + targetUserId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001218 return null;
1219 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001220
1221 final int callingUserId = UserHandle.getCallingUserId();
1222 final int callingGroupId = getUserInfoNoChecks(callingUserId).profileGroupId;
1223 final int targetGroupId = targetUserInfo.profileGroupId;
1224 final boolean sameGroup = (callingGroupId != UserInfo.NO_PROFILE_GROUP_ID
1225 && callingGroupId == targetGroupId);
1226 if ((callingUserId != targetUserId) && !sameGroup) {
Nicolas Prevot88cc3462014-05-14 14:51:48 +01001227 checkManageUsersPermission("get the icon of a user who is not related");
1228 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001229
1230 if (targetUserInfo.iconPath == null) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001231 return null;
1232 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001233 iconPath = targetUserInfo.iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001234 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001235
1236 try {
1237 return ParcelFileDescriptor.open(
1238 new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
1239 } catch (FileNotFoundException e) {
1240 Log.e(LOG_TAG, "Couldn't find icon file", e);
1241 }
1242 return null;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001243 }
1244
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001245 public void makeInitialized(int userId) {
1246 checkManageUsersPermission("makeInitialized");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001247 boolean scheduleWriteUser = false;
Amith Yamasani12747872015-12-07 14:19:49 -08001248 UserData userData;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001249 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001250 userData = mUsers.get(userId);
1251 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001252 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001253 return;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001254 }
Amith Yamasani12747872015-12-07 14:19:49 -08001255 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1256 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001257 scheduleWriteUser = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001258 }
1259 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001260 if (scheduleWriteUser) {
Amith Yamasani12747872015-12-07 14:19:49 -08001261 scheduleWriteUser(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001262 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001263 }
1264
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001265 /**
1266 * If default guest restrictions haven't been initialized yet, add the basic
1267 * restrictions.
1268 */
1269 private void initDefaultGuestRestrictions() {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001270 synchronized (mGuestRestrictions) {
1271 if (mGuestRestrictions.isEmpty()) {
Samuel Tand9453b82016-03-14 15:57:02 -07001272 mGuestRestrictions.putBoolean(UserManager.DISALLOW_CONFIG_WIFI, true);
Fyodor Kupolove04462c2015-11-30 15:02:53 -08001273 mGuestRestrictions.putBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, true);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001274 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
1275 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
1276 }
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001277 }
1278 }
1279
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001280 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301281 public Bundle getDefaultGuestRestrictions() {
1282 checkManageUsersPermission("getDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001283 synchronized (mGuestRestrictions) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301284 return new Bundle(mGuestRestrictions);
1285 }
1286 }
1287
1288 @Override
1289 public void setDefaultGuestRestrictions(Bundle restrictions) {
1290 checkManageUsersPermission("setDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001291 synchronized (mGuestRestrictions) {
1292 mGuestRestrictions.clear();
1293 mGuestRestrictions.putAll(restrictions);
1294 }
1295 synchronized (mPackagesLock) {
1296 writeUserListLP();
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301297 }
1298 }
1299
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001300 /**
Pavel Grafov6a40f092016-10-25 15:46:51 +01001301 * See {@link UserManagerInternal#setDevicePolicyUserRestrictions}
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001302 */
Pavel Grafov6a40f092016-10-25 15:46:51 +01001303 private void setDevicePolicyUserRestrictionsInner(int userId, @Nullable Bundle restrictions,
1304 boolean isDeviceOwner, int cameraRestrictionScope) {
1305 final Bundle global = new Bundle();
1306 final Bundle local = new Bundle();
1307
1308 // Sort restrictions into local and global ensuring they don't overlap.
1309 UserRestrictionsUtils.sortToGlobalAndLocal(restrictions, isDeviceOwner,
1310 cameraRestrictionScope, global, local);
1311
1312 boolean globalChanged, localChanged;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001313 synchronized (mRestrictionsLock) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001314 // Update global and local restrictions if they were changed.
1315 globalChanged = updateRestrictionsIfNeededLR(
1316 userId, global, mDevicePolicyGlobalUserRestrictions);
1317 localChanged = updateRestrictionsIfNeededLR(
1318 userId, local, mDevicePolicyLocalUserRestrictions);
1319
1320 if (isDeviceOwner) {
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001321 // Remember the global restriction owner userId to be able to make a distinction
1322 // in getUserRestrictionSource on who set local policies.
Pavel Grafov6a40f092016-10-25 15:46:51 +01001323 mDeviceOwnerUserId = userId;
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001324 } else {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001325 if (mDeviceOwnerUserId == userId) {
Zoltan Szatmary-Ban8a5536d2016-05-27 17:56:44 +01001326 // When profile owner sets restrictions it passes null global bundle and we
1327 // reset global restriction owner userId.
1328 // This means this user used to have DO, but now the DO is gone and the user
1329 // instead has PO.
Pavel Grafov6a40f092016-10-25 15:46:51 +01001330 mDeviceOwnerUserId = UserHandle.USER_NULL;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001331 }
1332 }
1333 }
1334 if (DBG) {
1335 Log.d(LOG_TAG, "setDevicePolicyUserRestrictions: userId=" + userId
1336 + " global=" + global + (globalChanged ? " (changed)" : "")
1337 + " local=" + local + (localChanged ? " (changed)" : "")
1338 );
1339 }
1340 // Don't call them within the mRestrictionsLock.
1341 synchronized (mPackagesLock) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001342 if (localChanged || globalChanged) {
Amith Yamasani12747872015-12-07 14:19:49 -08001343 writeUserLP(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001344 }
1345 }
1346
1347 synchronized (mRestrictionsLock) {
1348 if (globalChanged) {
1349 applyUserRestrictionsForAllUsersLR();
1350 } else if (localChanged) {
1351 applyUserRestrictionsLR(userId);
1352 }
1353 }
1354 }
1355
Pavel Grafov6a40f092016-10-25 15:46:51 +01001356 /**
1357 * Updates restriction bundle for a given user in a given restriction array. If new bundle is
1358 * empty, record is removed from the array.
1359 * @return whether restrictions bundle is different from the old one.
1360 */
1361 private boolean updateRestrictionsIfNeededLR(int userId, @Nullable Bundle restrictions,
1362 SparseArray<Bundle> restrictionsArray) {
1363 final boolean changed =
1364 !UserRestrictionsUtils.areEqual(restrictionsArray.get(userId), restrictions);
1365 if (changed) {
1366 if (!UserRestrictionsUtils.isEmpty(restrictions)) {
1367 restrictionsArray.put(userId, restrictions);
1368 } else {
1369 restrictionsArray.delete(userId);
1370 }
1371 }
1372 return changed;
1373 }
1374
Makoto Onuki068c54a2015-10-13 14:34:03 -07001375 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001376 private Bundle computeEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001377 final Bundle baseRestrictions =
1378 UserRestrictionsUtils.nonNull(mBaseUserRestrictions.get(userId));
Pavel Grafov6a40f092016-10-25 15:46:51 +01001379 final Bundle global = UserRestrictionsUtils.mergeAll(mDevicePolicyGlobalUserRestrictions);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001380 final Bundle local = mDevicePolicyLocalUserRestrictions.get(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001381
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001382 if (UserRestrictionsUtils.isEmpty(global) && UserRestrictionsUtils.isEmpty(local)) {
1383 // Common case first.
1384 return baseRestrictions;
Makoto Onuki068c54a2015-10-13 14:34:03 -07001385 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001386 final Bundle effective = UserRestrictionsUtils.clone(baseRestrictions);
1387 UserRestrictionsUtils.merge(effective, global);
1388 UserRestrictionsUtils.merge(effective, local);
1389
Makoto Onuki068c54a2015-10-13 14:34:03 -07001390 return effective;
1391 }
1392
1393 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001394 private void invalidateEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki068c54a2015-10-13 14:34:03 -07001395 if (DBG) {
1396 Log.d(LOG_TAG, "invalidateEffectiveUserRestrictions userId=" + userId);
1397 }
1398 mCachedEffectiveUserRestrictions.remove(userId);
1399 }
1400
1401 private Bundle getEffectiveUserRestrictions(int userId) {
1402 synchronized (mRestrictionsLock) {
1403 Bundle restrictions = mCachedEffectiveUserRestrictions.get(userId);
1404 if (restrictions == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001405 restrictions = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001406 mCachedEffectiveUserRestrictions.put(userId, restrictions);
1407 }
1408 return restrictions;
Amith Yamasani8cd28b52014-06-08 17:54:27 -07001409 }
1410 }
1411
Makoto Onuki068c54a2015-10-13 14:34:03 -07001412 /** @return a specific user restriction that's in effect currently. */
1413 @Override
1414 public boolean hasUserRestriction(String restrictionKey, int userId) {
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001415 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1416 return false;
1417 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001418 Bundle restrictions = getEffectiveUserRestrictions(userId);
1419 return restrictions != null && restrictions.getBoolean(restrictionKey);
1420 }
1421
1422 /**
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001423 * @hide
1424 *
1425 * Returns who set a user restriction on a user.
1426 * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
1427 * @param restrictionKey the string key representing the restriction
1428 * @param userId the id of the user for whom to retrieve the restrictions.
1429 * @return The source of user restriction. Any combination of
1430 * {@link UserManager#RESTRICTION_NOT_SET},
1431 * {@link UserManager#RESTRICTION_SOURCE_SYSTEM},
1432 * {@link UserManager#RESTRICTION_SOURCE_DEVICE_OWNER}
1433 * and {@link UserManager#RESTRICTION_SOURCE_PROFILE_OWNER}
1434 */
1435 @Override
1436 public int getUserRestrictionSource(String restrictionKey, int userId) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001437 List<EnforcingUser> enforcingUsers = getUserRestrictionSources(restrictionKey, userId);
1438 // Get "bitwise or" of restriction sources for all enforcing users.
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001439 int result = UserManager.RESTRICTION_NOT_SET;
Pavel Grafov6a40f092016-10-25 15:46:51 +01001440 for (int i = enforcingUsers.size() - 1; i >= 0; i--) {
1441 result |= enforcingUsers.get(i).getUserRestrictionSource();
1442 }
1443 return result;
1444 }
1445
1446 @Override
1447 public List<EnforcingUser> getUserRestrictionSources(
1448 String restrictionKey, @UserIdInt int userId) {
1449 checkManageUsersPermission("getUserRestrictionSource");
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001450
1451 // Shortcut for the most common case
1452 if (!hasUserRestriction(restrictionKey, userId)) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001453 return Collections.emptyList();
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001454 }
1455
Pavel Grafov6a40f092016-10-25 15:46:51 +01001456 final List<EnforcingUser> result = new ArrayList<>();
1457
1458 // Check if it is base restriction.
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001459 if (hasBaseUserRestriction(restrictionKey, userId)) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001460 result.add(new EnforcingUser(
1461 UserHandle.USER_NULL, UserManager.RESTRICTION_SOURCE_SYSTEM));
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001462 }
1463
Pavel Grafov6a40f092016-10-25 15:46:51 +01001464 synchronized (mRestrictionsLock) {
1465 // Check if it is set by profile owner.
1466 Bundle profileOwnerRestrictions = mDevicePolicyLocalUserRestrictions.get(userId);
1467 if (UserRestrictionsUtils.contains(profileOwnerRestrictions, restrictionKey)) {
1468 result.add(getEnforcingUserLocked(userId));
1469 }
1470
1471 // Iterate over all users who enforce global restrictions.
1472 for (int i = mDevicePolicyGlobalUserRestrictions.size() - 1; i >= 0; i--) {
1473 Bundle globalRestrictions = mDevicePolicyGlobalUserRestrictions.valueAt(i);
1474 int profileUserId = mDevicePolicyGlobalUserRestrictions.keyAt(i);
1475 if (UserRestrictionsUtils.contains(globalRestrictions, restrictionKey)) {
1476 result.add(getEnforcingUserLocked(profileUserId));
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001477 }
1478 }
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001479 }
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001480 return result;
1481 }
1482
Pavel Grafov6a40f092016-10-25 15:46:51 +01001483 private EnforcingUser getEnforcingUserLocked(@UserIdInt int userId) {
1484 int source = mDeviceOwnerUserId == userId ? UserManager.RESTRICTION_SOURCE_DEVICE_OWNER
1485 : UserManager.RESTRICTION_SOURCE_PROFILE_OWNER;
1486 return new EnforcingUser(userId, source);
1487 }
1488
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001489 /**
Makoto Onuki068c54a2015-10-13 14:34:03 -07001490 * @return UserRestrictions that are in effect currently. This always returns a new
1491 * {@link Bundle}.
1492 */
Amith Yamasani8cd28b52014-06-08 17:54:27 -07001493 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001494 public Bundle getUserRestrictions(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001495 return UserRestrictionsUtils.clone(getEffectiveUserRestrictions(userId));
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001496 }
1497
1498 @Override
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +00001499 public boolean hasBaseUserRestriction(String restrictionKey, int userId) {
1500 checkManageUsersPermission("hasBaseUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001501 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1502 return false;
1503 }
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +00001504 synchronized (mRestrictionsLock) {
1505 Bundle bundle = mBaseUserRestrictions.get(userId);
1506 return (bundle != null && bundle.getBoolean(restrictionKey, false));
1507 }
1508 }
1509
1510 @Override
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001511 public void setUserRestriction(String key, boolean value, int userId) {
Fyodor Kupolovd4b26042015-07-27 14:30:59 -07001512 checkManageUsersPermission("setUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001513 if (!UserRestrictionsUtils.isValidRestriction(key)) {
1514 return;
1515 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001516 synchronized (mRestrictionsLock) {
1517 // Note we can't modify Bundles stored in mBaseUserRestrictions directly, so create
1518 // a copy.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001519 final Bundle newRestrictions = UserRestrictionsUtils.clone(
1520 mBaseUserRestrictions.get(userId));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001521 newRestrictions.putBoolean(key, value);
1522
Fyodor Kupolov82402752015-10-28 14:54:51 -07001523 updateUserRestrictionsInternalLR(newRestrictions, userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001524 }
1525 }
1526
Makoto Onuki068c54a2015-10-13 14:34:03 -07001527 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001528 * Optionally updating user restrictions, calculate the effective user restrictions and also
1529 * propagate to other services and system settings.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001530 *
Pavel Grafov6a40f092016-10-25 15:46:51 +01001531 * @param newBaseRestrictions User restrictions to set.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001532 * If null, will not update user restrictions and only does the propagation.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001533 * @param userId target user ID.
1534 */
1535 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001536 private void updateUserRestrictionsInternalLR(
Pavel Grafov6a40f092016-10-25 15:46:51 +01001537 @Nullable Bundle newBaseRestrictions, int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001538 final Bundle prevAppliedRestrictions = UserRestrictionsUtils.nonNull(
1539 mAppliedUserRestrictions.get(userId));
1540
1541 // Update base restrictions.
Pavel Grafov6a40f092016-10-25 15:46:51 +01001542 if (newBaseRestrictions != null) {
1543 // If newBaseRestrictions == the current one, it's probably a bug.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001544 final Bundle prevBaseRestrictions = mBaseUserRestrictions.get(userId);
1545
Pavel Grafov6a40f092016-10-25 15:46:51 +01001546 Preconditions.checkState(prevBaseRestrictions != newBaseRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001547 Preconditions.checkState(mCachedEffectiveUserRestrictions.get(userId)
Pavel Grafov6a40f092016-10-25 15:46:51 +01001548 != newBaseRestrictions);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001549
Pavel Grafov6a40f092016-10-25 15:46:51 +01001550 if (updateRestrictionsIfNeededLR(userId, newBaseRestrictions, mBaseUserRestrictions)) {
Amith Yamasani12747872015-12-07 14:19:49 -08001551 scheduleWriteUser(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001552 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001553 }
1554
Fyodor Kupolov82402752015-10-28 14:54:51 -07001555 final Bundle effective = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001556
Makoto Onuki759a7632015-10-28 16:43:10 -07001557 mCachedEffectiveUserRestrictions.put(userId, effective);
1558
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001559 // Apply the new restrictions.
Makoto Onuki4f160732015-10-27 17:15:38 -07001560 if (DBG) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001561 debug("Applying user restrictions: userId=" + userId
1562 + " new=" + effective + " prev=" + prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001563 }
1564
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001565 if (mAppOpsService != null) { // We skip it until system-ready.
Fyodor Kupolovec30ca32016-06-16 15:09:29 -07001566 mHandler.post(new Runnable() {
1567 @Override
1568 public void run() {
1569 try {
1570 mAppOpsService.setUserRestrictions(effective, mUserRestriconToken, userId);
1571 } catch (RemoteException e) {
1572 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
1573 }
1574 }
1575 });
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001576 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001577
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001578 propagateUserRestrictionsLR(userId, effective, prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001579
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001580 mAppliedUserRestrictions.put(userId, new Bundle(effective));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001581 }
1582
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001583 private void propagateUserRestrictionsLR(final int userId,
Makoto Onukid45a4a22015-11-02 17:17:38 -08001584 Bundle newRestrictions, Bundle prevRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001585 // Note this method doesn't touch any state, meaning it doesn't require mRestrictionsLock
1586 // actually, but we still need some kind of synchronization otherwise we might end up
1587 // calling listeners out-of-order, thus "LR".
1588
1589 if (UserRestrictionsUtils.areEqual(newRestrictions, prevRestrictions)) {
1590 return;
1591 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08001592
1593 final Bundle newRestrictionsFinal = new Bundle(newRestrictions);
1594 final Bundle prevRestrictionsFinal = new Bundle(prevRestrictions);
1595
1596 mHandler.post(new Runnable() {
1597 @Override
1598 public void run() {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07001599 UserRestrictionsUtils.applyUserRestrictions(
1600 mContext, userId, newRestrictionsFinal, prevRestrictionsFinal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001601
Makoto Onukid45a4a22015-11-02 17:17:38 -08001602 final UserRestrictionsListener[] listeners;
1603 synchronized (mUserRestrictionsListeners) {
1604 listeners = new UserRestrictionsListener[mUserRestrictionsListeners.size()];
1605 mUserRestrictionsListeners.toArray(listeners);
1606 }
1607 for (int i = 0; i < listeners.length; i++) {
1608 listeners[i].onUserRestrictionsChanged(userId,
1609 newRestrictionsFinal, prevRestrictionsFinal);
1610 }
Makoto Onukie72f81b2017-03-16 14:08:19 -07001611
1612 final Intent broadcast = new Intent(UserManager.ACTION_USER_RESTRICTIONS_CHANGED)
1613 .setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
1614 mContext.sendBroadcastAsUser(broadcast, UserHandle.of(userId));
Makoto Onukid45a4a22015-11-02 17:17:38 -08001615 }
1616 });
1617 }
1618
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001619 // Package private for the inner class.
1620 void applyUserRestrictionsLR(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001621 updateUserRestrictionsInternalLR(null, userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001622 }
1623
1624 @GuardedBy("mRestrictionsLock")
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001625 // Package private for the inner class.
1626 void applyUserRestrictionsForAllUsersLR() {
1627 if (DBG) {
1628 debug("applyUserRestrictionsForAllUsersLR");
1629 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001630 // First, invalidate all cached values.
Makoto Onuki4f160732015-10-27 17:15:38 -07001631 mCachedEffectiveUserRestrictions.clear();
1632
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001633 // We don't want to call into ActivityManagerService while taking a lock, so we'll call
Makoto Onuki068c54a2015-10-13 14:34:03 -07001634 // it on a handler.
1635 final Runnable r = new Runnable() {
1636 @Override
1637 public void run() {
1638 // Then get the list of running users.
1639 final int[] runningUsers;
1640 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001641 runningUsers = ActivityManager.getService().getRunningUserIds();
Makoto Onuki068c54a2015-10-13 14:34:03 -07001642 } catch (RemoteException e) {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001643 Log.w(LOG_TAG, "Unable to access ActivityManagerService");
Makoto Onuki068c54a2015-10-13 14:34:03 -07001644 return;
1645 }
1646 // Then re-calculate the effective restrictions and apply, only for running users.
1647 // It's okay if a new user has started after the getRunningUserIds() call,
1648 // because we'll do the same thing (re-calculate the restrictions and apply)
1649 // when we start a user.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001650 synchronized (mRestrictionsLock) {
1651 for (int i = 0; i < runningUsers.length; i++) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001652 applyUserRestrictionsLR(runningUsers[i]);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001653 }
1654 }
1655 }
1656 };
1657 mHandler.post(r);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001658 }
1659
Amith Yamasani258848d2012-08-10 17:06:33 -07001660 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001661 * Check if we've hit the limit of how many users can be created.
1662 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001663 private boolean isUserLimitReached() {
1664 int count;
1665 synchronized (mUsersLock) {
1666 count = getAliveUsersExcludingGuestsCountLU();
1667 }
1668 return count >= UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001669 }
1670
1671 @Override
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001672 public boolean canAddMoreManagedProfiles(int userId, boolean allowedToRemoveOne) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001673 checkManageUsersPermission("check if more managed profiles can be added.");
1674 if (ActivityManager.isLowRamDeviceStatic()) {
1675 return false;
1676 }
Fyodor Kupolovb6157992015-06-05 15:32:28 -07001677 if (!mContext.getPackageManager().hasSystemFeature(
1678 PackageManager.FEATURE_MANAGED_USERS)) {
1679 return false;
1680 }
Nicolas Prevotb8186812015-08-06 15:00:03 +01001681 // Limit number of managed profiles that can be created
Benjamin Franzc8776152017-01-06 14:16:41 +00001682 final int managedProfilesCount = getProfiles(userId, false).size() - 1;
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001683 final int profilesRemovedCount = managedProfilesCount > 0 && allowedToRemoveOne ? 1 : 0;
Kenny Guy02c89902016-11-15 19:36:38 +00001684 if (managedProfilesCount - profilesRemovedCount >= getMaxManagedProfiles()) {
Nicolas Prevotb8186812015-08-06 15:00:03 +01001685 return false;
1686 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001687 synchronized(mUsersLock) {
1688 UserInfo userInfo = getUserInfoLU(userId);
yuanhao47f9f7c2017-01-18 09:54:45 +08001689 if (userInfo == null || !userInfo.canHaveProfile()) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001690 return false;
1691 }
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001692 int usersCountAfterRemoving = getAliveUsersExcludingGuestsCountLU()
1693 - profilesRemovedCount;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001694 // We allow creating a managed profile in the special case where there is only one user.
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001695 return usersCountAfterRemoving == 1
1696 || usersCountAfterRemoving < UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001697 }
1698 }
1699
Fyodor Kupolov82402752015-10-28 14:54:51 -07001700 private int getAliveUsersExcludingGuestsCountLU() {
Amith Yamasanif584f012014-05-19 17:57:25 -07001701 int aliveUserCount = 0;
1702 final int totalUserCount = mUsers.size();
1703 // Skip over users being removed
1704 for (int i = 0; i < totalUserCount; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001705 UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov6e99d3f2016-11-01 17:18:41 -07001706 if (!mRemovingUserIds.get(user.id) && !user.isGuest()) {
Amith Yamasanif584f012014-05-19 17:57:25 -07001707 aliveUserCount++;
1708 }
1709 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001710 return aliveUserCount;
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001711 }
1712
1713 /**
Amith Yamasani195263742012-08-21 15:40:12 -07001714 * Enforces that only the system UID or root's UID or apps that have the
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001715 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} and
1716 * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL INTERACT_ACROSS_USERS_FULL}
1717 * permissions can make certain calls to the UserManager.
1718 *
1719 * @param message used as message if SecurityException is thrown
1720 * @throws SecurityException if the caller does not have enough privilege.
1721 */
1722 private static final void checkManageUserAndAcrossUsersFullPermission(String message) {
1723 final int uid = Binder.getCallingUid();
1724 if (uid != Process.SYSTEM_UID && uid != 0
1725 && ActivityManager.checkComponentPermission(
1726 Manifest.permission.MANAGE_USERS,
1727 uid, -1, true) != PackageManager.PERMISSION_GRANTED
1728 && ActivityManager.checkComponentPermission(
1729 Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1730 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
1731 throw new SecurityException(
1732 "You need MANAGE_USERS and INTERACT_ACROSS_USERS_FULL permission to: "
1733 + message);
1734 }
1735 }
1736
1737 /**
1738 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001739 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -07001740 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -07001741 *
1742 * @param message used as message if SecurityException is thrown
1743 * @throws SecurityException if the caller is not system or root
Tony Mak4dc008c2016-03-16 10:46:49 +00001744 * @see #hasManageUsersPermission()
Amith Yamasani258848d2012-08-10 17:06:33 -07001745 */
Amith Yamasanibe465322014-04-24 13:45:17 -07001746 private static final void checkManageUsersPermission(String message) {
Tony Mak4dc008c2016-03-16 10:46:49 +00001747 if (!hasManageUsersPermission()) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001748 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
1749 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -04001750 }
1751
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001752 /**
Sudheer Shankaf5cea032016-06-08 17:13:24 -07001753 * Enforces that only the system UID or root's UID or apps that have the
1754 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or
1755 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS}
1756 * can make certain calls to the UserManager.
1757 *
1758 * @param message used as message if SecurityException is thrown
1759 * @throws SecurityException if the caller is not system or root
1760 * @see #hasManageOrCreateUsersPermission()
1761 */
1762 private static final void checkManageOrCreateUsersPermission(String message) {
1763 if (!hasManageOrCreateUsersPermission()) {
1764 throw new SecurityException(
1765 "You either need MANAGE_USERS or CREATE_USERS permission to: " + message);
1766 }
1767 }
1768
1769 /**
1770 * Similar to {@link #checkManageOrCreateUsersPermission(String)} but when the caller is tries
1771 * to create user/profiles other than what is allowed for
1772 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS} permission, then it will only
1773 * allow callers with {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} permission.
1774 */
1775 private static final void checkManageOrCreateUsersPermission(int creationFlags) {
1776 if ((creationFlags & ~ALLOWED_FLAGS_FOR_CREATE_USERS_PERMISSION) == 0) {
1777 if (!hasManageOrCreateUsersPermission()) {
1778 throw new SecurityException("You either need MANAGE_USERS or CREATE_USERS "
1779 + "permission to create an user with flags: " + creationFlags);
1780 }
1781 } else if (!hasManageUsersPermission()) {
1782 throw new SecurityException("You need MANAGE_USERS permission to create an user "
1783 + " with flags: " + creationFlags);
1784 }
1785 }
1786
1787 /**
Tony Mak4dc008c2016-03-16 10:46:49 +00001788 * @return whether the calling UID is system UID or root's UID or the calling app has the
1789 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}.
1790 */
1791 private static final boolean hasManageUsersPermission() {
1792 final int callingUid = Binder.getCallingUid();
1793 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
1794 || callingUid == Process.ROOT_UID
1795 || ActivityManager.checkComponentPermission(
1796 android.Manifest.permission.MANAGE_USERS,
1797 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED;
1798 }
1799
1800 /**
Sudheer Shankaf5cea032016-06-08 17:13:24 -07001801 * @return whether the calling UID is system UID or root's UID or the calling app has the
1802 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or
1803 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS}.
1804 */
1805 private static final boolean hasManageOrCreateUsersPermission() {
1806 final int callingUid = Binder.getCallingUid();
1807 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
1808 || callingUid == Process.ROOT_UID
1809 || ActivityManager.checkComponentPermission(
1810 android.Manifest.permission.MANAGE_USERS,
1811 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED
1812 || ActivityManager.checkComponentPermission(
1813 android.Manifest.permission.CREATE_USERS,
1814 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED;
1815 }
1816
1817 /**
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001818 * Enforces that only the system UID or root's UID (on any user) can make certain calls to the
1819 * UserManager.
1820 *
1821 * @param message used as message if SecurityException is thrown
1822 * @throws SecurityException if the caller is not system or root
1823 */
1824 private static void checkSystemOrRoot(String message) {
1825 final int uid = Binder.getCallingUid();
1826 if (!UserHandle.isSameApp(uid, Process.SYSTEM_UID) && uid != Process.ROOT_UID) {
1827 throw new SecurityException("Only system may: " + message);
1828 }
1829 }
1830
Fyodor Kupolov82402752015-10-28 14:54:51 -07001831 private void writeBitmapLP(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001832 try {
1833 File dir = new File(mUsersDir, Integer.toString(info.id));
1834 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +01001835 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001836 if (!dir.exists()) {
1837 dir.mkdir();
1838 FileUtils.setPermissions(
1839 dir.getPath(),
1840 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
1841 -1, -1);
1842 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001843 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +01001844 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001845 && tmp.renameTo(file) && SELinux.restorecon(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -07001846 info.iconPath = file.getAbsolutePath();
1847 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001848 try {
1849 os.close();
1850 } catch (IOException ioe) {
1851 // What the ... !
1852 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001853 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001854 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001855 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001856 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001857 }
1858
Amith Yamasani0b285492011-04-14 17:35:23 -07001859 /**
1860 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
1861 * cache it elsewhere.
1862 * @return the array of user ids.
1863 */
Dianne Hackborn1676c852012-09-10 14:52:30 -07001864 public int[] getUserIds() {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001865 synchronized (mUsersLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001866 return mUserIds;
1867 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001868 }
1869
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001870 private void readUserListLP() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001871 if (!mUserListFile.exists()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001872 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001873 return;
1874 }
1875 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001876 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001877 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001878 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001879 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001880 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001881 int type;
1882 while ((type = parser.next()) != XmlPullParser.START_TAG
1883 && type != XmlPullParser.END_DOCUMENT) {
Amith Yamasani12747872015-12-07 14:19:49 -08001884 // Skip
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001885 }
1886
1887 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001888 Slog.e(LOG_TAG, "Unable to read user list");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001889 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001890 return;
1891 }
1892
Amith Yamasani2a003292012-08-14 18:25:45 -07001893 mNextSerialNumber = -1;
1894 if (parser.getName().equals(TAG_USERS)) {
1895 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
1896 if (lastSerialNumber != null) {
1897 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
1898 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001899 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
1900 if (versionNumber != null) {
1901 mUserVersion = Integer.parseInt(versionNumber);
1902 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001903 }
1904
Pavel Grafov6a40f092016-10-25 15:46:51 +01001905 // Pre-O global user restriction were stored as a single bundle (as opposed to per-user
1906 // currently), take care of it in case of upgrade.
1907 Bundle oldDevicePolicyGlobalUserRestrictions = null;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001908
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001909 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301910 if (type == XmlPullParser.START_TAG) {
1911 final String name = parser.getName();
1912 if (name.equals(TAG_USER)) {
1913 String id = parser.getAttributeValue(null, ATTR_ID);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001914
Amith Yamasani12747872015-12-07 14:19:49 -08001915 UserData userData = readUserLP(Integer.parseInt(id));
1916
1917 if (userData != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001918 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001919 mUsers.put(userData.info.id, userData);
1920 if (mNextSerialNumber < 0
1921 || mNextSerialNumber <= userData.info.id) {
1922 mNextSerialNumber = userData.info.id + 1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001923 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301924 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001925 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301926 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -08001927 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1928 && type != XmlPullParser.END_TAG) {
1929 if (type == XmlPullParser.START_TAG) {
1930 if (parser.getName().equals(TAG_RESTRICTIONS)) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001931 synchronized (mGuestRestrictions) {
Fyodor Kupoloveafee022017-03-15 17:09:04 -07001932 UserRestrictionsUtils
1933 .readRestrictions(parser, mGuestRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001934 }
Amith Yamasanida0b1682014-11-21 12:58:17 -08001935 }
1936 break;
1937 }
1938 }
Pavel Grafov6a40f092016-10-25 15:46:51 +01001939 } else if (name.equals(TAG_DEVICE_OWNER_USER_ID)
1940 // Legacy name, should only be encountered when upgrading from pre-O.
1941 || name.equals(TAG_GLOBAL_RESTRICTION_OWNER_ID)) {
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001942 String ownerUserId = parser.getAttributeValue(null, ATTR_ID);
1943 if (ownerUserId != null) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001944 mDeviceOwnerUserId = Integer.parseInt(ownerUserId);
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001945 }
Pavel Grafov6a40f092016-10-25 15:46:51 +01001946 } else if (name.equals(TAG_DEVICE_POLICY_RESTRICTIONS)) {
1947 // Should only happen when upgrading from pre-O (version < 7).
1948 oldDevicePolicyGlobalUserRestrictions =
1949 UserRestrictionsUtils.readRestrictions(parser);
Amith Yamasani258848d2012-08-10 17:06:33 -07001950 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001951 }
1952 }
Pavel Grafov6a40f092016-10-25 15:46:51 +01001953
Fyodor Kupolov82402752015-10-28 14:54:51 -07001954 updateUserIds();
Pavel Grafov6a40f092016-10-25 15:46:51 +01001955 upgradeIfNecessaryLP(oldDevicePolicyGlobalUserRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001956 } catch (IOException | XmlPullParserException e) {
1957 fallbackToSingleUserLP();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001958 } finally {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001959 IoUtils.closeQuietly(fis);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001960 }
1961 }
1962
Amith Yamasani6f34b412012-10-22 18:19:27 -07001963 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -08001964 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Pavel Grafov6a40f092016-10-25 15:46:51 +01001965 * @param oldGlobalUserRestrictions Pre-O global device policy restrictions.
Amith Yamasani6f34b412012-10-22 18:19:27 -07001966 */
Pavel Grafov6a40f092016-10-25 15:46:51 +01001967 private void upgradeIfNecessaryLP(Bundle oldGlobalUserRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001968 final int originalVersion = mUserVersion;
Amith Yamasani6f34b412012-10-22 18:19:27 -07001969 int userVersion = mUserVersion;
1970 if (userVersion < 1) {
1971 // Assign a proper name for the owner, if not initialized correctly before
Amith Yamasani12747872015-12-07 14:19:49 -08001972 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
1973 if ("Primary".equals(userData.info.name)) {
1974 userData.info.name =
1975 mContext.getResources().getString(com.android.internal.R.string.owner_name);
1976 scheduleWriteUser(userData);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001977 }
1978 userVersion = 1;
1979 }
1980
Amith Yamasanibc9625052012-11-15 14:39:18 -08001981 if (userVersion < 2) {
1982 // Owner should be marked as initialized
Amith Yamasani12747872015-12-07 14:19:49 -08001983 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
1984 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1985 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
1986 scheduleWriteUser(userData);
Amith Yamasanibc9625052012-11-15 14:39:18 -08001987 }
1988 userVersion = 2;
1989 }
1990
Amith Yamasani350962c2013-08-06 11:18:53 -07001991
Amith Yamasani5e486f52013-08-07 11:06:44 -07001992 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -07001993 userVersion = 4;
1994 }
1995
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001996 if (userVersion < 5) {
1997 initDefaultGuestRestrictions();
1998 userVersion = 5;
1999 }
2000
Fyodor Kupolov1c363152015-09-02 13:27:21 -07002001 if (userVersion < 6) {
2002 final boolean splitSystemUser = UserManager.isSplitSystemUser();
Fyodor Kupolov82402752015-10-28 14:54:51 -07002003 synchronized (mUsersLock) {
2004 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002005 UserData userData = mUsers.valueAt(i);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002006 // In non-split mode, only user 0 can have restricted profiles
Amith Yamasani12747872015-12-07 14:19:49 -08002007 if (!splitSystemUser && userData.info.isRestricted()
2008 && (userData.info.restrictedProfileParentId
2009 == UserInfo.NO_PROFILE_GROUP_ID)) {
2010 userData.info.restrictedProfileParentId = UserHandle.USER_SYSTEM;
2011 scheduleWriteUser(userData);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002012 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07002013 }
2014 }
2015 userVersion = 6;
2016 }
2017
Pavel Grafov6a40f092016-10-25 15:46:51 +01002018 if (userVersion < 7) {
2019 // Previously only one user could enforce global restrictions, now it is per-user.
2020 synchronized (mRestrictionsLock) {
2021 if (!UserRestrictionsUtils.isEmpty(oldGlobalUserRestrictions)
2022 && mDeviceOwnerUserId != UserHandle.USER_NULL) {
2023 mDevicePolicyGlobalUserRestrictions.put(
2024 mDeviceOwnerUserId, oldGlobalUserRestrictions);
2025 }
2026 // ENSURE_VERIFY_APPS is now enforced globally even if put by profile owner, so move
2027 // it from local to global bundle for all users who set it.
2028 UserRestrictionsUtils.moveRestriction(UserManager.ENSURE_VERIFY_APPS,
2029 mDevicePolicyLocalUserRestrictions, mDevicePolicyGlobalUserRestrictions
2030 );
2031 }
2032 userVersion = 7;
2033 }
2034
Amith Yamasani6f34b412012-10-22 18:19:27 -07002035 if (userVersion < USER_VERSION) {
2036 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
2037 + USER_VERSION);
2038 } else {
2039 mUserVersion = userVersion;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002040
2041 if (originalVersion < mUserVersion) {
2042 writeUserListLP();
2043 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07002044 }
2045 }
2046
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002047 private void fallbackToSingleUserLP() {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07002048 int flags = UserInfo.FLAG_INITIALIZED;
2049 // In split system user mode, the admin and primary flags are assigned to the first human
2050 // user.
2051 if (!UserManager.isSplitSystemUser()) {
2052 flags |= UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY;
2053 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -07002054 // Create the system user
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07002055 UserInfo system = new UserInfo(UserHandle.USER_SYSTEM, null, null, flags);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002056 UserData userData = putUserInfo(system);
Amith Yamasani634cf312012-10-04 17:34:21 -07002057 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -04002058 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -08002059
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05002060 Bundle restrictions = new Bundle();
Mahaver Chopra3d9805d2016-07-07 16:25:05 +01002061 try {
2062 final String[] defaultFirstUserRestrictions = mContext.getResources().getStringArray(
2063 com.android.internal.R.array.config_defaultFirstUserRestrictions);
2064 for (String userRestriction : defaultFirstUserRestrictions) {
2065 if (UserRestrictionsUtils.isValidRestriction(userRestriction)) {
2066 restrictions.putBoolean(userRestriction, true);
2067 }
2068 }
2069 } catch (Resources.NotFoundException e) {
2070 Log.e(LOG_TAG, "Couldn't find resource: config_defaultFirstUserRestrictions", e);
2071 }
2072
Pavel Grafov6a40f092016-10-25 15:46:51 +01002073 if (!restrictions.isEmpty()) {
2074 synchronized (mRestrictionsLock) {
2075 mBaseUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions);
2076 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07002077 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08002078
Fyodor Kupolov82402752015-10-28 14:54:51 -07002079 updateUserIds();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07002080 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002081
Amith Yamasani12747872015-12-07 14:19:49 -08002082 writeUserLP(userData);
Jeff Sharkeycd575992016-03-29 14:12:49 -06002083 writeUserListLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002084 }
2085
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07002086 private String getOwnerName() {
2087 return mContext.getResources().getString(com.android.internal.R.string.owner_name);
2088 }
2089
Amith Yamasani12747872015-12-07 14:19:49 -08002090 private void scheduleWriteUser(UserData UserData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002091 if (DBG) {
2092 debug("scheduleWriteUser");
2093 }
Makoto Onuki9e935a32015-11-06 14:24:24 -08002094 // No need to wrap it within a lock -- worst case, we'll just post the same message
2095 // twice.
Amith Yamasani12747872015-12-07 14:19:49 -08002096 if (!mHandler.hasMessages(WRITE_USER_MSG, UserData)) {
2097 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, UserData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002098 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
2099 }
2100 }
2101
Amith Yamasani12747872015-12-07 14:19:49 -08002102 private void writeUserLP(UserData userData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002103 if (DBG) {
Amith Yamasani12747872015-12-07 14:19:49 -08002104 debug("writeUserLP " + userData);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002105 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002106 FileOutputStream fos = null;
Amith Yamasani12747872015-12-07 14:19:49 -08002107 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userData.info.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002108 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07002109 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002110 final BufferedOutputStream bos = new BufferedOutputStream(fos);
Kenny Guy02c89902016-11-15 19:36:38 +00002111 writeUserLP(userData, bos);
Amith Yamasani2a003292012-08-14 18:25:45 -07002112 userFile.finishWrite(fos);
2113 } catch (Exception ioe) {
Jeff Sharkeycd575992016-03-29 14:12:49 -06002114 Slog.e(LOG_TAG, "Error writing user info " + userData.info.id, ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -07002115 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002116 }
2117 }
2118
2119 /*
Kenny Guy02c89902016-11-15 19:36:38 +00002120 * Writes the user file in this format:
2121 *
2122 * <user flags="20039023" id="0">
2123 * <name>Primary</name>
2124 * </user>
2125 */
2126 @VisibleForTesting
2127 void writeUserLP(UserData userData, OutputStream os)
2128 throws IOException, XmlPullParserException {
2129 // XmlSerializer serializer = XmlUtils.serializerInstance();
2130 final XmlSerializer serializer = new FastXmlSerializer();
2131 serializer.setOutput(os, StandardCharsets.UTF_8.name());
2132 serializer.startDocument(null, true);
2133 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2134
2135 final UserInfo userInfo = userData.info;
2136 serializer.startTag(null, TAG_USER);
2137 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
2138 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
2139 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
2140 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
2141 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
2142 Long.toString(userInfo.lastLoggedInTime));
2143 if (userInfo.lastLoggedInFingerprint != null) {
2144 serializer.attribute(null, ATTR_LAST_LOGGED_IN_FINGERPRINT,
2145 userInfo.lastLoggedInFingerprint);
2146 }
2147 if (userInfo.iconPath != null) {
2148 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
2149 }
2150 if (userInfo.partial) {
2151 serializer.attribute(null, ATTR_PARTIAL, "true");
2152 }
2153 if (userInfo.guestToRemove) {
2154 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
2155 }
2156 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
2157 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
2158 Integer.toString(userInfo.profileGroupId));
2159 }
2160 serializer.attribute(null, ATTR_PROFILE_BADGE,
2161 Integer.toString(userInfo.profileBadge));
2162 if (userInfo.restrictedProfileParentId != UserInfo.NO_PROFILE_GROUP_ID) {
2163 serializer.attribute(null, ATTR_RESTRICTED_PROFILE_PARENT_ID,
2164 Integer.toString(userInfo.restrictedProfileParentId));
2165 }
2166 // Write seed data
2167 if (userData.persistSeedData) {
2168 if (userData.seedAccountName != null) {
2169 serializer.attribute(null, ATTR_SEED_ACCOUNT_NAME, userData.seedAccountName);
2170 }
2171 if (userData.seedAccountType != null) {
2172 serializer.attribute(null, ATTR_SEED_ACCOUNT_TYPE, userData.seedAccountType);
2173 }
2174 }
2175 if (userInfo.name != null) {
2176 serializer.startTag(null, TAG_NAME);
2177 serializer.text(userInfo.name);
2178 serializer.endTag(null, TAG_NAME);
2179 }
2180 synchronized (mRestrictionsLock) {
2181 UserRestrictionsUtils.writeRestrictions(serializer,
2182 mBaseUserRestrictions.get(userInfo.id), TAG_RESTRICTIONS);
2183 UserRestrictionsUtils.writeRestrictions(serializer,
2184 mDevicePolicyLocalUserRestrictions.get(userInfo.id),
2185 TAG_DEVICE_POLICY_RESTRICTIONS);
Pavel Grafov6a40f092016-10-25 15:46:51 +01002186 UserRestrictionsUtils.writeRestrictions(serializer,
2187 mDevicePolicyGlobalUserRestrictions.get(userInfo.id),
2188 TAG_DEVICE_POLICY_GLOBAL_RESTRICTIONS);
Kenny Guy02c89902016-11-15 19:36:38 +00002189 }
2190
2191 if (userData.account != null) {
2192 serializer.startTag(null, TAG_ACCOUNT);
2193 serializer.text(userData.account);
2194 serializer.endTag(null, TAG_ACCOUNT);
2195 }
2196
2197 if (userData.persistSeedData && userData.seedAccountOptions != null) {
2198 serializer.startTag(null, TAG_SEED_ACCOUNT_OPTIONS);
2199 userData.seedAccountOptions.saveToXml(serializer);
2200 serializer.endTag(null, TAG_SEED_ACCOUNT_OPTIONS);
2201 }
2202
2203 serializer.endTag(null, TAG_USER);
2204
2205 serializer.endDocument();
2206 }
2207
2208 /*
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002209 * Writes the user list file in this format:
2210 *
Amith Yamasani2a003292012-08-14 18:25:45 -07002211 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002212 * <user id="0"></user>
2213 * <user id="2"></user>
2214 * </users>
2215 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002216 private void writeUserListLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002217 if (DBG) {
2218 debug("writeUserList");
2219 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002220 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07002221 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002222 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07002223 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002224 final BufferedOutputStream bos = new BufferedOutputStream(fos);
2225
2226 // XmlSerializer serializer = XmlUtils.serializerInstance();
2227 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002228 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002229 serializer.startDocument(null, true);
2230 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2231
2232 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -07002233 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -07002234 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002235
Adam Lesinskieddeb492014-09-08 17:50:03 -07002236 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002237 synchronized (mGuestRestrictions) {
2238 UserRestrictionsUtils
2239 .writeRestrictions(serializer, mGuestRestrictions, TAG_RESTRICTIONS);
2240 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05302241 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Pavel Grafov6a40f092016-10-25 15:46:51 +01002242 serializer.startTag(null, TAG_DEVICE_OWNER_USER_ID);
2243 serializer.attribute(null, ATTR_ID, Integer.toString(mDeviceOwnerUserId));
2244 serializer.endTag(null, TAG_DEVICE_OWNER_USER_ID);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002245 int[] userIdsToWrite;
2246 synchronized (mUsersLock) {
2247 userIdsToWrite = new int[mUsers.size()];
2248 for (int i = 0; i < userIdsToWrite.length; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002249 UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002250 userIdsToWrite[i] = user.id;
2251 }
2252 }
2253 for (int id : userIdsToWrite) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002254 serializer.startTag(null, TAG_USER);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002255 serializer.attribute(null, ATTR_ID, Integer.toString(id));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002256 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002257 }
2258
2259 serializer.endTag(null, TAG_USERS);
2260
2261 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07002262 userListFile.finishWrite(fos);
2263 } catch (Exception e) {
2264 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -07002265 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002266 }
2267 }
2268
Amith Yamasani12747872015-12-07 14:19:49 -08002269 private UserData readUserLP(int id) {
Kenny Guy02c89902016-11-15 19:36:38 +00002270 FileInputStream fis = null;
2271 try {
2272 AtomicFile userFile =
2273 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
2274 fis = userFile.openRead();
2275 return readUserLP(id, fis);
2276 } catch (IOException ioe) {
2277 Slog.e(LOG_TAG, "Error reading user list");
2278 } catch (XmlPullParserException pe) {
2279 Slog.e(LOG_TAG, "Error reading user list");
2280 } finally {
2281 IoUtils.closeQuietly(fis);
2282 }
2283 return null;
2284 }
2285
2286 @VisibleForTesting
2287 UserData readUserLP(int id, InputStream is) throws IOException,
2288 XmlPullParserException {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002289 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -07002290 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002291 String name = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -08002292 String account = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002293 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -07002294 long creationTime = 0L;
2295 long lastLoggedInTime = 0L;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002296 String lastLoggedInFingerprint = null;
Kenny Guy2a764942014-04-02 13:29:20 +01002297 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Kenny Guy02c89902016-11-15 19:36:38 +00002298 int profileBadge = 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002299 int restrictedProfileParentId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002300 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -07002301 boolean guestToRemove = false;
Amith Yamasani12747872015-12-07 14:19:49 -08002302 boolean persistSeedData = false;
2303 String seedAccountName = null;
2304 String seedAccountType = null;
2305 PersistableBundle seedAccountOptions = null;
Pavel Grafov6a40f092016-10-25 15:46:51 +01002306 Bundle baseRestrictions = null;
2307 Bundle localRestrictions = null;
2308 Bundle globalRestrictions = null;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002309
Kenny Guy02c89902016-11-15 19:36:38 +00002310 XmlPullParser parser = Xml.newPullParser();
2311 parser.setInput(is, StandardCharsets.UTF_8.name());
2312 int type;
2313 while ((type = parser.next()) != XmlPullParser.START_TAG
2314 && type != XmlPullParser.END_DOCUMENT) {
2315 // Skip
2316 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002317
Kenny Guy02c89902016-11-15 19:36:38 +00002318 if (type != XmlPullParser.START_TAG) {
2319 Slog.e(LOG_TAG, "Unable to read user " + id);
2320 return null;
2321 }
2322
2323 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
2324 int storedId = readIntAttribute(parser, ATTR_ID, -1);
2325 if (storedId != id) {
2326 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002327 return null;
2328 }
Kenny Guy02c89902016-11-15 19:36:38 +00002329 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
2330 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
2331 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
2332 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
2333 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
2334 lastLoggedInFingerprint = parser.getAttributeValue(null,
2335 ATTR_LAST_LOGGED_IN_FINGERPRINT);
2336 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
2337 UserInfo.NO_PROFILE_GROUP_ID);
2338 profileBadge = readIntAttribute(parser, ATTR_PROFILE_BADGE, 0);
2339 restrictedProfileParentId = readIntAttribute(parser,
2340 ATTR_RESTRICTED_PROFILE_PARENT_ID, UserInfo.NO_PROFILE_GROUP_ID);
2341 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
2342 if ("true".equals(valueString)) {
2343 partial = true;
2344 }
2345 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
2346 if ("true".equals(valueString)) {
2347 guestToRemove = true;
2348 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002349
Kenny Guy02c89902016-11-15 19:36:38 +00002350 seedAccountName = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_NAME);
2351 seedAccountType = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_TYPE);
2352 if (seedAccountName != null || seedAccountType != null) {
2353 persistSeedData = true;
2354 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002355
Kenny Guy02c89902016-11-15 19:36:38 +00002356 int outerDepth = parser.getDepth();
2357 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2358 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2359 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2360 continue;
2361 }
2362 String tag = parser.getName();
2363 if (TAG_NAME.equals(tag)) {
2364 type = parser.next();
2365 if (type == XmlPullParser.TEXT) {
2366 name = parser.getText();
2367 }
2368 } else if (TAG_RESTRICTIONS.equals(tag)) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01002369 baseRestrictions = UserRestrictionsUtils.readRestrictions(parser);
Kenny Guy02c89902016-11-15 19:36:38 +00002370 } else if (TAG_DEVICE_POLICY_RESTRICTIONS.equals(tag)) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01002371 localRestrictions = UserRestrictionsUtils.readRestrictions(parser);
2372 } else if (TAG_DEVICE_POLICY_GLOBAL_RESTRICTIONS.equals(tag)) {
2373 globalRestrictions = UserRestrictionsUtils.readRestrictions(parser);
Kenny Guy02c89902016-11-15 19:36:38 +00002374 } else if (TAG_ACCOUNT.equals(tag)) {
2375 type = parser.next();
2376 if (type == XmlPullParser.TEXT) {
2377 account = parser.getText();
2378 }
2379 } else if (TAG_SEED_ACCOUNT_OPTIONS.equals(tag)) {
2380 seedAccountOptions = PersistableBundle.restoreFromXml(parser);
Amith Yamasani12747872015-12-07 14:19:49 -08002381 persistSeedData = true;
2382 }
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08002383 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002384 }
Kenny Guy02c89902016-11-15 19:36:38 +00002385
2386 // Create the UserInfo object that gets passed around
2387 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
2388 userInfo.serialNumber = serialNumber;
2389 userInfo.creationTime = creationTime;
2390 userInfo.lastLoggedInTime = lastLoggedInTime;
2391 userInfo.lastLoggedInFingerprint = lastLoggedInFingerprint;
2392 userInfo.partial = partial;
2393 userInfo.guestToRemove = guestToRemove;
2394 userInfo.profileGroupId = profileGroupId;
2395 userInfo.profileBadge = profileBadge;
2396 userInfo.restrictedProfileParentId = restrictedProfileParentId;
2397
2398 // Create the UserData object that's internal to this class
2399 UserData userData = new UserData();
2400 userData.info = userInfo;
2401 userData.account = account;
2402 userData.seedAccountName = seedAccountName;
2403 userData.seedAccountType = seedAccountType;
2404 userData.persistSeedData = persistSeedData;
2405 userData.seedAccountOptions = seedAccountOptions;
2406
2407 synchronized (mRestrictionsLock) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01002408 if (baseRestrictions != null) {
2409 mBaseUserRestrictions.put(id, baseRestrictions);
2410 }
2411 if (localRestrictions != null) {
2412 mDevicePolicyLocalUserRestrictions.put(id, localRestrictions);
2413 }
2414 if (globalRestrictions != null) {
2415 mDevicePolicyGlobalUserRestrictions.put(id, globalRestrictions);
2416 }
Kenny Guy02c89902016-11-15 19:36:38 +00002417 }
2418 return userData;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002419 }
2420
Amith Yamasani920ace02012-09-20 22:15:37 -07002421 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
2422 String valueString = parser.getAttributeValue(null, attr);
2423 if (valueString == null) return defaultValue;
2424 try {
2425 return Integer.parseInt(valueString);
2426 } catch (NumberFormatException nfe) {
2427 return defaultValue;
2428 }
2429 }
2430
2431 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
2432 String valueString = parser.getAttributeValue(null, attr);
2433 if (valueString == null) return defaultValue;
2434 try {
2435 return Long.parseLong(valueString);
2436 } catch (NumberFormatException nfe) {
2437 return defaultValue;
2438 }
2439 }
2440
Amith Yamasanib82add22013-07-09 11:24:44 -07002441 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002442 * Removes the app restrictions file for a specific package and user id, if it exists.
2443 */
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07002444 private static void cleanAppRestrictionsForPackageLAr(String pkg, int userId) {
2445 File dir = Environment.getUserSystemDirectory(userId);
2446 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
2447 if (resFile.exists()) {
2448 resFile.delete();
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002449 }
2450 }
2451
Kenny Guya52dc3e2014-02-11 15:33:14 +00002452 @Override
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002453 public UserInfo createProfileForUser(String name, int flags, int userId,
2454 String[] disallowedPackages) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002455 checkManageOrCreateUsersPermission(flags);
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002456 return createUserInternal(name, flags, userId, disallowedPackages);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002457 }
2458
Amith Yamasani258848d2012-08-10 17:06:33 -07002459 @Override
Tony Mak6dc428f2016-10-10 15:48:27 +01002460 public UserInfo createProfileForUserEvenWhenDisallowed(String name, int flags, int userId,
2461 String[] disallowedPackages) {
2462 checkManageOrCreateUsersPermission(flags);
2463 return createUserInternalUnchecked(name, flags, userId, disallowedPackages);
2464 }
2465
2466 @Override
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00002467 public boolean removeUserEvenWhenDisallowed(@UserIdInt int userHandle) {
2468 checkManageOrCreateUsersPermission("Only the system can remove users");
2469 return removeUserUnchecked(userHandle);
2470 }
2471
2472 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07002473 public UserInfo createUser(String name, int flags) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002474 checkManageOrCreateUsersPermission(flags);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00002475 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002476 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07002477
Jessica Hummelbe81c802014-04-22 15:49:22 +01002478 private UserInfo createUserInternal(String name, int flags, int parentId) {
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002479 return createUserInternal(name, flags, parentId, null);
2480 }
2481
2482 private UserInfo createUserInternal(String name, int flags, int parentId,
2483 String[] disallowedPackages) {
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002484 String restriction = ((flags & UserInfo.FLAG_MANAGED_PROFILE) != 0)
2485 ? UserManager.DISALLOW_ADD_MANAGED_PROFILE
2486 : UserManager.DISALLOW_ADD_USER;
2487 if (hasUserRestriction(restriction, UserHandle.getCallingUserId())) {
2488 Log.w(LOG_TAG, "Cannot add user. " + restriction + " is enabled.");
Julia Reynolds75175022014-06-26 16:35:00 -04002489 return null;
2490 }
Tony Mak6dc428f2016-10-10 15:48:27 +01002491 return createUserInternalUnchecked(name, flags, parentId, disallowedPackages);
2492 }
2493
2494 private UserInfo createUserInternalUnchecked(String name, int flags, int parentId,
2495 String[] disallowedPackages) {
Suprabh Shuklac5e057c2016-08-08 16:22:44 -07002496 DeviceStorageMonitorInternal dsm = LocalServices
2497 .getService(DeviceStorageMonitorInternal.class);
2498 if (dsm.isMemoryLow()) {
2499 Log.w(LOG_TAG, "Cannot add user. Not enough space on disk.");
2500 return null;
2501 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07002502 if (ActivityManager.isLowRamDeviceStatic()) {
2503 return null;
2504 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07002505 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Nicolas Prevot12678a92015-05-13 12:15:03 -07002506 final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002507 final boolean isRestricted = (flags & UserInfo.FLAG_RESTRICTED) != 0;
Amith Yamasani52c21e32016-05-31 09:12:20 -07002508 final boolean isDemo = (flags & UserInfo.FLAG_DEMO) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002509 final long ident = Binder.clearCallingIdentity();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002510 UserInfo userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08002511 UserData userData;
Amith Yamasanibb054c92015-07-09 14:16:27 -07002512 final int userId;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002513 try {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002514 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002515 UserData parent = null;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002516 if (parentId != UserHandle.USER_NULL) {
2517 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002518 parent = getUserDataLU(parentId);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00002519 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002520 if (parent == null) return null;
2521 }
2522 if (isManagedProfile && !canAddMoreManagedProfiles(parentId, false)) {
2523 Log.e(LOG_TAG, "Cannot add more managed profiles for user " + parentId);
2524 return null;
2525 }
Amith Yamasani52c21e32016-05-31 09:12:20 -07002526 if (!isGuest && !isManagedProfile && !isDemo && isUserLimitReached()) {
2527 // If we're not adding a guest/demo user or a managed profile and the limit has
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002528 // been reached, cannot add a user.
2529 return null;
2530 }
2531 // If we're adding a guest and there already exists one, bail.
2532 if (isGuest && findCurrentGuestUser() != null) {
2533 return null;
2534 }
2535 // In legacy mode, restricted profile's parent can only be the owner user
2536 if (isRestricted && !UserManager.isSplitSystemUser()
2537 && (parentId != UserHandle.USER_SYSTEM)) {
2538 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
2539 return null;
2540 }
2541 if (isRestricted && UserManager.isSplitSystemUser()) {
2542 if (parent == null) {
2543 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be "
2544 + "specified");
Nicolas Prevot12678a92015-05-13 12:15:03 -07002545 return null;
2546 }
Amith Yamasani12747872015-12-07 14:19:49 -08002547 if (!parent.info.canHaveProfile()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002548 Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be "
2549 + "created for the specified parent user id " + parentId);
Amith Yamasani95ab7842014-08-11 17:09:26 -07002550 return null;
2551 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002552 }
2553 // In split system user mode, we assign the first human user the primary flag.
2554 // And if there is no device owner, we also assign the admin flag to primary user.
2555 if (UserManager.isSplitSystemUser()
2556 && !isGuest && !isManagedProfile && getPrimaryUser() == null) {
2557 flags |= UserInfo.FLAG_PRIMARY;
Makoto Onukie7927da2015-11-25 10:05:17 -08002558 synchronized (mUsersLock) {
2559 if (!mIsDeviceManaged) {
2560 flags |= UserInfo.FLAG_ADMIN;
2561 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07002562 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002563 }
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002564
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002565 userId = getNextAvailableId();
2566 Environment.getUserSystemDirectory(userId).mkdirs();
Lenka Trochtova02fee152015-12-22 14:26:18 +01002567 boolean ephemeralGuests = Resources.getSystem()
2568 .getBoolean(com.android.internal.R.bool.config_guestUserEphemeral);
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002569
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002570 synchronized (mUsersLock) {
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002571 // Add ephemeral flag to guests/users if required. Also inherit it from parent.
2572 if ((isGuest && ephemeralGuests) || mForceEphemeralUsers
2573 || (parent != null && parent.info.isEphemeral())) {
2574 flags |= UserInfo.FLAG_EPHEMERAL;
2575 }
2576
2577 userInfo = new UserInfo(userId, name, null, flags);
2578 userInfo.serialNumber = mNextSerialNumber++;
2579 long now = System.currentTimeMillis();
2580 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
2581 userInfo.partial = true;
Fyodor Kupolov83c24242016-03-31 13:30:42 -07002582 userInfo.lastLoggedInFingerprint = Build.FINGERPRINT;
Kenny Guy02c89902016-11-15 19:36:38 +00002583 if (isManagedProfile && parentId != UserHandle.USER_NULL) {
2584 userInfo.profileBadge = getFreeProfileBadgeLU(parentId);
2585 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002586 userData = new UserData();
2587 userData.info = userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08002588 mUsers.put(userId, userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002589 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06002590 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002591 writeUserListLP();
2592 if (parent != null) {
2593 if (isManagedProfile) {
Amith Yamasani12747872015-12-07 14:19:49 -08002594 if (parent.info.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
2595 parent.info.profileGroupId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002596 writeUserLP(parent);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002597 }
Amith Yamasani12747872015-12-07 14:19:49 -08002598 userInfo.profileGroupId = parent.info.profileGroupId;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002599 } else if (isRestricted) {
Amith Yamasani12747872015-12-07 14:19:49 -08002600 if (parent.info.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) {
2601 parent.info.restrictedProfileParentId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002602 writeUserLP(parent);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002603 }
Amith Yamasani12747872015-12-07 14:19:49 -08002604 userInfo.restrictedProfileParentId = parent.info.restrictedProfileParentId;
Makoto Onuki068c54a2015-10-13 14:34:03 -07002605 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002606 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07002607 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002608 final StorageManager storage = mContext.getSystemService(StorageManager.class);
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002609 storage.createUserKey(userId, userInfo.serialNumber, userInfo.isEphemeral());
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -08002610 mUserDataPreparer.prepareUserData(userId, userInfo.serialNumber,
Jeff Sharkey47f71082016-02-01 17:03:54 -07002611 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002612 mPm.createNewUser(userId, disallowedPackages);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002613 userInfo.partial = false;
2614 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002615 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002616 }
2617 updateUserIds();
2618 Bundle restrictions = new Bundle();
Fyodor Kupolove04462c2015-11-30 15:02:53 -08002619 if (isGuest) {
2620 synchronized (mGuestRestrictions) {
2621 restrictions.putAll(mGuestRestrictions);
2622 }
2623 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002624 synchronized (mRestrictionsLock) {
2625 mBaseUserRestrictions.append(userId, restrictions);
2626 }
Fyodor Kupolov5fd967d2016-07-12 14:46:19 -07002627 mPm.onNewUserCreated(userId);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002628 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
2629 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
2630 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
2631 android.Manifest.permission.MANAGE_USERS);
Christine Franks88220562017-05-24 11:11:21 -07002632 MetricsLogger.count(mContext, isGuest ? TRON_GUEST_CREATED
2633 : (isDemo ? TRON_DEMO_CREATED : TRON_USER_CREATED), 1);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002634 } finally {
2635 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07002636 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002637 return userInfo;
2638 }
2639
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002640 @VisibleForTesting
2641 UserData putUserInfo(UserInfo userInfo) {
2642 final UserData userData = new UserData();
2643 userData.info = userInfo;
2644 synchronized (mUsers) {
2645 mUsers.put(userInfo.id, userData);
2646 }
2647 return userData;
2648 }
2649
2650 @VisibleForTesting
2651 void removeUserInfo(int userId) {
2652 synchronized (mUsers) {
2653 mUsers.remove(userId);
2654 }
2655 }
2656
Amith Yamasani0b285492011-04-14 17:35:23 -07002657 /**
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002658 * @hide
2659 */
Amith Yamasani12747872015-12-07 14:19:49 -08002660 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002661 public UserInfo createRestrictedProfile(String name, int parentUserId) {
Sudheer Shanka53d41472016-06-16 09:11:08 -07002662 checkManageOrCreateUsersPermission("setupRestrictedProfile");
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002663 final UserInfo user = createProfileForUser(
2664 name, UserInfo.FLAG_RESTRICTED, parentUserId, null);
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002665 if (user == null) {
2666 return null;
2667 }
Fyodor Kupolov9e912ba2016-02-09 18:29:43 -08002668 long identity = Binder.clearCallingIdentity();
2669 try {
2670 setUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, true, user.id);
2671 // Change the setting before applying the DISALLOW_SHARE_LOCATION restriction, otherwise
2672 // the putIntForUser() will fail.
2673 android.provider.Settings.Secure.putIntForUser(mContext.getContentResolver(),
2674 android.provider.Settings.Secure.LOCATION_MODE,
2675 android.provider.Settings.Secure.LOCATION_MODE_OFF, user.id);
2676 setUserRestriction(UserManager.DISALLOW_SHARE_LOCATION, true, user.id);
2677 } finally {
2678 Binder.restoreCallingIdentity(identity);
2679 }
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002680 return user;
2681 }
2682
2683 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07002684 * Find the current guest user. If the Guest user is partial,
2685 * then do not include it in the results as it is about to die.
Adam Lesinskieddeb492014-09-08 17:50:03 -07002686 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002687 private UserInfo findCurrentGuestUser() {
2688 synchronized (mUsersLock) {
2689 final int size = mUsers.size();
2690 for (int i = 0; i < size; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002691 final UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002692 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
2693 return user;
2694 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002695 }
2696 }
2697 return null;
2698 }
2699
2700 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07002701 * Mark this guest user for deletion to allow us to create another guest
2702 * and switch to that user before actually removing this guest.
2703 * @param userHandle the userid of the current guest
2704 * @return whether the user could be marked for deletion
2705 */
Amith Yamasani12747872015-12-07 14:19:49 -08002706 @Override
Amith Yamasani1df14732014-08-29 21:37:27 -07002707 public boolean markGuestForDeletion(int userHandle) {
2708 checkManageUsersPermission("Only the system can remove users");
2709 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
2710 UserManager.DISALLOW_REMOVE_USER, false)) {
2711 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
2712 return false;
2713 }
2714
2715 long ident = Binder.clearCallingIdentity();
2716 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002717 final UserData userData;
Amith Yamasani1df14732014-08-29 21:37:27 -07002718 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002719 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002720 userData = mUsers.get(userHandle);
2721 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002722 return false;
2723 }
Amith Yamasani1df14732014-08-29 21:37:27 -07002724 }
Amith Yamasani12747872015-12-07 14:19:49 -08002725 if (!userData.info.isGuest()) {
Amith Yamasani1df14732014-08-29 21:37:27 -07002726 return false;
2727 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002728 // We set this to a guest user that is to be removed. This is a temporary state
2729 // where we are allowed to add new Guest users, even if this one is still not
2730 // removed. This user will still show up in getUserInfo() calls.
2731 // If we don't get around to removing this Guest user, it will be purged on next
2732 // startup.
Amith Yamasani12747872015-12-07 14:19:49 -08002733 userData.info.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07002734 // Mark it as disabled, so that it isn't returned any more when
2735 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002736 userData.info.flags |= UserInfo.FLAG_DISABLED;
2737 writeUserLP(userData);
Amith Yamasani1df14732014-08-29 21:37:27 -07002738 }
2739 } finally {
2740 Binder.restoreCallingIdentity(ident);
2741 }
2742 return true;
2743 }
2744
2745 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002746 * Removes a user and all data directories created for that user. This method should be called
2747 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07002748 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07002749 */
Amith Yamasani12747872015-12-07 14:19:49 -08002750 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -07002751 public boolean removeUser(int userHandle) {
Fyodor Kupolov4593e422016-10-27 11:00:29 -07002752 Slog.i(LOG_TAG, "removeUser u" + userHandle);
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002753 checkManageOrCreateUsersPermission("Only the system can remove users");
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002754
2755 final boolean isManagedProfile;
2756 synchronized (mUsersLock) {
2757 UserInfo userInfo = getUserInfoLU(userHandle);
2758 isManagedProfile = userInfo != null && userInfo.isManagedProfile();
2759 }
2760 String restriction = isManagedProfile
2761 ? UserManager.DISALLOW_REMOVE_MANAGED_PROFILE : UserManager.DISALLOW_REMOVE_USER;
2762 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(restriction, false)) {
2763 Log.w(LOG_TAG, "Cannot remove user. " + restriction + " is enabled.");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04002764 return false;
2765 }
Nicolas Prevotdf1b87d2016-10-25 13:57:08 +01002766 return removeUserUnchecked(userHandle);
2767 }
Julia Reynolds4ac5f852014-06-23 17:38:51 -04002768
Nicolas Prevotdf1b87d2016-10-25 13:57:08 +01002769 private boolean removeUserUnchecked(int userHandle) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002770 long ident = Binder.clearCallingIdentity();
2771 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002772 final UserData userData;
Fyodor Kupolov0df68cd2015-10-01 13:54:22 -07002773 int currentUser = ActivityManager.getCurrentUser();
2774 if (currentUser == userHandle) {
2775 Log.w(LOG_TAG, "Current user cannot be removed");
2776 return false;
2777 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002778 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002779 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002780 userData = mUsers.get(userHandle);
2781 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002782 return false;
2783 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002784
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002785 addRemovingUserIdLocked(userHandle);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002786 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002787
Kenny Guyee58b4f2014-05-23 15:19:53 +01002788 // Set this to a partially created user, so that the user will be purged
2789 // on next startup, in case the runtime stops now before stopping and
2790 // removing the user completely.
Amith Yamasani12747872015-12-07 14:19:49 -08002791 userData.info.partial = true;
Kenny Guyee58b4f2014-05-23 15:19:53 +01002792 // Mark it as disabled, so that it isn't returned any more when
2793 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002794 userData.info.flags |= UserInfo.FLAG_DISABLED;
2795 writeUserLP(userData);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002796 }
Fyodor Kupolov6c96f7f2017-06-28 18:22:59 -07002797 try {
2798 mAppOpsService.removeUser(userHandle);
2799 } catch (RemoteException e) {
2800 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
2801 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002802
Amith Yamasani12747872015-12-07 14:19:49 -08002803 if (userData.info.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
2804 && userData.info.isManagedProfile()) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002805 // Send broadcast to notify system that the user removed was a
2806 // managed user.
Amith Yamasani12747872015-12-07 14:19:49 -08002807 sendProfileRemovedBroadcast(userData.info.profileGroupId, userData.info.id);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002808 }
2809
2810 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
2811 int res;
2812 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08002813 res = ActivityManager.getService().stopUser(userHandle, /* force= */ true,
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07002814 new IStopUserCallback.Stub() {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002815 @Override
2816 public void userStopped(int userId) {
2817 finishRemoveUser(userId);
2818 }
2819 @Override
2820 public void userStopAborted(int userId) {
2821 }
2822 });
2823 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002824 return false;
2825 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002826 return res == ActivityManager.USER_OP_SUCCESS;
2827 } finally {
2828 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002829 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002830 }
2831
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002832 @VisibleForTesting
2833 void addRemovingUserIdLocked(int userId) {
2834 // We remember deleted user IDs to prevent them from being
2835 // reused during the current boot; they can still be reused
2836 // after a reboot or recycling of userIds.
2837 mRemovingUserIds.put(userId, true);
2838 mRecentlyRemovedIds.add(userId);
2839 // Keep LRU queue of recently removed IDs for recycling
2840 if (mRecentlyRemovedIds.size() > MAX_RECENTLY_REMOVED_IDS_SIZE) {
2841 mRecentlyRemovedIds.removeFirst();
2842 }
2843 }
2844
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002845 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07002846 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002847 // Let other services shutdown any activity and clean up their state before completely
2848 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002849 long ident = Binder.clearCallingIdentity();
2850 try {
2851 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
2852 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002853 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
2854 android.Manifest.permission.MANAGE_USERS,
2855
2856 new BroadcastReceiver() {
2857 @Override
2858 public void onReceive(Context context, Intent intent) {
2859 if (DBG) {
2860 Slog.i(LOG_TAG,
2861 "USER_REMOVED broadcast sent, cleaning up user data "
2862 + userHandle);
2863 }
2864 new Thread() {
Amith Yamasani12747872015-12-07 14:19:49 -08002865 @Override
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002866 public void run() {
Amith Yamasani515d4062015-09-28 11:30:06 -07002867 // Clean up any ActivityManager state
2868 LocalServices.getService(ActivityManagerInternal.class)
2869 .onUserRemoved(userHandle);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002870 removeUserState(userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002871 }
2872 }.start();
2873 }
2874 },
2875
2876 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002877 } finally {
2878 Binder.restoreCallingIdentity(ident);
2879 }
Amith Yamasani2a003292012-08-14 18:25:45 -07002880 }
2881
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002882 private void removeUserState(final int userHandle) {
Paul Crowley91293792016-03-25 15:23:07 -07002883 try {
2884 mContext.getSystemService(StorageManager.class).destroyUserKey(userHandle);
2885 } catch (IllegalStateException e) {
2886 // This may be simply because the user was partially created.
2887 Slog.i(LOG_TAG,
2888 "Destroying key for user " + userHandle + " failed, continuing anyway", e);
2889 }
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002890
Amith Yamasanid04aaa32016-06-13 12:09:36 -07002891 // Cleanup gatekeeper secure user id
2892 try {
2893 final IGateKeeperService gk = GateKeeper.getService();
2894 if (gk != null) {
2895 gk.clearSecureUserId(userHandle);
2896 }
2897 } catch (Exception ex) {
2898 Slog.w(LOG_TAG, "unable to clear GK secure user id");
2899 }
2900
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002901 // Cleanup package manager settings
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002902 mPm.cleanUpUser(this, userHandle);
Amith Yamasanid04aaa32016-06-13 12:09:36 -07002903
2904 // Clean up all data before removing metadata
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -08002905 mUserDataPreparer.destroyUserData(userHandle,
Amith Yamasanid04aaa32016-06-13 12:09:36 -07002906 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2907
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002908 // Remove this user from the list
Fyodor Kupolov82402752015-10-28 14:54:51 -07002909 synchronized (mUsersLock) {
2910 mUsers.remove(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08002911 mIsUserManaged.delete(userHandle);
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00002912 }
2913 synchronized (mUserStates) {
2914 mUserStates.delete(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08002915 }
2916 synchronized (mRestrictionsLock) {
2917 mBaseUserRestrictions.remove(userHandle);
2918 mAppliedUserRestrictions.remove(userHandle);
2919 mCachedEffectiveUserRestrictions.remove(userHandle);
2920 mDevicePolicyLocalUserRestrictions.remove(userHandle);
Pavel Grafov6a40f092016-10-25 15:46:51 +01002921 if (mDevicePolicyGlobalUserRestrictions.get(userHandle) != null) {
2922 mDevicePolicyGlobalUserRestrictions.remove(userHandle);
2923 applyUserRestrictionsForAllUsersLR();
2924 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002925 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002926 // Update the user list
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002927 synchronized (mPackagesLock) {
2928 writeUserListLP();
2929 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06002930 // Remove user file
2931 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
2932 userFile.delete();
Fyodor Kupolov82402752015-10-28 14:54:51 -07002933 updateUserIds();
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002934 if (RELEASE_DELETED_USER_ID) {
2935 synchronized (mUsers) {
2936 mRemovingUserIds.delete(userHandle);
2937 }
2938 }
Amith Yamasani61f57372012-08-31 12:12:28 -07002939 }
2940
Kenny Guyf8d3a232014-05-15 16:09:52 +01002941 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01002942 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01002943 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
2944 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002945 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
Jeff Sharkeyaf6ec292015-12-17 11:19:00 -07002946 managedProfileIntent.putExtra(Intent.EXTRA_USER_HANDLE, removedUserId);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002947 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01002948 }
2949
Amith Yamasani2a003292012-08-14 18:25:45 -07002950 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002951 public Bundle getApplicationRestrictions(String packageName) {
2952 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
2953 }
2954
2955 @Override
2956 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002957 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07002958 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07002959 checkSystemOrRoot("get application restrictions for other user/app " + packageName);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002960 }
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07002961 synchronized (mAppRestrictionsLock) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002962 // Read the restrictions from XML
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07002963 return readApplicationRestrictionsLAr(packageName, userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002964 }
2965 }
2966
2967 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002968 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002969 int userId) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00002970 checkSystemOrRoot("set application restrictions");
Fyodor Kupolov0d88d542016-04-19 11:37:22 -07002971 if (restrictions != null) {
2972 restrictions.setDefusable(true);
2973 }
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07002974 synchronized (mAppRestrictionsLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01002975 if (restrictions == null || restrictions.isEmpty()) {
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07002976 cleanAppRestrictionsForPackageLAr(packageName, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01002977 } else {
2978 // Write the restrictions to XML
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07002979 writeApplicationRestrictionsLAr(packageName, restrictions, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01002980 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002981 }
Robin Lee66e5d962014-04-09 16:44:21 +01002982
Fyodor Kupolovd2846122016-02-11 18:06:34 -08002983 // Notify package of changes via an intent - only sent to explicitly registered receivers.
2984 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
2985 changeIntent.setPackage(packageName);
2986 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
2987 mContext.sendBroadcastAsUser(changeIntent, UserHandle.of(userId));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002988 }
2989
2990 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07002991 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002992 try {
2993 return mContext.getPackageManager().getApplicationInfo(packageName,
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07002994 PackageManager.MATCH_ANY_USER).uid;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002995 } catch (NameNotFoundException nnfe) {
2996 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07002997 } finally {
2998 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002999 }
3000 }
3001
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003002 @GuardedBy("mAppRestrictionsLock")
3003 private static Bundle readApplicationRestrictionsLAr(String packageName, int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003004 AtomicFile restrictionsFile =
3005 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
3006 packageToRestrictionsFileName(packageName)));
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003007 return readApplicationRestrictionsLAr(restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003008 }
3009
3010 @VisibleForTesting
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003011 @GuardedBy("mAppRestrictionsLock")
3012 static Bundle readApplicationRestrictionsLAr(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07003013 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003014 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07003015 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07003016 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07003017 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003018
3019 FileInputStream fis = null;
3020 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003021 fis = restrictionsFile.openRead();
3022 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01003023 parser.setInput(fis, StandardCharsets.UTF_8.name());
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003024 XmlUtils.nextElement(parser);
3025 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003026 Slog.e(LOG_TAG, "Unable to read restrictions file "
3027 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07003028 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003029 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003030 while (parser.next() != XmlPullParser.END_DOCUMENT) {
3031 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003032 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003033 } catch (IOException|XmlPullParserException e) {
3034 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003035 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003036 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003037 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07003038 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003039 }
3040
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003041 private static void readEntry(Bundle restrictions, ArrayList<String> values,
3042 XmlPullParser parser) throws XmlPullParserException, IOException {
3043 int type = parser.getEventType();
3044 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
3045 String key = parser.getAttributeValue(null, ATTR_KEY);
3046 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
3047 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
3048 if (multiple != null) {
3049 values.clear();
3050 int count = Integer.parseInt(multiple);
3051 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
3052 if (type == XmlPullParser.START_TAG
3053 && parser.getName().equals(TAG_VALUE)) {
3054 values.add(parser.nextText().trim());
3055 count--;
3056 }
3057 }
3058 String [] valueStrings = new String[values.size()];
3059 values.toArray(valueStrings);
3060 restrictions.putStringArray(key, valueStrings);
3061 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
3062 restrictions.putBundle(key, readBundleEntry(parser, values));
3063 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
3064 final int outerDepth = parser.getDepth();
3065 ArrayList<Bundle> bundleList = new ArrayList<>();
3066 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
3067 Bundle childBundle = readBundleEntry(parser, values);
3068 bundleList.add(childBundle);
3069 }
3070 restrictions.putParcelableArray(key,
3071 bundleList.toArray(new Bundle[bundleList.size()]));
3072 } else {
3073 String value = parser.nextText().trim();
3074 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
3075 restrictions.putBoolean(key, Boolean.parseBoolean(value));
3076 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
3077 restrictions.putInt(key, Integer.parseInt(value));
3078 } else {
3079 restrictions.putString(key, value);
3080 }
3081 }
3082 }
3083 }
3084
3085 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
3086 throws IOException, XmlPullParserException {
3087 Bundle childBundle = new Bundle();
3088 final int outerDepth = parser.getDepth();
3089 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
3090 readEntry(childBundle, values, parser);
3091 }
3092 return childBundle;
3093 }
3094
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003095 @GuardedBy("mAppRestrictionsLock")
3096 private static void writeApplicationRestrictionsLAr(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07003097 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003098 AtomicFile restrictionsFile = new AtomicFile(
3099 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07003100 packageToRestrictionsFileName(packageName)));
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003101 writeApplicationRestrictionsLAr(restrictions, restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003102 }
3103
3104 @VisibleForTesting
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003105 @GuardedBy("mAppRestrictionsLock")
3106 static void writeApplicationRestrictionsLAr(Bundle restrictions, AtomicFile restrictionsFile) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003107 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003108 try {
3109 fos = restrictionsFile.startWrite();
3110 final BufferedOutputStream bos = new BufferedOutputStream(fos);
3111
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003112 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01003113 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003114 serializer.startDocument(null, true);
3115 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
3116
3117 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003118 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003119 serializer.endTag(null, TAG_RESTRICTIONS);
3120
3121 serializer.endDocument();
3122 restrictionsFile.finishWrite(fos);
3123 } catch (Exception e) {
3124 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003125 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
3126 }
3127 }
3128
3129 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
3130 throws IOException {
3131 for (String key : restrictions.keySet()) {
3132 Object value = restrictions.get(key);
3133 serializer.startTag(null, TAG_ENTRY);
3134 serializer.attribute(null, ATTR_KEY, key);
3135
3136 if (value instanceof Boolean) {
3137 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
3138 serializer.text(value.toString());
3139 } else if (value instanceof Integer) {
3140 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
3141 serializer.text(value.toString());
3142 } else if (value == null || value instanceof String) {
3143 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
3144 serializer.text(value != null ? (String) value : "");
3145 } else if (value instanceof Bundle) {
3146 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
3147 writeBundle((Bundle) value, serializer);
3148 } else if (value instanceof Parcelable[]) {
3149 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
3150 Parcelable[] array = (Parcelable[]) value;
3151 for (Parcelable parcelable : array) {
3152 if (!(parcelable instanceof Bundle)) {
3153 throw new IllegalArgumentException("bundle-array can only hold Bundles");
3154 }
3155 serializer.startTag(null, TAG_ENTRY);
3156 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
3157 writeBundle((Bundle) parcelable, serializer);
3158 serializer.endTag(null, TAG_ENTRY);
3159 }
3160 } else {
3161 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
3162 String[] values = (String[]) value;
3163 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
3164 for (String choice : values) {
3165 serializer.startTag(null, TAG_VALUE);
3166 serializer.text(choice != null ? choice : "");
3167 serializer.endTag(null, TAG_VALUE);
3168 }
3169 }
3170 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003171 }
3172 }
3173
3174 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07003175 public int getUserSerialNumber(int userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003176 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07003177 if (!exists(userHandle)) return -1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003178 return getUserInfoLU(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07003179 }
3180 }
3181
3182 @Override
Fyodor Kupolov605b12a2017-05-10 15:58:09 -07003183 public boolean isUserNameSet(int userHandle) {
3184 synchronized (mUsersLock) {
3185 UserInfo userInfo = getUserInfoLU(userHandle);
3186 return userInfo != null && userInfo.name != null;
3187 }
3188 }
3189
3190 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07003191 public int getUserHandle(int userSerialNumber) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003192 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07003193 for (int userId : mUserIds) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003194 UserInfo info = getUserInfoLU(userId);
Kenny Guy945f8832015-02-10 15:17:26 +00003195 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07003196 }
3197 // Not found
3198 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07003199 }
3200 }
3201
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003202 @Override
3203 public long getUserCreationTime(int userHandle) {
3204 int callingUserId = UserHandle.getCallingUserId();
3205 UserInfo userInfo = null;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003206 synchronized (mUsersLock) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003207 if (callingUserId == userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003208 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003209 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003210 UserInfo parent = getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003211 if (parent != null && parent.id == callingUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003212 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003213 }
3214 }
3215 }
3216 if (userInfo == null) {
3217 throw new SecurityException("userHandle can only be the calling user or a managed "
3218 + "profile associated with this user");
3219 }
3220 return userInfo.creationTime;
3221 }
3222
Amith Yamasani0b285492011-04-14 17:35:23 -07003223 /**
3224 * Caches the list of user ids in an array, adjusting the array size when necessary.
3225 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07003226 private void updateUserIds() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003227 int num = 0;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003228 synchronized (mUsersLock) {
3229 final int userSize = mUsers.size();
3230 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003231 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003232 num++;
3233 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003234 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07003235 final int[] newUsers = new int[num];
3236 int n = 0;
3237 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003238 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003239 newUsers[n++] = mUsers.keyAt(i);
3240 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003241 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07003242 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07003243 }
3244 }
3245
3246 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003247 * Called right before a user is started. This gives us a chance to prepare
3248 * app storage and apply any user restrictions.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003249 */
3250 public void onBeforeStartUser(int userId) {
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003251 UserInfo userInfo = getUserInfo(userId);
3252 if (userInfo == null) {
3253 return;
3254 }
3255 final int userSerial = userInfo.serialNumber;
3256 // Migrate only if build fingerprints mismatch
3257 boolean migrateAppsData = !Build.FINGERPRINT.equals(userInfo.lastLoggedInFingerprint);
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -08003258 mUserDataPreparer.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_DE);
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003259 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_DE, migrateAppsData);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003260
3261 if (userId != UserHandle.USER_SYSTEM) {
3262 synchronized (mRestrictionsLock) {
3263 applyUserRestrictionsLR(userId);
3264 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003265 }
3266 }
3267
3268 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003269 * Called right before a user is unlocked. This gives us a chance to prepare
3270 * app storage.
3271 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003272 public void onBeforeUnlockUser(@UserIdInt int userId) {
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003273 UserInfo userInfo = getUserInfo(userId);
3274 if (userInfo == null) {
3275 return;
3276 }
3277 final int userSerial = userInfo.serialNumber;
3278 // Migrate only if build fingerprints mismatch
3279 boolean migrateAppsData = !Build.FINGERPRINT.equals(userInfo.lastLoggedInFingerprint);
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -08003280 mUserDataPreparer.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_CE);
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003281 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_CE, migrateAppsData);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003282 }
3283
3284 /**
Fyodor Kupolov50979d12017-01-27 17:36:32 -08003285 * Examine all users present on given mounted volume, and destroy data
3286 * belonging to users that are no longer valid, or whose user ID has been
3287 * recycled.
3288 */
3289 void reconcileUsers(String volumeUuid) {
3290 mUserDataPreparer.reconcileUsers(volumeUuid, getUsers(true /* excludeDying */));
3291 }
3292
3293 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07003294 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasanieb437d42016-04-29 09:31:25 -07003295 * This is called with ActivityManagerService lock held.
Amith Yamasani920ace02012-09-20 22:15:37 -07003296 * @param userId the user that was just foregrounded
3297 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003298 public void onUserLoggedIn(@UserIdInt int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -08003299 UserData userData = getUserDataNoChecks(userId);
3300 if (userData == null || userData.info.partial) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003301 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
3302 return;
3303 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003304
3305 final long now = System.currentTimeMillis();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003306 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani12747872015-12-07 14:19:49 -08003307 userData.info.lastLoggedInTime = now;
Amith Yamasani920ace02012-09-20 22:15:37 -07003308 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003309 userData.info.lastLoggedInFingerprint = Build.FINGERPRINT;
3310 scheduleWriteUser(userData);
Amith Yamasani920ace02012-09-20 22:15:37 -07003311 }
3312
3313 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07003314 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani0b285492011-04-14 17:35:23 -07003315 */
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003316 @VisibleForTesting
3317 int getNextAvailableId() {
3318 int nextId;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003319 synchronized (mUsersLock) {
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003320 nextId = scanNextAvailableIdLocked();
3321 if (nextId >= 0) {
3322 return nextId;
3323 }
3324 // All ids up to MAX_USER_ID were used. Remove all mRemovingUserIds,
3325 // except most recently removed
3326 if (mRemovingUserIds.size() > 0) {
3327 Slog.i(LOG_TAG, "All available IDs are used. Recycling LRU ids.");
3328 mRemovingUserIds.clear();
3329 for (Integer recentlyRemovedId : mRecentlyRemovedIds) {
3330 mRemovingUserIds.put(recentlyRemovedId, true);
Amith Yamasani195263742012-08-21 15:40:12 -07003331 }
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003332 nextId = scanNextAvailableIdLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003333 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003334 }
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003335 if (nextId < 0) {
3336 throw new IllegalStateException("No user id available!");
3337 }
3338 return nextId;
3339 }
3340
3341 private int scanNextAvailableIdLocked() {
3342 for (int i = MIN_USER_ID; i < MAX_USER_ID; i++) {
3343 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
3344 return i;
3345 }
3346 }
3347 return -1;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003348 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003349
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003350 private static String packageToRestrictionsFileName(String packageName) {
Amith Yamasanifc95e702013-09-26 13:20:17 -07003351 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
3352 }
3353
Amith Yamasani920ace02012-09-20 22:15:37 -07003354 @Override
Amith Yamasani12747872015-12-07 14:19:49 -08003355 public void setSeedAccountData(int userId, String accountName, String accountType,
3356 PersistableBundle accountOptions, boolean persist) {
3357 checkManageUsersPermission("Require MANAGE_USERS permission to set user seed data");
3358 synchronized (mPackagesLock) {
3359 final UserData userData;
3360 synchronized (mUsersLock) {
3361 userData = getUserDataLU(userId);
3362 if (userData == null) {
3363 Slog.e(LOG_TAG, "No such user for settings seed data u=" + userId);
3364 return;
3365 }
3366 userData.seedAccountName = accountName;
3367 userData.seedAccountType = accountType;
3368 userData.seedAccountOptions = accountOptions;
3369 userData.persistSeedData = persist;
3370 }
3371 if (persist) {
3372 writeUserLP(userData);
3373 }
3374 }
3375 }
3376
3377 @Override
3378 public String getSeedAccountName() throws RemoteException {
3379 checkManageUsersPermission("Cannot get seed account information");
3380 synchronized (mUsersLock) {
3381 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3382 return userData.seedAccountName;
3383 }
3384 }
3385
3386 @Override
3387 public String getSeedAccountType() throws RemoteException {
3388 checkManageUsersPermission("Cannot get seed account information");
3389 synchronized (mUsersLock) {
3390 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3391 return userData.seedAccountType;
3392 }
3393 }
3394
3395 @Override
3396 public PersistableBundle getSeedAccountOptions() throws RemoteException {
3397 checkManageUsersPermission("Cannot get seed account information");
3398 synchronized (mUsersLock) {
3399 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3400 return userData.seedAccountOptions;
3401 }
3402 }
3403
3404 @Override
3405 public void clearSeedAccountData() throws RemoteException {
3406 checkManageUsersPermission("Cannot clear seed account information");
3407 synchronized (mPackagesLock) {
3408 UserData userData;
3409 synchronized (mUsersLock) {
3410 userData = getUserDataLU(UserHandle.getCallingUserId());
3411 if (userData == null) return;
3412 userData.clearSeedAccountData();
3413 }
3414 writeUserLP(userData);
3415 }
3416 }
3417
3418 @Override
3419 public boolean someUserHasSeedAccount(String accountName, String accountType)
3420 throws RemoteException {
3421 checkManageUsersPermission("Cannot check seed account information");
3422 synchronized (mUsersLock) {
3423 final int userSize = mUsers.size();
3424 for (int i = 0; i < userSize; i++) {
3425 final UserData data = mUsers.valueAt(i);
3426 if (data.info.isInitialized()) continue;
3427 if (data.seedAccountName == null || !data.seedAccountName.equals(accountName)) {
3428 continue;
3429 }
3430 if (data.seedAccountType == null || !data.seedAccountType.equals(accountType)) {
3431 continue;
3432 }
3433 return true;
3434 }
3435 }
3436 return false;
3437 }
3438
3439 @Override
Todd Kennedy60459ab2015-10-30 11:32:16 -07003440 public void onShellCommand(FileDescriptor in, FileDescriptor out,
Dianne Hackborn354736e2016-08-22 17:00:05 -07003441 FileDescriptor err, String[] args, ShellCallback callback,
3442 ResultReceiver resultReceiver) {
3443 (new Shell()).exec(this, in, out, err, args, callback, resultReceiver);
Todd Kennedy60459ab2015-10-30 11:32:16 -07003444 }
3445
3446 int onShellCommand(Shell shell, String cmd) {
3447 if (cmd == null) {
3448 return shell.handleDefaultCommands(cmd);
3449 }
3450
3451 final PrintWriter pw = shell.getOutPrintWriter();
3452 try {
3453 switch(cmd) {
3454 case "list":
3455 return runList(pw);
3456 }
3457 } catch (RemoteException e) {
3458 pw.println("Remote exception: " + e);
3459 }
3460 return -1;
3461 }
3462
3463 private int runList(PrintWriter pw) throws RemoteException {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003464 final IActivityManager am = ActivityManager.getService();
Todd Kennedy60459ab2015-10-30 11:32:16 -07003465 final List<UserInfo> users = getUsers(false);
3466 if (users == null) {
3467 pw.println("Error: couldn't get users");
3468 return 1;
3469 } else {
3470 pw.println("Users:");
3471 for (int i = 0; i < users.size(); i++) {
Jeff Sharkeye17ac152015-11-06 22:40:29 -08003472 String running = am.isUserRunning(users.get(i).id, 0) ? " running" : "";
Todd Kennedy60459ab2015-10-30 11:32:16 -07003473 pw.println("\t" + users.get(i).toString() + running);
3474 }
3475 return 0;
3476 }
3477 }
3478
3479 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -07003480 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06003481 if (!DumpUtils.checkDumpPermission(mContext, LOG_TAG, pw)) return;
Amith Yamasani920ace02012-09-20 22:15:37 -07003482
3483 long now = System.currentTimeMillis();
3484 StringBuilder sb = new StringBuilder();
3485 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003486 synchronized (mUsersLock) {
3487 pw.println("Users:");
3488 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003489 UserData userData = mUsers.valueAt(i);
3490 if (userData == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003491 continue;
3492 }
Amith Yamasani12747872015-12-07 14:19:49 -08003493 UserInfo userInfo = userData.info;
3494 final int userId = userInfo.id;
3495 pw.print(" "); pw.print(userInfo);
3496 pw.print(" serialNo="); pw.print(userInfo.serialNumber);
Makoto Onukie7927da2015-11-25 10:05:17 -08003497 if (mRemovingUserIds.get(userId)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003498 pw.print(" <removing> ");
3499 }
Amith Yamasani12747872015-12-07 14:19:49 -08003500 if (userInfo.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003501 pw.print(" <partial>");
3502 }
3503 pw.println();
Makoto Onuki88aef752017-03-29 16:52:03 -07003504 pw.print(" State: ");
3505 final int state;
3506 synchronized (mUserStates) {
3507 state = mUserStates.get(userId, -1);
3508 }
3509 pw.println(UserState.stateToString(state));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003510 pw.print(" Created: ");
Amith Yamasani12747872015-12-07 14:19:49 -08003511 if (userInfo.creationTime == 0) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003512 pw.println("<unknown>");
3513 } else {
3514 sb.setLength(0);
Amith Yamasani12747872015-12-07 14:19:49 -08003515 TimeUtils.formatDuration(now - userInfo.creationTime, sb);
Fyodor Kupolov82402752015-10-28 14:54:51 -07003516 sb.append(" ago");
3517 pw.println(sb);
3518 }
3519 pw.print(" Last logged in: ");
Amith Yamasani12747872015-12-07 14:19:49 -08003520 if (userInfo.lastLoggedInTime == 0) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003521 pw.println("<unknown>");
3522 } else {
3523 sb.setLength(0);
Amith Yamasani12747872015-12-07 14:19:49 -08003524 TimeUtils.formatDuration(now - userInfo.lastLoggedInTime, sb);
Fyodor Kupolov82402752015-10-28 14:54:51 -07003525 sb.append(" ago");
3526 pw.println(sb);
3527 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003528 pw.print(" Last logged in fingerprint: ");
3529 pw.println(userInfo.lastLoggedInFingerprint);
Makoto Onukie7927da2015-11-25 10:05:17 -08003530 pw.print(" Has profile owner: ");
3531 pw.println(mIsUserManaged.get(userId));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003532 pw.println(" Restrictions:");
3533 synchronized (mRestrictionsLock) {
3534 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003535 pw, " ", mBaseUserRestrictions.get(userInfo.id));
Pavel Grafov6a40f092016-10-25 15:46:51 +01003536 pw.println(" Device policy global restrictions:");
3537 UserRestrictionsUtils.dumpRestrictions(
3538 pw, " ", mDevicePolicyGlobalUserRestrictions.get(userInfo.id));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003539 pw.println(" Device policy local restrictions:");
3540 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003541 pw, " ", mDevicePolicyLocalUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003542 pw.println(" Effective restrictions:");
3543 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003544 pw, " ", mCachedEffectiveUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003545 }
Amith Yamasani12747872015-12-07 14:19:49 -08003546
3547 if (userData.account != null) {
3548 pw.print(" Account name: " + userData.account);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08003549 pw.println();
3550 }
Amith Yamasani12747872015-12-07 14:19:49 -08003551
3552 if (userData.seedAccountName != null) {
3553 pw.print(" Seed account name: " + userData.seedAccountName);
3554 pw.println();
3555 if (userData.seedAccountType != null) {
3556 pw.print(" account type: " + userData.seedAccountType);
3557 pw.println();
3558 }
3559 if (userData.seedAccountOptions != null) {
3560 pw.print(" account options exist");
3561 pw.println();
3562 }
3563 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003564 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003565 }
Amith Yamasani12747872015-12-07 14:19:49 -08003566 pw.println();
Pavel Grafov6a40f092016-10-25 15:46:51 +01003567 pw.println(" Device owner id:" + mDeviceOwnerUserId);
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01003568 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003569 pw.println(" Guest restrictions:");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003570 synchronized (mGuestRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003571 UserRestrictionsUtils.dumpRestrictions(pw, " ", mGuestRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003572 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003573 synchronized (mUsersLock) {
3574 pw.println();
3575 pw.println(" Device managed: " + mIsDeviceManaged);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003576 if (mRemovingUserIds.size() > 0) {
3577 pw.println();
3578 pw.println(" Recently removed userIds: " + mRecentlyRemovedIds);
3579 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003580 }
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003581 synchronized (mUserStates) {
3582 pw.println(" Started users state: " + mUserStates);
3583 }
Amith Yamasani12747872015-12-07 14:19:49 -08003584 // Dump some capabilities
3585 pw.println();
3586 pw.println(" Max users: " + UserManager.getMaxSupportedUsers());
3587 pw.println(" Supports switchable users: " + UserManager.supportsMultipleUsers());
Lenka Trochtova02fee152015-12-22 14:26:18 +01003588 pw.println(" All guests ephemeral: " + Resources.getSystem().getBoolean(
3589 com.android.internal.R.bool.config_guestUserEphemeral));
Amith Yamasani920ace02012-09-20 22:15:37 -07003590 }
3591 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08003592
3593 final class MainHandler extends Handler {
3594
3595 @Override
3596 public void handleMessage(Message msg) {
3597 switch (msg.what) {
3598 case WRITE_USER_MSG:
3599 removeMessages(WRITE_USER_MSG, msg.obj);
3600 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08003601 int userId = ((UserData) msg.obj).info.id;
3602 UserData userData = getUserDataNoChecks(userId);
3603 if (userData != null) {
3604 writeUserLP(userData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08003605 }
3606 }
3607 }
3608 }
3609 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07003610
3611 /**
3612 * @param userId
3613 * @return whether the user has been initialized yet
3614 */
Todd Kennedy0eb97382017-10-03 16:57:22 -07003615 boolean isUserInitialized(int userId) {
3616 return mLocalService.isUserInitialized(userId);
Amith Yamasanibb054c92015-07-09 14:16:27 -07003617 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003618
3619 private class LocalService extends UserManagerInternal {
Makoto Onuki068c54a2015-10-13 14:34:03 -07003620 @Override
Pavel Grafov6a40f092016-10-25 15:46:51 +01003621 public void setDevicePolicyUserRestrictions(int userId, @Nullable Bundle restrictions,
3622 boolean isDeviceOwner, int cameraRestrictionScope) {
3623 UserManagerService.this.setDevicePolicyUserRestrictionsInner(userId, restrictions,
3624 isDeviceOwner, cameraRestrictionScope);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003625 }
3626
3627 @Override
3628 public Bundle getBaseUserRestrictions(int userId) {
3629 synchronized (mRestrictionsLock) {
3630 return mBaseUserRestrictions.get(userId);
3631 }
3632 }
3633
3634 @Override
3635 public void setBaseUserRestrictionsByDpmsForMigration(
3636 int userId, Bundle baseRestrictions) {
3637 synchronized (mRestrictionsLock) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01003638 if (updateRestrictionsIfNeededLR(
3639 userId, new Bundle(baseRestrictions), mBaseUserRestrictions)) {
3640 invalidateEffectiveUserRestrictionsLR(userId);
3641 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003642 }
3643
Amith Yamasani12747872015-12-07 14:19:49 -08003644 final UserData userData = getUserDataNoChecks(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003645 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08003646 if (userData != null) {
3647 writeUserLP(userData);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003648 } else {
3649 Slog.w(LOG_TAG, "UserInfo not found for " + userId);
3650 }
3651 }
3652 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08003653
3654 @Override
3655 public boolean getUserRestriction(int userId, String key) {
3656 return getUserRestrictions(userId).getBoolean(key);
3657 }
3658
3659 @Override
3660 public void addUserRestrictionsListener(UserRestrictionsListener listener) {
3661 synchronized (mUserRestrictionsListeners) {
3662 mUserRestrictionsListeners.add(listener);
3663 }
3664 }
3665
3666 @Override
3667 public void removeUserRestrictionsListener(UserRestrictionsListener listener) {
3668 synchronized (mUserRestrictionsListeners) {
3669 mUserRestrictionsListeners.remove(listener);
3670 }
3671 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003672
3673 @Override
3674 public void setDeviceManaged(boolean isManaged) {
3675 synchronized (mUsersLock) {
3676 mIsDeviceManaged = isManaged;
3677 }
3678 }
3679
3680 @Override
3681 public void setUserManaged(int userId, boolean isManaged) {
3682 synchronized (mUsersLock) {
3683 mIsUserManaged.put(userId, isManaged);
3684 }
3685 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01003686
3687 @Override
3688 public void setUserIcon(int userId, Bitmap bitmap) {
3689 long ident = Binder.clearCallingIdentity();
3690 try {
3691 synchronized (mPackagesLock) {
3692 UserData userData = getUserDataNoChecks(userId);
3693 if (userData == null || userData.info.partial) {
3694 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
3695 return;
3696 }
3697 writeBitmapLP(userData.info, bitmap);
3698 writeUserLP(userData);
3699 }
3700 sendUserInfoChangedBroadcast(userId);
3701 } finally {
3702 Binder.restoreCallingIdentity(ident);
3703 }
3704 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01003705
3706 @Override
3707 public void setForceEphemeralUsers(boolean forceEphemeralUsers) {
3708 synchronized (mUsersLock) {
3709 mForceEphemeralUsers = forceEphemeralUsers;
3710 }
3711 }
3712
3713 @Override
3714 public void removeAllUsers() {
3715 if (UserHandle.USER_SYSTEM == ActivityManager.getCurrentUser()) {
3716 // Remove the non-system users straight away.
3717 removeNonSystemUsers();
3718 } else {
3719 // Switch to the system user first and then remove the other users.
3720 BroadcastReceiver userSwitchedReceiver = new BroadcastReceiver() {
3721 @Override
3722 public void onReceive(Context context, Intent intent) {
3723 int userId =
3724 intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3725 if (userId != UserHandle.USER_SYSTEM) {
3726 return;
3727 }
3728 mContext.unregisterReceiver(this);
3729 removeNonSystemUsers();
3730 }
3731 };
3732 IntentFilter userSwitchedFilter = new IntentFilter();
3733 userSwitchedFilter.addAction(Intent.ACTION_USER_SWITCHED);
3734 mContext.registerReceiver(
3735 userSwitchedReceiver, userSwitchedFilter, null, mHandler);
3736
3737 // Switch to the system user.
3738 ActivityManager am =
3739 (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
3740 am.switchUser(UserHandle.USER_SYSTEM);
3741 }
3742 }
phweisse9c44062016-02-10 12:57:38 +01003743
3744 @Override
Lenka Trochtova1ddda472016-02-12 10:42:12 +01003745 public void onEphemeralUserStop(int userId) {
3746 synchronized (mUsersLock) {
3747 UserInfo userInfo = getUserInfoLU(userId);
3748 if (userInfo != null && userInfo.isEphemeral()) {
3749 // Do not allow switching back to the ephemeral user again as the user is going
3750 // to be deleted.
3751 userInfo.flags |= UserInfo.FLAG_DISABLED;
3752 if (userInfo.isGuest()) {
3753 // Indicate that the guest will be deleted after it stops.
3754 userInfo.guestToRemove = true;
3755 }
3756 }
3757 }
3758 }
3759
3760 @Override
Alex Chaub6a9f942017-11-07 11:28:56 +08003761 public UserInfo createUserEvenWhenDisallowed(String name, int flags,
3762 String[] disallowedPackages) {
3763 UserInfo user = createUserInternalUnchecked(name, flags, UserHandle.USER_NULL,
3764 disallowedPackages);
phweisse9c44062016-02-10 12:57:38 +01003765 // Keep this in sync with UserManager.createUser
Christine Franks97a54802017-08-09 10:06:43 -07003766 if (user != null && !user.isAdmin() && !user.isDemo()) {
phweisse9c44062016-02-10 12:57:38 +01003767 setUserRestriction(UserManager.DISALLOW_SMS, true, user.id);
3768 setUserRestriction(UserManager.DISALLOW_OUTGOING_CALLS, true, user.id);
3769 }
3770 return user;
3771 }
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003772
3773 @Override
Nicolas Prevotdf1b87d2016-10-25 13:57:08 +01003774 public boolean removeUserEvenWhenDisallowed(int userId) {
3775 return removeUserUnchecked(userId);
3776 }
3777
3778 @Override
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003779 public boolean isUserRunning(int userId) {
3780 synchronized (mUserStates) {
3781 return mUserStates.get(userId, -1) >= 0;
3782 }
3783 }
3784
3785 @Override
3786 public void setUserState(int userId, int userState) {
3787 synchronized (mUserStates) {
3788 mUserStates.put(userId, userState);
3789 }
3790 }
3791
3792 @Override
3793 public void removeUserState(int userId) {
3794 synchronized (mUserStates) {
3795 mUserStates.delete(userId);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003796 }
3797 }
3798
3799 @Override
Michael Wachenschwanz3f2b6552017-05-15 13:53:09 -07003800 public int[] getUserIds() {
3801 return UserManagerService.this.getUserIds();
3802 }
3803
3804 @Override
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003805 public boolean isUserUnlockingOrUnlocked(int userId) {
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07003806 int state;
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003807 synchronized (mUserStates) {
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07003808 state = mUserStates.get(userId, -1);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003809 }
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07003810 // Special case, in the stopping/shutdown state user key can still be unlocked
3811 if (state == UserState.STATE_STOPPING || state == UserState.STATE_SHUTDOWN) {
3812 return StorageManager.isUserKeyUnlocked(userId);
3813 }
3814 return (state == UserState.STATE_RUNNING_UNLOCKING)
3815 || (state == UserState.STATE_RUNNING_UNLOCKED);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003816 }
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08003817
3818 @Override
3819 public boolean isUserUnlocked(int userId) {
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07003820 int state;
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08003821 synchronized (mUserStates) {
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07003822 state = mUserStates.get(userId, -1);
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08003823 }
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07003824 // Special case, in the stopping/shutdown state user key can still be unlocked
3825 if (state == UserState.STATE_STOPPING || state == UserState.STATE_SHUTDOWN) {
3826 return StorageManager.isUserKeyUnlocked(userId);
3827 }
3828 return state == UserState.STATE_RUNNING_UNLOCKED;
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08003829 }
Todd Kennedy0eb97382017-10-03 16:57:22 -07003830
3831 @Override
3832 public boolean isUserInitialized(int userId) {
3833 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
3834 }
3835
3836 @Override
3837 public boolean exists(int userId) {
3838 return getUserInfoNoChecks(userId) != null;
3839 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01003840 }
3841
3842 /* Remove all the users except of the system one. */
3843 private void removeNonSystemUsers() {
3844 ArrayList<UserInfo> usersToRemove = new ArrayList<>();
3845 synchronized (mUsersLock) {
3846 final int userSize = mUsers.size();
3847 for (int i = 0; i < userSize; i++) {
3848 UserInfo ui = mUsers.valueAt(i).info;
3849 if (ui.id != UserHandle.USER_SYSTEM) {
3850 usersToRemove.add(ui);
3851 }
3852 }
3853 }
3854 for (UserInfo ui: usersToRemove) {
3855 removeUser(ui.id);
3856 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003857 }
Todd Kennedy60459ab2015-10-30 11:32:16 -07003858
3859 private class Shell extends ShellCommand {
3860 @Override
3861 public int onCommand(String cmd) {
3862 return onShellCommand(this, cmd);
3863 }
3864
3865 @Override
3866 public void onHelp() {
3867 final PrintWriter pw = getOutPrintWriter();
3868 pw.println("User manager (user) commands:");
3869 pw.println(" help");
3870 pw.println(" Print this help text.");
3871 pw.println("");
3872 pw.println(" list");
3873 pw.println(" Prints all users on the system.");
3874 }
3875 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003876
3877 private static void debug(String message) {
3878 Log.d(LOG_TAG, message +
3879 (DBG_WITH_STACKTRACE ? " called at\n" + Debug.getCallers(10, " ") : ""));
3880 }
Kenny Guy02c89902016-11-15 19:36:38 +00003881
3882 @VisibleForTesting
3883 static int getMaxManagedProfiles() {
3884 // Allow overriding max managed profiles on debuggable builds for testing
3885 // of multiple profiles.
3886 if (!Build.IS_DEBUGGABLE) {
3887 return MAX_MANAGED_PROFILES;
3888 } else {
3889 return SystemProperties.getInt("persist.sys.max_profiles",
3890 MAX_MANAGED_PROFILES);
3891 }
3892 }
3893
3894 @VisibleForTesting
3895 int getFreeProfileBadgeLU(int parentUserId) {
3896 int maxManagedProfiles = getMaxManagedProfiles();
3897 boolean[] usedBadges = new boolean[maxManagedProfiles];
3898 final int userSize = mUsers.size();
3899 for (int i = 0; i < userSize; i++) {
3900 UserInfo ui = mUsers.valueAt(i).info;
3901 // Check which badge indexes are already used by this profile group.
3902 if (ui.isManagedProfile()
3903 && ui.profileGroupId == parentUserId
3904 && !mRemovingUserIds.get(ui.id)
3905 && ui.profileBadge < maxManagedProfiles) {
3906 usedBadges[ui.profileBadge] = true;
3907 }
3908 }
3909 for (int i = 0; i < maxManagedProfiles; i++) {
3910 if (!usedBadges[i]) {
3911 return i;
3912 }
3913 }
3914 return 0;
3915 }
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07003916
3917 /**
3918 * Checks if the given user has a managed profile associated with it.
3919 * @param userId The parent user
3920 * @return
3921 */
3922 boolean hasManagedProfile(int userId) {
3923 synchronized (mUsersLock) {
3924 UserInfo userInfo = getUserInfoLU(userId);
3925 final int userSize = mUsers.size();
3926 for (int i = 0; i < userSize; i++) {
3927 UserInfo profile = mUsers.valueAt(i).info;
3928 if (userId != profile.id && isProfileOf(userInfo, profile)) {
3929 return true;
3930 }
3931 }
3932 return false;
3933 }
3934 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003935}