blob: c3dce313302660cfa73a52a13c666dd44e19fe4f [file] [log] [blame]
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
Benjamin Franzf02420c2016-04-04 18:52:21 +010019import static android.content.Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS;
20import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
21
Xiaohui Chenb3b92582015-12-07 11:22:13 -080022import android.Manifest;
Xiaohui Chen594f2082015-08-18 11:04:20 -070023import android.annotation.NonNull;
Makoto Onuki068c54a2015-10-13 14:34:03 -070024import android.annotation.Nullable;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -060025import android.annotation.UserIdInt;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070026import android.app.Activity;
Amith Yamasani2a003292012-08-14 18:25:45 -070027import android.app.ActivityManager;
Amith Yamasani515d4062015-09-28 11:30:06 -070028import android.app.ActivityManagerInternal;
Andrew Scull85a63bc2016-10-24 13:47:47 +010029import android.app.ActivityManagerNative;
Todd Kennedy60459ab2015-10-30 11:32:16 -070030import android.app.IActivityManager;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070031import android.app.IStopUserCallback;
Benjamin Franzf02420c2016-04-04 18:52:21 +010032import android.app.KeyguardManager;
Ricky Waib1dd80b2016-06-07 18:00:55 +010033import android.app.PendingIntent;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070034import android.content.BroadcastReceiver;
Amith Yamasani258848d2012-08-10 17:06:33 -070035import android.content.Context;
36import android.content.Intent;
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +010037import android.content.IntentFilter;
Benjamin Franzf02420c2016-04-04 18:52:21 +010038import android.content.IntentSender;
Amith Yamasani0b285492011-04-14 17:35:23 -070039import android.content.pm.PackageManager;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -080040import android.content.pm.PackageManager.NameNotFoundException;
Tony Make3d1f652017-12-12 11:00:37 +000041import android.content.pm.ShortcutServiceInternal;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070042import android.content.pm.UserInfo;
Lenka Trochtova02fee152015-12-22 14:26:18 +010043import android.content.res.Resources;
Amith Yamasanie928d7d2012-09-17 21:46:51 -070044import android.graphics.Bitmap;
Amith Yamasani258848d2012-08-10 17:06:33 -070045import android.os.Binder;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -060046import android.os.Build;
Amith Yamasanie4cf7342012-12-17 11:12:09 -080047import android.os.Bundle;
Makoto Onuki1a2cd742015-11-16 13:51:27 -080048import android.os.Debug;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070049import android.os.Environment;
50import android.os.FileUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080051import android.os.Handler;
Svet Ganov9cea80cd2016-02-16 11:47:00 -080052import android.os.IBinder;
Tony Mak64fd8c02017-12-01 19:11:59 +000053import android.os.IProgressListener;
Amith Yamasani258848d2012-08-10 17:06:33 -070054import android.os.IUserManager;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -080055import android.os.Message;
Adrian Roos1bdff912015-02-17 15:51:35 +010056import android.os.ParcelFileDescriptor;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070057import android.os.Parcelable;
Amith Yamasani12747872015-12-07 14:19:49 -080058import android.os.PersistableBundle;
Amith Yamasani258848d2012-08-10 17:06:33 -070059import android.os.Process;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070060import android.os.RemoteException;
Todd Kennedy60459ab2015-10-30 11:32:16 -070061import android.os.ResultReceiver;
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +010062import android.os.SELinux;
Jason Monk62062992014-05-06 09:55:28 -040063import android.os.ServiceManager;
Dianne Hackborn354736e2016-08-22 17:00:05 -070064import android.os.ShellCallback;
Todd Kennedy60459ab2015-10-30 11:32:16 -070065import android.os.ShellCommand;
Kenny Guy02c89902016-11-15 19:36:38 +000066import android.os.SystemProperties;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070067import android.os.UserHandle;
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070068import android.os.UserManager;
Pavel Grafov6a40f092016-10-25 15:46:51 +010069import android.os.UserManager.EnforcingUser;
Makoto Onuki068c54a2015-10-13 14:34:03 -070070import android.os.UserManagerInternal;
Makoto Onukid45a4a22015-11-02 17:17:38 -080071import android.os.UserManagerInternal.UserRestrictionsListener;
Paul Crowley85e4e812015-05-19 12:42:00 +010072import android.os.storage.StorageManager;
Amith Yamasanid04aaa32016-06-13 12:09:36 -070073import android.security.GateKeeper;
74import android.service.gatekeeper.IGateKeeperService;
Amith Yamasani2a003292012-08-14 18:25:45 -070075import android.util.AtomicFile;
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -070076import android.util.IntArray;
Amith Yamasani655d0e22013-06-12 14:19:10 -070077import android.util.Log;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070078import android.util.Slog;
79import android.util.SparseArray;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080080import android.util.SparseBooleanArray;
Amith Yamasaniea1b9d72016-05-27 15:57:38 +000081import android.util.SparseIntArray;
Amith Yamasani920ace02012-09-20 22:15:37 -070082import android.util.TimeUtils;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070083import android.util.Xml;
84
Makoto Onuki068c54a2015-10-13 14:34:03 -070085import com.android.internal.annotations.GuardedBy;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070086import com.android.internal.annotations.VisibleForTesting;
Jason Monk62062992014-05-06 09:55:28 -040087import com.android.internal.app.IAppOpsService;
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -080088import com.android.internal.logging.MetricsLogger;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -060089import com.android.internal.util.DumpUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080090import com.android.internal.util.FastXmlSerializer;
Makoto Onuki068c54a2015-10-13 14:34:03 -070091import com.android.internal.util.Preconditions;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070092import com.android.internal.util.XmlUtils;
Clara Bayarri10ad84a2015-12-01 17:38:05 +000093import com.android.internal.widget.LockPatternUtils;
Amith Yamasani515d4062015-09-28 11:30:06 -070094import com.android.server.LocalServices;
Jeff Sharkey5f3e9342017-03-13 14:53:11 -060095import com.android.server.LockGuard;
Amith Yamasanid04aaa32016-06-13 12:09:36 -070096import com.android.server.SystemService;
Amith Yamasaniea1b9d72016-05-27 15:57:38 +000097import com.android.server.am.UserState;
Suprabh Shuklac5e057c2016-08-08 16:22:44 -070098import com.android.server.storage.DeviceStorageMonitorInternal;
Tony Mak6dc428f2016-10-10 15:48:27 +010099
Jeff Sharkey47f71082016-02-01 17:03:54 -0700100import libcore.io.IoUtils;
101import libcore.util.Objects;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800102
103import org.xmlpull.v1.XmlPullParser;
104import org.xmlpull.v1.XmlPullParserException;
105import org.xmlpull.v1.XmlSerializer;
106
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700107import java.io.BufferedOutputStream;
108import java.io.File;
Amith Yamasani920ace02012-09-20 22:15:37 -0700109import java.io.FileDescriptor;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700110import java.io.FileInputStream;
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700111import java.io.FileNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700112import java.io.FileOutputStream;
Tony Mak64fd8c02017-12-01 19:11:59 +0000113import java.io.IOException;
Kenny Guy02c89902016-11-15 19:36:38 +0000114import java.io.InputStream;
115import java.io.OutputStream;
Amith Yamasani920ace02012-09-20 22:15:37 -0700116import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100117import java.nio.charset.StandardCharsets;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700118import java.util.ArrayList;
Pavel Grafov6a40f092016-10-25 15:46:51 +0100119import java.util.Collections;
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700120import java.util.LinkedList;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700121import java.util.List;
122
Makoto Onuki068c54a2015-10-13 14:34:03 -0700123/**
124 * Service for {@link UserManager}.
125 *
126 * Method naming convention:
Fyodor Kupolov82402752015-10-28 14:54:51 -0700127 * <ul>
Fyodor Kupolovd31cee92017-09-05 16:31:08 -0700128 * <li> Methods suffixed with "LAr" should be called within the {@link #mAppRestrictionsLock} lock.
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800129 * <li> Methods suffixed with "LP" should be called within the {@link #mPackagesLock} lock.
Fyodor Kupolov82402752015-10-28 14:54:51 -0700130 * <li> Methods suffixed with "LR" should be called within the {@link #mRestrictionsLock} lock.
131 * <li> Methods suffixed with "LU" should be called within the {@link #mUsersLock} lock.
132 * </ul>
Makoto Onuki068c54a2015-10-13 14:34:03 -0700133 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700134public class UserManagerService extends IUserManager.Stub {
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700135
Amith Yamasani2a003292012-08-14 18:25:45 -0700136 private static final String LOG_TAG = "UserManagerService";
Makoto Onuki81c61ea2016-01-22 11:22:26 -0800137 static final boolean DBG = false; // DO NOT SUBMIT WITH TRUE
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800138 private static final boolean DBG_WITH_STACKTRACE = false; // DO NOT SUBMIT WITH TRUE
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700139 // Can be used for manual testing of id recycling
140 private static final boolean RELEASE_DELETED_USER_ID = false; // DO NOT SUBMIT WITH TRUE
Amith Yamasani16389312012-10-17 21:20:14 -0700141
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700142 private static final String TAG_NAME = "name";
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800143 private static final String TAG_ACCOUNT = "account";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700144 private static final String ATTR_FLAGS = "flags";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700145 private static final String ATTR_ICON_PATH = "icon";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700146 private static final String ATTR_ID = "id";
Amith Yamasani920ace02012-09-20 22:15:37 -0700147 private static final String ATTR_CREATION_TIME = "created";
148 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -0600149 private static final String ATTR_LAST_LOGGED_IN_FINGERPRINT = "lastLoggedInFingerprint";
Amith Yamasani2a003292012-08-14 18:25:45 -0700150 private static final String ATTR_SERIAL_NO = "serialNumber";
151 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700152 private static final String ATTR_PARTIAL = "partial";
Adam Lesinskieddeb492014-09-08 17:50:03 -0700153 private static final String ATTR_GUEST_TO_REMOVE = "guestToRemove";
Amith Yamasani6f34b412012-10-22 18:19:27 -0700154 private static final String ATTR_USER_VERSION = "version";
Kenny Guy2a764942014-04-02 13:29:20 +0100155 private static final String ATTR_PROFILE_GROUP_ID = "profileGroupId";
Kenny Guy02c89902016-11-15 19:36:38 +0000156 private static final String ATTR_PROFILE_BADGE = "profileBadge";
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700157 private static final String ATTR_RESTRICTED_PROFILE_PARENT_ID = "restrictedProfileParentId";
Amith Yamasani12747872015-12-07 14:19:49 -0800158 private static final String ATTR_SEED_ACCOUNT_NAME = "seedAccountName";
159 private static final String ATTR_SEED_ACCOUNT_TYPE = "seedAccountType";
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530160 private static final String TAG_GUEST_RESTRICTIONS = "guestRestrictions";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700161 private static final String TAG_USERS = "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700162 private static final String TAG_USER = "user";
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800163 private static final String TAG_RESTRICTIONS = "restrictions";
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800164 private static final String TAG_DEVICE_POLICY_RESTRICTIONS = "device_policy_restrictions";
Pavel Grafov6a40f092016-10-25 15:46:51 +0100165 private static final String TAG_DEVICE_POLICY_GLOBAL_RESTRICTIONS =
166 "device_policy_global_restrictions";
167 /** Legacy name for device owner id tag. */
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +0100168 private static final String TAG_GLOBAL_RESTRICTION_OWNER_ID = "globalRestrictionOwnerUserId";
Pavel Grafov6a40f092016-10-25 15:46:51 +0100169 private static final String TAG_DEVICE_OWNER_USER_ID = "deviceOwnerUserId";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800170 private static final String TAG_ENTRY = "entry";
171 private static final String TAG_VALUE = "value";
Amith Yamasani12747872015-12-07 14:19:49 -0800172 private static final String TAG_SEED_ACCOUNT_OPTIONS = "seedAccountOptions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800173 private static final String ATTR_KEY = "key";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700174 private static final String ATTR_VALUE_TYPE = "type";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800175 private static final String ATTR_MULTIPLE = "m";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700176
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700177 private static final String ATTR_TYPE_STRING_ARRAY = "sa";
178 private static final String ATTR_TYPE_STRING = "s";
179 private static final String ATTR_TYPE_BOOLEAN = "b";
Amith Yamasani5b5aa402014-06-01 20:10:14 -0700180 private static final String ATTR_TYPE_INTEGER = "i";
Fyodor Kupolov262f9952015-03-23 18:55:11 -0700181 private static final String ATTR_TYPE_BUNDLE = "B";
182 private static final String ATTR_TYPE_BUNDLE_ARRAY = "BA";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700183
Amith Yamasani0b285492011-04-14 17:35:23 -0700184 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700185 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700186 private static final String USER_PHOTO_FILENAME = "photo.png";
Adrian Roos1bdff912015-02-17 15:51:35 +0100187 private static final String USER_PHOTO_FILENAME_TMP = USER_PHOTO_FILENAME + ".tmp";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700188
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800189 private static final String RESTRICTIONS_FILE_PREFIX = "res_";
Amith Yamasanifc95e702013-09-26 13:20:17 -0700190 private static final String XML_SUFFIX = ".xml";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800191
Sudheer Shankaf5cea032016-06-08 17:13:24 -0700192 private static final int ALLOWED_FLAGS_FOR_CREATE_USERS_PERMISSION =
193 UserInfo.FLAG_MANAGED_PROFILE
194 | UserInfo.FLAG_EPHEMERAL
195 | UserInfo.FLAG_RESTRICTED
Sudheer Shanka234d1af2016-08-26 15:42:53 -0700196 | UserInfo.FLAG_GUEST
197 | UserInfo.FLAG_DEMO;
Sudheer Shankaf5cea032016-06-08 17:13:24 -0700198
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700199 @VisibleForTesting
200 static final int MIN_USER_ID = 10;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700201 // We need to keep process uid within Integer.MAX_VALUE.
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700202 @VisibleForTesting
203 static final int MAX_USER_ID = Integer.MAX_VALUE / UserHandle.PER_USER_RANGE;
204
205 // Max size of the queue of recently removed users
206 @VisibleForTesting
207 static final int MAX_RECENTLY_REMOVED_IDS_SIZE = 100;
Amith Yamasani634cf312012-10-04 17:34:21 -0700208
Pavel Grafov6a40f092016-10-25 15:46:51 +0100209 private static final int USER_VERSION = 7;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700210
Amith Yamasani920ace02012-09-20 22:15:37 -0700211 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
212
Nicolas Prevotb8186812015-08-06 15:00:03 +0100213 // Maximum number of managed profiles permitted per user is 1. This cannot be increased
Amith Yamasani95ab7842014-08-11 17:09:26 -0700214 // without first making sure that the rest of the framework is prepared for it.
Kenny Guy02c89902016-11-15 19:36:38 +0000215 @VisibleForTesting
216 static final int MAX_MANAGED_PROFILES = 1;
Amith Yamasani95ab7842014-08-11 17:09:26 -0700217
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800218 static final int WRITE_USER_MSG = 1;
219 static final int WRITE_USER_DELAY = 2*1000; // 2 seconds
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530220
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -0800221 // Tron counters
222 private static final String TRON_GUEST_CREATED = "users_guest_created";
223 private static final String TRON_USER_CREATED = "users_user_created";
Christine Franks88220562017-05-24 11:11:21 -0700224 private static final String TRON_DEMO_CREATED = "users_demo_created";
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -0800225
Dianne Hackborn4428e172012-08-24 17:43:05 -0700226 private final Context mContext;
227 private final PackageManagerService mPm;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700228 private final Object mPackagesLock;
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800229 private final UserDataPreparer mUserDataPreparer;
Fyodor Kupolov82402752015-10-28 14:54:51 -0700230 // Short-term lock for internal state, when interaction/sync with PM is not required
Jeff Sharkey5f3e9342017-03-13 14:53:11 -0600231 private final Object mUsersLock = LockGuard.installNewLock(LockGuard.INDEX_USER);
Fyodor Kupolov82402752015-10-28 14:54:51 -0700232 private final Object mRestrictionsLock = new Object();
Fyodor Kupolovd31cee92017-09-05 16:31:08 -0700233 // Used for serializing access to app restriction files
234 private final Object mAppRestrictionsLock = new Object();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700235
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800236 private final Handler mHandler;
237
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700238 private final File mUsersDir;
239 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700240
Svet Ganov9cea80cd2016-02-16 11:47:00 -0800241 private static final IBinder mUserRestriconToken = new Binder();
242
Makoto Onuki068c54a2015-10-13 14:34:03 -0700243 /**
Amith Yamasani12747872015-12-07 14:19:49 -0800244 * User-related information that is used for persisting to flash. Only UserInfo is
245 * directly exposed to other system apps.
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800246 */
Kenny Guy02c89902016-11-15 19:36:38 +0000247 @VisibleForTesting
248 static class UserData {
Amith Yamasani12747872015-12-07 14:19:49 -0800249 // Basic user information and properties
250 UserInfo info;
251 // Account name used when there is a strong association between a user and an account
252 String account;
253 // Account information for seeding into a newly created user. This could also be
254 // used for login validation for an existing user, for updating their credentials.
255 // In the latter case, data may not need to be persisted as it is only valid for the
256 // current login session.
257 String seedAccountName;
258 String seedAccountType;
259 PersistableBundle seedAccountOptions;
260 // Whether to perist the seed account information to be available after a boot
261 boolean persistSeedData;
262
263 void clearSeedAccountData() {
264 seedAccountName = null;
265 seedAccountType = null;
266 seedAccountOptions = null;
267 persistSeedData = false;
268 }
269 }
270
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800271 @GuardedBy("mUsersLock")
Amith Yamasani12747872015-12-07 14:19:49 -0800272 private final SparseArray<UserData> mUsers = new SparseArray<>();
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800273
274 /**
Makoto Onuki068c54a2015-10-13 14:34:03 -0700275 * User restrictions set via UserManager. This doesn't include restrictions set by
Pavel Grafov6a40f092016-10-25 15:46:51 +0100276 * device owner / profile owners. Only non-empty restriction bundles are stored.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700277 *
278 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
279 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
280 * maybe shared between {@link #mBaseUserRestrictions} and
281 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
282 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700283 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700284 */
285 @GuardedBy("mRestrictionsLock")
286 private final SparseArray<Bundle> mBaseUserRestrictions = new SparseArray<>();
287
288 /**
289 * Cached user restrictions that are in effect -- i.e. {@link #mBaseUserRestrictions} combined
290 * with device / profile owner restrictions. We'll initialize it lazily; use
291 * {@link #getEffectiveUserRestrictions} to access it.
292 *
293 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
294 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
295 * maybe shared between {@link #mBaseUserRestrictions} and
296 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
297 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700298 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700299 */
300 @GuardedBy("mRestrictionsLock")
301 private final SparseArray<Bundle> mCachedEffectiveUserRestrictions = new SparseArray<>();
302
Makoto Onuki4f160732015-10-27 17:15:38 -0700303 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800304 * User restrictions that have already been applied in
305 * {@link #updateUserRestrictionsInternalLR(Bundle, int)}. We use it to detect restrictions
306 * that have changed since the last
307 * {@link #updateUserRestrictionsInternalLR(Bundle, int)} call.
Makoto Onuki4f160732015-10-27 17:15:38 -0700308 */
309 @GuardedBy("mRestrictionsLock")
310 private final SparseArray<Bundle> mAppliedUserRestrictions = new SparseArray<>();
311
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800312 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800313 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
Pavel Grafov6a40f092016-10-25 15:46:51 +0100314 * that should be applied to all users, including guests. Only non-empty restriction bundles are
315 * stored.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800316 */
317 @GuardedBy("mRestrictionsLock")
Pavel Grafov6a40f092016-10-25 15:46:51 +0100318 private final SparseArray<Bundle> mDevicePolicyGlobalUserRestrictions = new SparseArray<>();
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800319
320 /**
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +0100321 * Id of the user that set global restrictions.
322 */
323 @GuardedBy("mRestrictionsLock")
Pavel Grafov6a40f092016-10-25 15:46:51 +0100324 private int mDeviceOwnerUserId = UserHandle.USER_NULL;
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +0100325
326 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800327 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
Pavel Grafov6a40f092016-10-25 15:46:51 +0100328 * for each user. Only non-empty restriction bundles are stored.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800329 */
330 @GuardedBy("mRestrictionsLock")
331 private final SparseArray<Bundle> mDevicePolicyLocalUserRestrictions = new SparseArray<>();
332
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800333 @GuardedBy("mGuestRestrictions")
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530334 private final Bundle mGuestRestrictions = new Bundle();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800335
336 /**
337 * Set of user IDs being actively removed. Removed IDs linger in this set
338 * for several seconds to work around a VFS caching issue.
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700339 * Use {@link #addRemovingUserIdLocked(int)} to add elements to this array
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800340 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700341 @GuardedBy("mUsersLock")
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800342 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700343
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700344 /**
345 * Queue of recently removed userIds. Used for recycling of userIds
346 */
347 @GuardedBy("mUsersLock")
348 private final LinkedList<Integer> mRecentlyRemovedIds = new LinkedList<>();
349
Fyodor Kupolov82402752015-10-28 14:54:51 -0700350 @GuardedBy("mUsersLock")
Amith Yamasani0b285492011-04-14 17:35:23 -0700351 private int[] mUserIds;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800352 @GuardedBy("mPackagesLock")
Amith Yamasani2a003292012-08-14 18:25:45 -0700353 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700354 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700355
Jason Monk62062992014-05-06 09:55:28 -0400356 private IAppOpsService mAppOpsService;
357
Makoto Onuki068c54a2015-10-13 14:34:03 -0700358 private final LocalService mLocalService;
359
Makoto Onukie7927da2015-11-25 10:05:17 -0800360 @GuardedBy("mUsersLock")
361 private boolean mIsDeviceManaged;
362
363 @GuardedBy("mUsersLock")
364 private final SparseBooleanArray mIsUserManaged = new SparseBooleanArray();
365
Makoto Onukid45a4a22015-11-02 17:17:38 -0800366 @GuardedBy("mUserRestrictionsListeners")
367 private final ArrayList<UserRestrictionsListener> mUserRestrictionsListeners =
368 new ArrayList<>();
369
Clara Bayarria1771112015-12-18 16:29:18 +0000370 private final LockPatternUtils mLockPatternUtils;
371
Ricky Waib1dd80b2016-06-07 18:00:55 +0100372 private final String ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK =
373 "com.android.server.pm.DISABLE_QUIET_MODE_AFTER_UNLOCK";
374
375 private final BroadcastReceiver mDisableQuietModeCallback = new BroadcastReceiver() {
376 @Override
377 public void onReceive(Context context, Intent intent) {
Tony Mak64fd8c02017-12-01 19:11:59 +0000378 if (!ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK.equals(intent.getAction())) {
379 return;
Ricky Waib1dd80b2016-06-07 18:00:55 +0100380 }
Tony Mak64fd8c02017-12-01 19:11:59 +0000381 final IntentSender target = intent.getParcelableExtra(Intent.EXTRA_INTENT);
382 final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_ID, UserHandle.USER_NULL);
383 setQuietModeEnabled(userHandle, false, target);
Ricky Waib1dd80b2016-06-07 18:00:55 +0100384 }
385 };
386
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +0100387 /**
Tony Mak64fd8c02017-12-01 19:11:59 +0000388 * Start an {@link IntentSender} when user is unlocked after disabling quiet mode.
389 *
Tony Make3d1f652017-12-12 11:00:37 +0000390 * @see {@link #trySetQuietModeEnabled(String, boolean, int, IntentSender)}
Tony Mak64fd8c02017-12-01 19:11:59 +0000391 */
392 private class DisableQuietModeUserUnlockedCallback extends IProgressListener.Stub {
393 private final IntentSender mTarget;
394
395 public DisableQuietModeUserUnlockedCallback(IntentSender target) {
396 Preconditions.checkNotNull(target);
397 mTarget = target;
398 }
399
400 @Override
401 public void onStarted(int id, Bundle extras) {}
402
403 @Override
404 public void onProgress(int id, int progress, Bundle extras) {}
405
406 @Override
407 public void onFinished(int id, Bundle extras) {
408 try {
409 mContext.startIntentSender(mTarget, null, 0, 0, 0);
410 } catch (IntentSender.SendIntentException e) {
411 Slog.e(LOG_TAG, "Failed to start the target in the callback", e);
412 }
413 }
414 }
415
416 /**
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +0100417 * Whether all users should be created ephemeral.
418 */
419 @GuardedBy("mUsersLock")
420 private boolean mForceEphemeralUsers;
421
Amith Yamasaniea1b9d72016-05-27 15:57:38 +0000422 @GuardedBy("mUserStates")
423 private final SparseIntArray mUserStates = new SparseIntArray();
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -0700424
Amith Yamasani258848d2012-08-10 17:06:33 -0700425 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700426
Dianne Hackborn4428e172012-08-24 17:43:05 -0700427 public static UserManagerService getInstance() {
428 synchronized (UserManagerService.class) {
429 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700430 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700431 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700432
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700433 public static class LifeCycle extends SystemService {
434
435 private UserManagerService mUms;
436
437 /**
438 * @param context
439 */
440 public LifeCycle(Context context) {
441 super(context);
442 }
443
444 @Override
445 public void onStart() {
446 mUms = UserManagerService.getInstance();
447 publishBinderService(Context.USER_SERVICE, mUms);
448 }
449
450 @Override
451 public void onBootPhase(int phase) {
452 if (phase == SystemService.PHASE_ACTIVITY_MANAGER_READY) {
453 mUms.cleanupPartialUsers();
454 }
455 }
456 }
457
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700458 // TODO b/28848102 Add support for test dependencies injection
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800459 @VisibleForTesting
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700460 UserManagerService(Context context) {
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800461 this(context, null, null, new Object(), context.getCacheDir());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700462 }
463
Dianne Hackborn4428e172012-08-24 17:43:05 -0700464 /**
465 * Called by package manager to create the service. This is closely
466 * associated with the package manager, and the given lock is the
467 * package manager's own lock.
468 */
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800469 UserManagerService(Context context, PackageManagerService pm, UserDataPreparer userDataPreparer,
470 Object packagesLock) {
471 this(context, pm, userDataPreparer, packagesLock, Environment.getDataDirectory());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700472 }
473
Dianne Hackborn4428e172012-08-24 17:43:05 -0700474 private UserManagerService(Context context, PackageManagerService pm,
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800475 UserDataPreparer userDataPreparer, Object packagesLock, File dataDir) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700476 mContext = context;
477 mPm = pm;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700478 mPackagesLock = packagesLock;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800479 mHandler = new MainHandler();
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800480 mUserDataPreparer = userDataPreparer;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800481 synchronized (mPackagesLock) {
482 mUsersDir = new File(dataDir, USER_INFO_DIR);
483 mUsersDir.mkdirs();
484 // Make zeroth user directory, for services to migrate their files to that location
485 File userZeroDir = new File(mUsersDir, String.valueOf(UserHandle.USER_SYSTEM));
486 userZeroDir.mkdirs();
487 FileUtils.setPermissions(mUsersDir.toString(),
488 FileUtils.S_IRWXU | FileUtils.S_IRWXG | FileUtils.S_IROTH | FileUtils.S_IXOTH,
489 -1, -1);
490 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
491 initDefaultGuestRestrictions();
492 readUserListLP();
493 sInstance = this;
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700494 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700495 mLocalService = new LocalService();
496 LocalServices.addService(UserManagerInternal.class, mLocalService);
Clara Bayarria1771112015-12-18 16:29:18 +0000497 mLockPatternUtils = new LockPatternUtils(mContext);
Amith Yamasaniea1b9d72016-05-27 15:57:38 +0000498 mUserStates.put(UserHandle.USER_SYSTEM, UserState.STATE_BOOTING);
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700499 }
500
501 void systemReady() {
Jason Monk62062992014-05-06 09:55:28 -0400502 mAppOpsService = IAppOpsService.Stub.asInterface(
503 ServiceManager.getService(Context.APP_OPS_SERVICE));
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800504
505 synchronized (mRestrictionsLock) {
506 applyUserRestrictionsLR(UserHandle.USER_SYSTEM);
Jason Monk62062992014-05-06 09:55:28 -0400507 }
Samuel Tand9453b82016-03-14 15:57:02 -0700508
509 UserInfo currentGuestUser = findCurrentGuestUser();
510 if (currentGuestUser != null && !hasUserRestriction(
511 UserManager.DISALLOW_CONFIG_WIFI, currentGuestUser.id)) {
512 // If a guest user currently exists, apply the DISALLOW_CONFIG_WIFI option
513 // to it, in case this guest was created in a previous version where this
514 // user restriction was not a default guest restriction.
515 setUserRestriction(UserManager.DISALLOW_CONFIG_WIFI, true, currentGuestUser.id);
516 }
Amith Yamasanieb437d42016-04-29 09:31:25 -0700517
Ricky Waib1dd80b2016-06-07 18:00:55 +0100518 mContext.registerReceiver(mDisableQuietModeCallback,
519 new IntentFilter(ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK),
520 null, mHandler);
Amith Yamasani258848d2012-08-10 17:06:33 -0700521 }
522
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700523 void cleanupPartialUsers() {
524 // Prune out any partially created, partially removed and ephemeral users.
525 ArrayList<UserInfo> partials = new ArrayList<>();
526 synchronized (mUsersLock) {
527 final int userSize = mUsers.size();
528 for (int i = 0; i < userSize; i++) {
529 UserInfo ui = mUsers.valueAt(i).info;
530 if ((ui.partial || ui.guestToRemove || ui.isEphemeral()) && i != 0) {
531 partials.add(ui);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700532 addRemovingUserIdLocked(ui.id);
Amith Yamasaniae261892016-06-27 10:40:09 -0700533 ui.partial = true;
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700534 }
535 }
536 }
537 final int partialsSize = partials.size();
538 for (int i = 0; i < partialsSize; i++) {
539 UserInfo ui = partials.get(i);
540 Slog.w(LOG_TAG, "Removing partially created user " + ui.id
541 + " (name=" + ui.name + ")");
542 removeUserState(ui.id);
543 }
544 }
545
Amith Yamasani258848d2012-08-10 17:06:33 -0700546 @Override
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800547 public String getUserAccount(int userId) {
548 checkManageUserAndAcrossUsersFullPermission("get user account");
549 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800550 return mUsers.get(userId).account;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800551 }
552 }
553
554 @Override
555 public void setUserAccount(int userId, String accountName) {
556 checkManageUserAndAcrossUsersFullPermission("set user account");
Amith Yamasani12747872015-12-07 14:19:49 -0800557 UserData userToUpdate = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800558 synchronized (mPackagesLock) {
559 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800560 final UserData userData = mUsers.get(userId);
561 if (userData == null) {
562 Slog.e(LOG_TAG, "User not found for setting user account: u" + userId);
563 return;
564 }
565 String currentAccount = userData.account;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800566 if (!Objects.equal(currentAccount, accountName)) {
Amith Yamasani12747872015-12-07 14:19:49 -0800567 userData.account = accountName;
568 userToUpdate = userData;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800569 }
570 }
571
572 if (userToUpdate != null) {
573 writeUserLP(userToUpdate);
574 }
575 }
576 }
577
578 @Override
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700579 public UserInfo getPrimaryUser() {
580 checkManageUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700581 synchronized (mUsersLock) {
Amith Yamasani515d4062015-09-28 11:30:06 -0700582 final int userSize = mUsers.size();
583 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800584 UserInfo ui = mUsers.valueAt(i).info;
Xiaohui Chend3e9e182015-11-18 13:37:32 -0800585 if (ui.isPrimary() && !mRemovingUserIds.get(ui.id)) {
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700586 return ui;
587 }
588 }
589 }
590 return null;
591 }
592
593 @Override
Xiaohui Chen594f2082015-08-18 11:04:20 -0700594 public @NonNull List<UserInfo> getUsers(boolean excludeDying) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -0700595 checkManageOrCreateUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700596 synchronized (mUsersLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700597 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasani515d4062015-09-28 11:30:06 -0700598 final int userSize = mUsers.size();
599 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800600 UserInfo ui = mUsers.valueAt(i).info;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700601 if (ui.partial) {
602 continue;
603 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800604 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Amith Yamasani6f48d6e2016-03-23 14:28:25 -0700605 users.add(userWithName(ui));
Amith Yamasani920ace02012-09-20 22:15:37 -0700606 }
Amith Yamasani13593602012-03-22 16:16:17 -0700607 }
608 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700609 }
Amith Yamasani13593602012-03-22 16:16:17 -0700610 }
611
Amith Yamasani258848d2012-08-10 17:06:33 -0700612 @Override
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100613 public List<UserInfo> getProfiles(int userId, boolean enabledOnly) {
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700614 boolean returnFullInfo = true;
Amith Yamasani4f582632014-02-19 14:31:52 -0800615 if (userId != UserHandle.getCallingUserId()) {
Sudheer Shanka74680912016-07-29 11:03:37 -0700616 checkManageOrCreateUsersPermission("getting profiles related to user " + userId);
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700617 } else {
618 returnFullInfo = hasManageUsersPermission();
Amith Yamasani4f582632014-02-19 14:31:52 -0800619 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700620 final long ident = Binder.clearCallingIdentity();
621 try {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700622 synchronized (mUsersLock) {
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700623 return getProfilesLU(userId, enabledOnly, returnFullInfo);
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100624 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700625 } finally {
626 Binder.restoreCallingIdentity(ident);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000627 }
628 }
629
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700630 @Override
631 public int[] getProfileIds(int userId, boolean enabledOnly) {
632 if (userId != UserHandle.getCallingUserId()) {
bohu12d23a12016-09-26 16:20:07 -0700633 checkManageOrCreateUsersPermission("getting profiles related to user " + userId);
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700634 }
635 final long ident = Binder.clearCallingIdentity();
636 try {
637 synchronized (mUsersLock) {
638 return getProfileIdsLU(userId, enabledOnly).toArray();
639 }
640 } finally {
641 Binder.restoreCallingIdentity(ident);
642 }
643 }
644
Amith Yamasanibe465322014-04-24 13:45:17 -0700645 /** Assume permissions already checked and caller's identity cleared */
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700646 private List<UserInfo> getProfilesLU(int userId, boolean enabledOnly, boolean fullInfo) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700647 IntArray profileIds = getProfileIdsLU(userId, enabledOnly);
648 ArrayList<UserInfo> users = new ArrayList<>(profileIds.size());
649 for (int i = 0; i < profileIds.size(); i++) {
650 int profileId = profileIds.get(i);
651 UserInfo userInfo = mUsers.get(profileId).info;
652 // If full info is not required - clear PII data to prevent 3P apps from reading it
653 if (!fullInfo) {
654 userInfo = new UserInfo(userInfo);
655 userInfo.name = null;
656 userInfo.iconPath = null;
657 } else {
658 userInfo = userWithName(userInfo);
659 }
660 users.add(userInfo);
661 }
662 return users;
663 }
664
665 /**
666 * Assume permissions already checked and caller's identity cleared
667 */
668 private IntArray getProfileIdsLU(int userId, boolean enabledOnly) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700669 UserInfo user = getUserInfoLU(userId);
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700670 IntArray result = new IntArray(mUsers.size());
Amith Yamasanidda003f2014-08-28 18:06:51 -0700671 if (user == null) {
672 // Probably a dying user
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700673 return result;
Amith Yamasanidda003f2014-08-28 18:06:51 -0700674 }
Amith Yamasani515d4062015-09-28 11:30:06 -0700675 final int userSize = mUsers.size();
676 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800677 UserInfo profile = mUsers.valueAt(i).info;
Amith Yamasanibe465322014-04-24 13:45:17 -0700678 if (!isProfileOf(user, profile)) {
679 continue;
680 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100681 if (enabledOnly && !profile.isEnabled()) {
682 continue;
Amith Yamasanibe465322014-04-24 13:45:17 -0700683 }
Amith Yamasani70fcf0c2014-07-11 08:40:19 -0700684 if (mRemovingUserIds.get(profile.id)) {
685 continue;
686 }
Tony Mak80189cd2016-04-05 17:21:42 +0100687 if (profile.partial) {
688 continue;
689 }
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700690 result.add(profile.id);
Amith Yamasanibe465322014-04-24 13:45:17 -0700691 }
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700692 return result;
Amith Yamasanibe465322014-04-24 13:45:17 -0700693 }
694
Jessica Hummelbe81c802014-04-22 15:49:22 +0100695 @Override
Andres Moralesc5548c02015-08-05 10:23:12 -0700696 public int getCredentialOwnerProfile(int userHandle) {
697 checkManageUsersPermission("get the credential owner");
Clara Bayarria1771112015-12-18 16:29:18 +0000698 if (!mLockPatternUtils.isSeparateProfileChallengeEnabled(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700699 synchronized (mUsersLock) {
700 UserInfo profileParent = getProfileParentLU(userHandle);
Andres Moralesc5548c02015-08-05 10:23:12 -0700701 if (profileParent != null) {
702 return profileParent.id;
703 }
704 }
705 }
706
707 return userHandle;
708 }
709
710 @Override
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700711 public boolean isSameProfileGroup(int userId, int otherUserId) {
712 if (userId == otherUserId) return true;
713 checkManageUsersPermission("check if in the same profile group");
Fyodor Kupolov0fb772e2016-10-13 16:27:34 -0700714 return isSameProfileGroupNoChecks(userId, otherUserId);
715 }
716
717 private boolean isSameProfileGroupNoChecks(int userId, int otherUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700718 synchronized (mUsersLock) {
719 UserInfo userInfo = getUserInfoLU(userId);
720 if (userInfo == null || userInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
721 return false;
722 }
723 UserInfo otherUserInfo = getUserInfoLU(otherUserId);
724 if (otherUserInfo == null
725 || otherUserInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
726 return false;
727 }
728 return userInfo.profileGroupId == otherUserInfo.profileGroupId;
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700729 }
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700730 }
731
732 @Override
Jessica Hummelbe81c802014-04-22 15:49:22 +0100733 public UserInfo getProfileParent(int userHandle) {
734 checkManageUsersPermission("get the profile parent");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700735 synchronized (mUsersLock) {
736 return getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700737 }
738 }
739
Jakub Pawlowski0f1f5b72017-11-15 14:50:43 -0800740 @Override
741 public int getProfileParentId(int userHandle) {
742 checkManageUsersPermission("get the profile parent");
743 synchronized (mUsersLock) {
744 UserInfo profileParent = getProfileParentLU(userHandle);
745 if (profileParent == null) {
746 return userHandle;
747 }
748
749 return profileParent.id;
750 }
751 }
752
Fyodor Kupolov82402752015-10-28 14:54:51 -0700753 private UserInfo getProfileParentLU(int userHandle) {
754 UserInfo profile = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700755 if (profile == null) {
756 return null;
757 }
758 int parentUserId = profile.profileGroupId;
Amith Yamasani801e3422017-01-25 11:35:44 -0800759 if (parentUserId == userHandle || parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700760 return null;
761 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700762 return getUserInfoLU(parentUserId);
Jessica Hummelbe81c802014-04-22 15:49:22 +0100763 }
764 }
765
Fyodor Kupolov82402752015-10-28 14:54:51 -0700766 private static boolean isProfileOf(UserInfo user, UserInfo profile) {
Kenny Guy2a764942014-04-02 13:29:20 +0100767 return user.id == profile.id ||
768 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
769 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000770 }
771
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000772 private void broadcastProfileAvailabilityChanges(UserHandle profileHandle,
Rubin Xuf13c9802016-01-21 18:06:00 +0000773 UserHandle parentHandle, boolean inQuietMode) {
Rubin Xue95057a2016-04-01 16:49:25 +0100774 Intent intent = new Intent();
775 if (inQuietMode) {
776 intent.setAction(Intent.ACTION_MANAGED_PROFILE_UNAVAILABLE);
777 } else {
778 intent.setAction(Intent.ACTION_MANAGED_PROFILE_AVAILABLE);
779 }
Rubin Xuf13c9802016-01-21 18:06:00 +0000780 intent.putExtra(Intent.EXTRA_QUIET_MODE, inQuietMode);
781 intent.putExtra(Intent.EXTRA_USER, profileHandle);
782 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileHandle.getIdentifier());
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000783 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Rubin Xuf13c9802016-01-21 18:06:00 +0000784 mContext.sendBroadcastAsUser(intent, parentHandle);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000785 }
786
787 @Override
Tony Make3d1f652017-12-12 11:00:37 +0000788 public boolean trySetQuietModeEnabled(@NonNull String callingPackage, boolean enableQuietMode,
789 int userHandle, @Nullable IntentSender target) {
790 Preconditions.checkNotNull(callingPackage);
791
Tony Makb7e6fd42017-12-05 19:40:28 +0000792 if (enableQuietMode && target != null) {
793 throw new IllegalArgumentException(
794 "target should only be specified when we are disabling quiet mode.");
795 }
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000796
Tony Makd390ae92017-12-28 13:23:10 +0000797 ensureCanModifyQuietMode(callingPackage, Binder.getCallingUid(), target != null);
Tony Makb7e6fd42017-12-05 19:40:28 +0000798 final long identity = Binder.clearCallingIdentity();
799 try {
800 if (enableQuietMode) {
801 setQuietModeEnabled(userHandle, true /* enableQuietMode */, target);
802 return true;
803 } else {
804 boolean needToShowConfirmCredential =
805 mLockPatternUtils.isSecure(userHandle)
806 && !StorageManager.isUserKeyUnlocked(userHandle);
807 if (needToShowConfirmCredential) {
808 showConfirmCredentialToDisableQuietMode(userHandle, target);
809 return false;
810 } else {
811 setQuietModeEnabled(userHandle, false /* enableQuietMode */, target);
812 return true;
813 }
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000814 }
Tony Makb7e6fd42017-12-05 19:40:28 +0000815 } finally {
816 Binder.restoreCallingIdentity(identity);
817 }
818 }
819
Tony Make3d1f652017-12-12 11:00:37 +0000820 /**
Tony Makd390ae92017-12-28 13:23:10 +0000821 * The caller can modify quiet mode if it meets one of these conditions:
Tony Make3d1f652017-12-12 11:00:37 +0000822 * <ul>
823 * <li>Has system UID or root UID</li>
824 * <li>Has {@link Manifest.permission#MODIFY_QUIET_MODE}</li>
825 * <li>Has {@link Manifest.permission#MANAGE_USERS}</li>
826 * </ul>
Tony Makd390ae92017-12-28 13:23:10 +0000827 * <p>
828 * If caller wants to start an intent after disabling the quiet mode, it must has
829 * {@link Manifest.permission#MANAGE_USERS}.
Tony Make3d1f652017-12-12 11:00:37 +0000830 */
Tony Makd390ae92017-12-28 13:23:10 +0000831 private void ensureCanModifyQuietMode(String callingPackage, int callingUid,
832 boolean startIntent) {
Tony Make3d1f652017-12-12 11:00:37 +0000833 if (hasManageUsersPermission()) {
Tony Makd390ae92017-12-28 13:23:10 +0000834 return;
Tony Make3d1f652017-12-12 11:00:37 +0000835 }
Tony Makd390ae92017-12-28 13:23:10 +0000836 if (startIntent) {
837 throw new SecurityException("MANAGE_USERS permission is required to start intent "
838 + "after disabling quiet mode.");
839 }
Tony Make3d1f652017-12-12 11:00:37 +0000840 final boolean hasModifyQuietModePermission = ActivityManager.checkComponentPermission(
841 Manifest.permission.MODIFY_QUIET_MODE,
842 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED;
843 if (hasModifyQuietModePermission) {
Tony Makd390ae92017-12-28 13:23:10 +0000844 return;
Tony Make3d1f652017-12-12 11:00:37 +0000845 }
846
Tony Makd390ae92017-12-28 13:23:10 +0000847 verifyCallingPackage(callingPackage, callingUid);
Tony Make3d1f652017-12-12 11:00:37 +0000848 final ShortcutServiceInternal shortcutInternal =
849 LocalServices.getService(ShortcutServiceInternal.class);
850 if (shortcutInternal != null) {
851 boolean isForegroundLauncher =
852 shortcutInternal.isForegroundDefaultLauncher(callingPackage, callingUid);
853 if (isForegroundLauncher) {
Tony Makd390ae92017-12-28 13:23:10 +0000854 return;
Tony Make3d1f652017-12-12 11:00:37 +0000855 }
856 }
Tony Makd390ae92017-12-28 13:23:10 +0000857 throw new SecurityException("Can't modify quiet mode, caller is neither foreground "
858 + "default launcher nor has MANAGE_USERS/MODIFY_QUIET_MODE permission");
Tony Make3d1f652017-12-12 11:00:37 +0000859 }
860
Tony Makb7e6fd42017-12-05 19:40:28 +0000861 private void setQuietModeEnabled(
862 int userHandle, boolean enableQuietMode, IntentSender target) {
863 final UserInfo profile, parent;
864 final UserData profileUserData;
865 synchronized (mUsersLock) {
866 profile = getUserInfoLU(userHandle);
867 parent = getProfileParentLU(userHandle);
868
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000869 if (profile == null || !profile.isManagedProfile()) {
870 throw new IllegalArgumentException("User " + userHandle + " is not a profile");
871 }
Tony Makb7e6fd42017-12-05 19:40:28 +0000872 if (profile.isQuietModeEnabled() == enableQuietMode) {
873 Slog.i(LOG_TAG, "Quiet mode is already " + enableQuietMode);
874 return;
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000875 }
Tony Makb7e6fd42017-12-05 19:40:28 +0000876 profile.flags ^= UserInfo.FLAG_QUIET_MODE;
877 profileUserData = getUserDataLU(profile.id);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000878 }
Tony Makb7e6fd42017-12-05 19:40:28 +0000879 synchronized (mPackagesLock) {
880 writeUserLP(profileUserData);
881 }
882 try {
883 if (enableQuietMode) {
884 ActivityManager.getService().stopUser(userHandle, /* force */true, null);
885 LocalServices.getService(ActivityManagerInternal.class)
886 .killForegroundAppsForUser(userHandle);
887 } else {
888 IProgressListener callback = target != null
889 ? new DisableQuietModeUserUnlockedCallback(target)
890 : null;
891 ActivityManager.getService().startUserInBackgroundWithListener(
892 userHandle, callback);
Rubin Xuf13c9802016-01-21 18:06:00 +0000893 }
Tony Makb7e6fd42017-12-05 19:40:28 +0000894 } catch (RemoteException e) {
895 // Should not happen, same process.
896 e.rethrowAsRuntimeException();
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000897 }
Tony Makb7e6fd42017-12-05 19:40:28 +0000898 broadcastProfileAvailabilityChanges(profile.getUserHandle(), parent.getUserHandle(),
899 enableQuietMode);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000900 }
901
902 @Override
903 public boolean isQuietModeEnabled(int userHandle) {
904 synchronized (mPackagesLock) {
905 UserInfo info;
906 synchronized (mUsersLock) {
907 info = getUserInfoLU(userHandle);
908 }
909 if (info == null || !info.isManagedProfile()) {
Rubin Xuf13c9802016-01-21 18:06:00 +0000910 return false;
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000911 }
912 return info.isQuietModeEnabled();
913 }
914 }
915
Tony Makb7e6fd42017-12-05 19:40:28 +0000916 /**
917 * Show confirm credential screen to unlock user in order to turn off quiet mode.
918 */
919 private void showConfirmCredentialToDisableQuietMode(
Tony Mak64fd8c02017-12-01 19:11:59 +0000920 @UserIdInt int userHandle, @Nullable IntentSender target) {
Tony Makb7e6fd42017-12-05 19:40:28 +0000921 // otherwise, we show a profile challenge to trigger decryption of the user
922 final KeyguardManager km = (KeyguardManager) mContext.getSystemService(
923 Context.KEYGUARD_SERVICE);
924 // We should use userHandle not credentialOwnerUserId here, as even if it is unified
925 // lock, confirm screenlock page will know and show personal challenge, and unlock
926 // work profile when personal challenge is correct
927 final Intent unlockIntent = km.createConfirmDeviceCredentialIntent(null, null,
928 userHandle);
929 if (unlockIntent == null) {
930 return;
Benjamin Franzf02420c2016-04-04 18:52:21 +0100931 }
Tony Makb7e6fd42017-12-05 19:40:28 +0000932 final Intent callBackIntent = new Intent(
933 ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK);
934 if (target != null) {
935 callBackIntent.putExtra(Intent.EXTRA_INTENT, target);
Benjamin Franzf02420c2016-04-04 18:52:21 +0100936 }
Tony Makb7e6fd42017-12-05 19:40:28 +0000937 callBackIntent.putExtra(Intent.EXTRA_USER_ID, userHandle);
938 callBackIntent.setPackage(mContext.getPackageName());
939 callBackIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
940 final PendingIntent pendingIntent = PendingIntent.getBroadcast(
941 mContext,
942 0,
943 callBackIntent,
944 PendingIntent.FLAG_CANCEL_CURRENT |
945 PendingIntent.FLAG_ONE_SHOT |
946 PendingIntent.FLAG_IMMUTABLE);
947 // After unlocking the challenge, it will disable quiet mode and run the original
948 // intentSender
949 unlockIntent.putExtra(Intent.EXTRA_INTENT, pendingIntent.getIntentSender());
950 unlockIntent.setFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
951 mContext.startActivity(unlockIntent);
Benjamin Franzf02420c2016-04-04 18:52:21 +0100952 }
953
954 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100955 public void setUserEnabled(int userId) {
956 checkManageUsersPermission("enable user");
957 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700958 UserInfo info;
959 synchronized (mUsersLock) {
960 info = getUserInfoLU(userId);
961 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100962 if (info != null && !info.isEnabled()) {
963 info.flags ^= UserInfo.FLAG_DISABLED;
Amith Yamasani12747872015-12-07 14:19:49 -0800964 writeUserLP(getUserDataLU(info.id));
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100965 }
966 }
967 }
968
Andrew Scull85a63bc2016-10-24 13:47:47 +0100969 /**
970 * Evicts a user's CE key by stopping and restarting the user.
971 *
972 * The key is evicted automatically by the user controller when the user has stopped.
973 */
974 @Override
975 public void evictCredentialEncryptionKey(@UserIdInt int userId) {
976 checkManageUsersPermission("evict CE key");
977 final IActivityManager am = ActivityManagerNative.getDefault();
978 final long identity = Binder.clearCallingIdentity();
979 try {
980 am.restartUserInBackground(userId);
981 } catch (RemoteException re) {
982 throw re.rethrowAsRuntimeException();
983 } finally {
984 Binder.restoreCallingIdentity(identity);
985 }
986 }
987
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100988 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700989 public UserInfo getUserInfo(int userId) {
Sudheer Shankaaccaa082016-06-14 16:22:57 -0700990 checkManageOrCreateUsersPermission("query user");
Tony Mak8673b282016-03-21 21:10:59 +0000991 synchronized (mUsersLock) {
Amith Yamasani6f48d6e2016-03-23 14:28:25 -0700992 return userWithName(getUserInfoLU(userId));
993 }
994 }
995
996 /**
997 * Returns a UserInfo object with the name filled in, for Owner, or the original
998 * if the name is already set.
999 */
1000 private UserInfo userWithName(UserInfo orig) {
1001 if (orig != null && orig.name == null && orig.id == UserHandle.USER_SYSTEM) {
1002 UserInfo withName = new UserInfo(orig);
1003 withName.name = getOwnerName();
1004 return withName;
1005 } else {
1006 return orig;
Tony Mak8673b282016-03-21 21:10:59 +00001007 }
1008 }
1009
1010 @Override
Kenny Guy02c89902016-11-15 19:36:38 +00001011 public int getManagedProfileBadge(@UserIdInt int userId) {
1012 int callingUserId = UserHandle.getCallingUserId();
1013 if (callingUserId != userId && !hasManageUsersPermission()) {
1014 if (!isSameProfileGroupNoChecks(callingUserId, userId)) {
1015 throw new SecurityException(
1016 "You need MANAGE_USERS permission to: check if specified user a " +
1017 "managed profile outside your profile group");
1018 }
1019 }
1020 synchronized (mUsersLock) {
1021 UserInfo userInfo = getUserInfoLU(userId);
1022 return userInfo != null ? userInfo.profileBadge : 0;
1023 }
1024 }
1025
1026 @Override
Tony Mak8673b282016-03-21 21:10:59 +00001027 public boolean isManagedProfile(int userId) {
Tony Makb531d082016-03-16 14:49:52 +00001028 int callingUserId = UserHandle.getCallingUserId();
1029 if (callingUserId != userId && !hasManageUsersPermission()) {
Fyodor Kupolov0fb772e2016-10-13 16:27:34 -07001030 if (!isSameProfileGroupNoChecks(callingUserId, userId)) {
Fyodor Kupolovc413f702016-10-06 17:11:14 -07001031 throw new SecurityException(
1032 "You need MANAGE_USERS permission to: check if specified user a " +
1033 "managed profile outside your profile group");
Tony Makb531d082016-03-16 14:49:52 +00001034 }
Tony Mak4dc008c2016-03-16 10:46:49 +00001035 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001036 synchronized (mUsersLock) {
Amith Yamasani1c41dc82016-06-28 16:13:15 -07001037 UserInfo userInfo = getUserInfoLU(userId);
Tony Mak8673b282016-03-21 21:10:59 +00001038 return userInfo != null && userInfo.isManagedProfile();
Amith Yamasani13593602012-03-22 16:16:17 -07001039 }
1040 }
1041
Amith Yamasani71e6c692013-03-24 17:39:28 -07001042 @Override
Fyodor Kupolovc413f702016-10-06 17:11:14 -07001043 public boolean isUserUnlockingOrUnlocked(int userId) {
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08001044 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isUserUnlockingOrUnlocked");
Fyodor Kupolovc413f702016-10-06 17:11:14 -07001045 return mLocalService.isUserUnlockingOrUnlocked(userId);
1046 }
1047
1048 @Override
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08001049 public boolean isUserUnlocked(int userId) {
1050 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isUserUnlocked");
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07001051 return mLocalService.isUserUnlocked(userId);
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08001052 }
1053
1054 @Override
1055 public boolean isUserRunning(int userId) {
1056 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isUserRunning");
1057 return mLocalService.isUserRunning(userId);
1058 }
1059
1060 private void checkManageOrInteractPermIfCallerInOtherProfileGroup(int userId, String name) {
1061 int callingUserId = UserHandle.getCallingUserId();
1062 if (callingUserId == userId || isSameProfileGroupNoChecks(callingUserId, userId) ||
1063 hasManageUsersPermission()) {
1064 return;
1065 }
1066 if (ActivityManager.checkComponentPermission(Manifest.permission.INTERACT_ACROSS_USERS,
1067 Binder.getCallingUid(), -1, true) != PackageManager.PERMISSION_GRANTED) {
1068 throw new SecurityException("You need INTERACT_ACROSS_USERS or MANAGE_USERS permission "
1069 + "to: check " + name);
1070 }
1071 }
1072
1073 @Override
Amith Yamasani1c41dc82016-06-28 16:13:15 -07001074 public boolean isDemoUser(int userId) {
1075 int callingUserId = UserHandle.getCallingUserId();
1076 if (callingUserId != userId && !hasManageUsersPermission()) {
1077 throw new SecurityException("You need MANAGE_USERS permission to query if u=" + userId
1078 + " is a demo user");
1079 }
1080 synchronized (mUsersLock) {
1081 UserInfo userInfo = getUserInfoLU(userId);
1082 return userInfo != null && userInfo.isDemo();
1083 }
1084 }
1085
1086 @Override
Amith Yamasani71e6c692013-03-24 17:39:28 -07001087 public boolean isRestricted() {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001088 synchronized (mUsersLock) {
1089 return getUserInfoLU(UserHandle.getCallingUserId()).isRestricted();
Amith Yamasani71e6c692013-03-24 17:39:28 -07001090 }
1091 }
1092
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001093 @Override
1094 public boolean canHaveRestrictedProfile(int userId) {
1095 checkManageUsersPermission("canHaveRestrictedProfile");
Fyodor Kupolov82402752015-10-28 14:54:51 -07001096 synchronized (mUsersLock) {
1097 final UserInfo userInfo = getUserInfoLU(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001098 if (userInfo == null || !userInfo.canHaveProfile()) {
1099 return false;
1100 }
1101 if (!userInfo.isAdmin()) {
1102 return false;
1103 }
Makoto Onukie7927da2015-11-25 10:05:17 -08001104 // restricted profile can be created if there is no DO set and the admin user has no PO;
1105 return !mIsDeviceManaged && !mIsUserManaged.get(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001106 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001107 }
1108
Fyodor Kupolovca177562017-11-09 17:43:01 -08001109 @Override
1110 public boolean hasRestrictedProfiles() {
1111 checkManageUsersPermission("hasRestrictedProfiles");
1112 final int callingUserId = UserHandle.getCallingUserId();
1113 synchronized (mUsersLock) {
1114 final int userSize = mUsers.size();
1115 for (int i = 0; i < userSize; i++) {
1116 UserInfo profile = mUsers.valueAt(i).info;
1117 if (callingUserId != profile.id
1118 && profile.restrictedProfileParentId == callingUserId) {
1119 return true;
1120 }
1121 }
1122 return false;
1123 }
1124 }
1125
Amith Yamasani195263742012-08-21 15:40:12 -07001126 /*
1127 * Should be locked on mUsers before calling this.
1128 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001129 private UserInfo getUserInfoLU(int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -08001130 final UserData userData = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -07001131 // If it is partial and not in the process of being removed, return as unknown user.
Amith Yamasani12747872015-12-07 14:19:49 -08001132 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001133 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
1134 return null;
1135 }
Amith Yamasani12747872015-12-07 14:19:49 -08001136 return userData != null ? userData.info : null;
1137 }
1138
1139 private UserData getUserDataLU(int userId) {
1140 final UserData userData = mUsers.get(userId);
1141 // If it is partial and not in the process of being removed, return as unknown user.
1142 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
1143 return null;
1144 }
1145 return userData;
Amith Yamasani195263742012-08-21 15:40:12 -07001146 }
1147
Fyodor Kupolov82402752015-10-28 14:54:51 -07001148 /**
1149 * Obtains {@link #mUsersLock} and return UserInfo from mUsers.
1150 * <p>No permissions checking or any addition checks are made</p>
1151 */
1152 private UserInfo getUserInfoNoChecks(int userId) {
1153 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001154 final UserData userData = mUsers.get(userId);
1155 return userData != null ? userData.info : null;
1156 }
1157 }
1158
1159 /**
1160 * Obtains {@link #mUsersLock} and return UserData from mUsers.
1161 * <p>No permissions checking or any addition checks are made</p>
1162 */
1163 private UserData getUserDataNoChecks(int userId) {
1164 synchronized (mUsersLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001165 return mUsers.get(userId);
1166 }
1167 }
1168
Amith Yamasani236b2b52015-08-18 14:32:14 -07001169 /** Called by PackageManagerService */
Amith Yamasani13593602012-03-22 16:16:17 -07001170 public boolean exists(int userId) {
Todd Kennedy0eb97382017-10-03 16:57:22 -07001171 return mLocalService.exists(userId);
Amith Yamasani13593602012-03-22 16:16:17 -07001172 }
1173
Amith Yamasani258848d2012-08-10 17:06:33 -07001174 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001175 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001176 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001177 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -07001178 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001179 UserData userData = getUserDataNoChecks(userId);
1180 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001181 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
1182 return;
1183 }
Amith Yamasani12747872015-12-07 14:19:49 -08001184 if (name != null && !name.equals(userData.info.name)) {
1185 userData.info.name = name;
1186 writeUserLP(userData);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001187 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -07001188 }
1189 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001190 if (changed) {
1191 sendUserInfoChangedBroadcast(userId);
1192 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001193 }
1194
Amith Yamasani258848d2012-08-10 17:06:33 -07001195 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001196 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001197 checkManageUsersPermission("update users");
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01001198 if (hasUserRestriction(UserManager.DISALLOW_SET_USER_ICON, userId)) {
1199 Log.w(LOG_TAG, "Cannot set user icon. DISALLOW_SET_USER_ICON is enabled.");
1200 return;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001201 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01001202 mLocalService.setUserIcon(userId, bitmap);
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001203 }
1204
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01001205
1206
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001207 private void sendUserInfoChangedBroadcast(int userId) {
1208 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
1209 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
1210 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -07001211 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001212 }
1213
Amith Yamasani258848d2012-08-10 17:06:33 -07001214 @Override
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001215 public ParcelFileDescriptor getUserIcon(int targetUserId) {
Adrian Roos1bdff912015-02-17 15:51:35 +01001216 String iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001217 synchronized (mPackagesLock) {
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001218 UserInfo targetUserInfo = getUserInfoNoChecks(targetUserId);
1219 if (targetUserInfo == null || targetUserInfo.partial) {
1220 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + targetUserId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001221 return null;
1222 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001223
1224 final int callingUserId = UserHandle.getCallingUserId();
1225 final int callingGroupId = getUserInfoNoChecks(callingUserId).profileGroupId;
1226 final int targetGroupId = targetUserInfo.profileGroupId;
1227 final boolean sameGroup = (callingGroupId != UserInfo.NO_PROFILE_GROUP_ID
1228 && callingGroupId == targetGroupId);
1229 if ((callingUserId != targetUserId) && !sameGroup) {
Nicolas Prevot88cc3462014-05-14 14:51:48 +01001230 checkManageUsersPermission("get the icon of a user who is not related");
1231 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001232
1233 if (targetUserInfo.iconPath == null) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001234 return null;
1235 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001236 iconPath = targetUserInfo.iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001237 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001238
1239 try {
1240 return ParcelFileDescriptor.open(
1241 new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
1242 } catch (FileNotFoundException e) {
1243 Log.e(LOG_TAG, "Couldn't find icon file", e);
1244 }
1245 return null;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001246 }
1247
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001248 public void makeInitialized(int userId) {
1249 checkManageUsersPermission("makeInitialized");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001250 boolean scheduleWriteUser = false;
Amith Yamasani12747872015-12-07 14:19:49 -08001251 UserData userData;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001252 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001253 userData = mUsers.get(userId);
1254 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001255 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001256 return;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001257 }
Amith Yamasani12747872015-12-07 14:19:49 -08001258 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1259 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001260 scheduleWriteUser = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001261 }
1262 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001263 if (scheduleWriteUser) {
Amith Yamasani12747872015-12-07 14:19:49 -08001264 scheduleWriteUser(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001265 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001266 }
1267
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001268 /**
1269 * If default guest restrictions haven't been initialized yet, add the basic
1270 * restrictions.
1271 */
1272 private void initDefaultGuestRestrictions() {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001273 synchronized (mGuestRestrictions) {
1274 if (mGuestRestrictions.isEmpty()) {
Samuel Tand9453b82016-03-14 15:57:02 -07001275 mGuestRestrictions.putBoolean(UserManager.DISALLOW_CONFIG_WIFI, true);
Fyodor Kupolove04462c2015-11-30 15:02:53 -08001276 mGuestRestrictions.putBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, true);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001277 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
1278 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
1279 }
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001280 }
1281 }
1282
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001283 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301284 public Bundle getDefaultGuestRestrictions() {
1285 checkManageUsersPermission("getDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001286 synchronized (mGuestRestrictions) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301287 return new Bundle(mGuestRestrictions);
1288 }
1289 }
1290
1291 @Override
1292 public void setDefaultGuestRestrictions(Bundle restrictions) {
1293 checkManageUsersPermission("setDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001294 synchronized (mGuestRestrictions) {
1295 mGuestRestrictions.clear();
1296 mGuestRestrictions.putAll(restrictions);
1297 }
1298 synchronized (mPackagesLock) {
1299 writeUserListLP();
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301300 }
1301 }
1302
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001303 /**
Pavel Grafov6a40f092016-10-25 15:46:51 +01001304 * See {@link UserManagerInternal#setDevicePolicyUserRestrictions}
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001305 */
Pavel Grafov6a40f092016-10-25 15:46:51 +01001306 private void setDevicePolicyUserRestrictionsInner(int userId, @Nullable Bundle restrictions,
1307 boolean isDeviceOwner, int cameraRestrictionScope) {
1308 final Bundle global = new Bundle();
1309 final Bundle local = new Bundle();
1310
1311 // Sort restrictions into local and global ensuring they don't overlap.
1312 UserRestrictionsUtils.sortToGlobalAndLocal(restrictions, isDeviceOwner,
1313 cameraRestrictionScope, global, local);
1314
1315 boolean globalChanged, localChanged;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001316 synchronized (mRestrictionsLock) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001317 // Update global and local restrictions if they were changed.
1318 globalChanged = updateRestrictionsIfNeededLR(
1319 userId, global, mDevicePolicyGlobalUserRestrictions);
1320 localChanged = updateRestrictionsIfNeededLR(
1321 userId, local, mDevicePolicyLocalUserRestrictions);
1322
1323 if (isDeviceOwner) {
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001324 // Remember the global restriction owner userId to be able to make a distinction
1325 // in getUserRestrictionSource on who set local policies.
Pavel Grafov6a40f092016-10-25 15:46:51 +01001326 mDeviceOwnerUserId = userId;
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001327 } else {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001328 if (mDeviceOwnerUserId == userId) {
Zoltan Szatmary-Ban8a5536d2016-05-27 17:56:44 +01001329 // When profile owner sets restrictions it passes null global bundle and we
1330 // reset global restriction owner userId.
1331 // This means this user used to have DO, but now the DO is gone and the user
1332 // instead has PO.
Pavel Grafov6a40f092016-10-25 15:46:51 +01001333 mDeviceOwnerUserId = UserHandle.USER_NULL;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001334 }
1335 }
1336 }
1337 if (DBG) {
1338 Log.d(LOG_TAG, "setDevicePolicyUserRestrictions: userId=" + userId
1339 + " global=" + global + (globalChanged ? " (changed)" : "")
1340 + " local=" + local + (localChanged ? " (changed)" : "")
1341 );
1342 }
1343 // Don't call them within the mRestrictionsLock.
1344 synchronized (mPackagesLock) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001345 if (localChanged || globalChanged) {
Amith Yamasani12747872015-12-07 14:19:49 -08001346 writeUserLP(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001347 }
1348 }
1349
1350 synchronized (mRestrictionsLock) {
1351 if (globalChanged) {
1352 applyUserRestrictionsForAllUsersLR();
1353 } else if (localChanged) {
1354 applyUserRestrictionsLR(userId);
1355 }
1356 }
1357 }
1358
Pavel Grafov6a40f092016-10-25 15:46:51 +01001359 /**
1360 * Updates restriction bundle for a given user in a given restriction array. If new bundle is
1361 * empty, record is removed from the array.
1362 * @return whether restrictions bundle is different from the old one.
1363 */
1364 private boolean updateRestrictionsIfNeededLR(int userId, @Nullable Bundle restrictions,
1365 SparseArray<Bundle> restrictionsArray) {
1366 final boolean changed =
1367 !UserRestrictionsUtils.areEqual(restrictionsArray.get(userId), restrictions);
1368 if (changed) {
1369 if (!UserRestrictionsUtils.isEmpty(restrictions)) {
1370 restrictionsArray.put(userId, restrictions);
1371 } else {
1372 restrictionsArray.delete(userId);
1373 }
1374 }
1375 return changed;
1376 }
1377
Makoto Onuki068c54a2015-10-13 14:34:03 -07001378 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001379 private Bundle computeEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001380 final Bundle baseRestrictions =
1381 UserRestrictionsUtils.nonNull(mBaseUserRestrictions.get(userId));
Pavel Grafov6a40f092016-10-25 15:46:51 +01001382 final Bundle global = UserRestrictionsUtils.mergeAll(mDevicePolicyGlobalUserRestrictions);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001383 final Bundle local = mDevicePolicyLocalUserRestrictions.get(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001384
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001385 if (UserRestrictionsUtils.isEmpty(global) && UserRestrictionsUtils.isEmpty(local)) {
1386 // Common case first.
1387 return baseRestrictions;
Makoto Onuki068c54a2015-10-13 14:34:03 -07001388 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001389 final Bundle effective = UserRestrictionsUtils.clone(baseRestrictions);
1390 UserRestrictionsUtils.merge(effective, global);
1391 UserRestrictionsUtils.merge(effective, local);
1392
Makoto Onuki068c54a2015-10-13 14:34:03 -07001393 return effective;
1394 }
1395
1396 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001397 private void invalidateEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki068c54a2015-10-13 14:34:03 -07001398 if (DBG) {
1399 Log.d(LOG_TAG, "invalidateEffectiveUserRestrictions userId=" + userId);
1400 }
1401 mCachedEffectiveUserRestrictions.remove(userId);
1402 }
1403
1404 private Bundle getEffectiveUserRestrictions(int userId) {
1405 synchronized (mRestrictionsLock) {
1406 Bundle restrictions = mCachedEffectiveUserRestrictions.get(userId);
1407 if (restrictions == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001408 restrictions = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001409 mCachedEffectiveUserRestrictions.put(userId, restrictions);
1410 }
1411 return restrictions;
Amith Yamasani8cd28b52014-06-08 17:54:27 -07001412 }
1413 }
1414
Makoto Onuki068c54a2015-10-13 14:34:03 -07001415 /** @return a specific user restriction that's in effect currently. */
1416 @Override
1417 public boolean hasUserRestriction(String restrictionKey, int userId) {
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001418 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1419 return false;
1420 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001421 Bundle restrictions = getEffectiveUserRestrictions(userId);
1422 return restrictions != null && restrictions.getBoolean(restrictionKey);
1423 }
1424
1425 /**
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001426 * @hide
1427 *
1428 * Returns who set a user restriction on a user.
1429 * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
1430 * @param restrictionKey the string key representing the restriction
1431 * @param userId the id of the user for whom to retrieve the restrictions.
1432 * @return The source of user restriction. Any combination of
1433 * {@link UserManager#RESTRICTION_NOT_SET},
1434 * {@link UserManager#RESTRICTION_SOURCE_SYSTEM},
1435 * {@link UserManager#RESTRICTION_SOURCE_DEVICE_OWNER}
1436 * and {@link UserManager#RESTRICTION_SOURCE_PROFILE_OWNER}
1437 */
1438 @Override
1439 public int getUserRestrictionSource(String restrictionKey, int userId) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001440 List<EnforcingUser> enforcingUsers = getUserRestrictionSources(restrictionKey, userId);
1441 // Get "bitwise or" of restriction sources for all enforcing users.
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001442 int result = UserManager.RESTRICTION_NOT_SET;
Pavel Grafov6a40f092016-10-25 15:46:51 +01001443 for (int i = enforcingUsers.size() - 1; i >= 0; i--) {
1444 result |= enforcingUsers.get(i).getUserRestrictionSource();
1445 }
1446 return result;
1447 }
1448
1449 @Override
1450 public List<EnforcingUser> getUserRestrictionSources(
1451 String restrictionKey, @UserIdInt int userId) {
1452 checkManageUsersPermission("getUserRestrictionSource");
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001453
1454 // Shortcut for the most common case
1455 if (!hasUserRestriction(restrictionKey, userId)) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001456 return Collections.emptyList();
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001457 }
1458
Pavel Grafov6a40f092016-10-25 15:46:51 +01001459 final List<EnforcingUser> result = new ArrayList<>();
1460
1461 // Check if it is base restriction.
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001462 if (hasBaseUserRestriction(restrictionKey, userId)) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001463 result.add(new EnforcingUser(
1464 UserHandle.USER_NULL, UserManager.RESTRICTION_SOURCE_SYSTEM));
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001465 }
1466
Pavel Grafov6a40f092016-10-25 15:46:51 +01001467 synchronized (mRestrictionsLock) {
1468 // Check if it is set by profile owner.
1469 Bundle profileOwnerRestrictions = mDevicePolicyLocalUserRestrictions.get(userId);
1470 if (UserRestrictionsUtils.contains(profileOwnerRestrictions, restrictionKey)) {
1471 result.add(getEnforcingUserLocked(userId));
1472 }
1473
1474 // Iterate over all users who enforce global restrictions.
1475 for (int i = mDevicePolicyGlobalUserRestrictions.size() - 1; i >= 0; i--) {
1476 Bundle globalRestrictions = mDevicePolicyGlobalUserRestrictions.valueAt(i);
1477 int profileUserId = mDevicePolicyGlobalUserRestrictions.keyAt(i);
1478 if (UserRestrictionsUtils.contains(globalRestrictions, restrictionKey)) {
1479 result.add(getEnforcingUserLocked(profileUserId));
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001480 }
1481 }
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001482 }
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001483 return result;
1484 }
1485
Pavel Grafov6a40f092016-10-25 15:46:51 +01001486 private EnforcingUser getEnforcingUserLocked(@UserIdInt int userId) {
1487 int source = mDeviceOwnerUserId == userId ? UserManager.RESTRICTION_SOURCE_DEVICE_OWNER
1488 : UserManager.RESTRICTION_SOURCE_PROFILE_OWNER;
1489 return new EnforcingUser(userId, source);
1490 }
1491
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001492 /**
Makoto Onuki068c54a2015-10-13 14:34:03 -07001493 * @return UserRestrictions that are in effect currently. This always returns a new
1494 * {@link Bundle}.
1495 */
Amith Yamasani8cd28b52014-06-08 17:54:27 -07001496 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001497 public Bundle getUserRestrictions(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001498 return UserRestrictionsUtils.clone(getEffectiveUserRestrictions(userId));
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001499 }
1500
1501 @Override
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +00001502 public boolean hasBaseUserRestriction(String restrictionKey, int userId) {
1503 checkManageUsersPermission("hasBaseUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001504 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1505 return false;
1506 }
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +00001507 synchronized (mRestrictionsLock) {
1508 Bundle bundle = mBaseUserRestrictions.get(userId);
1509 return (bundle != null && bundle.getBoolean(restrictionKey, false));
1510 }
1511 }
1512
1513 @Override
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001514 public void setUserRestriction(String key, boolean value, int userId) {
Fyodor Kupolovd4b26042015-07-27 14:30:59 -07001515 checkManageUsersPermission("setUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001516 if (!UserRestrictionsUtils.isValidRestriction(key)) {
1517 return;
1518 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001519 synchronized (mRestrictionsLock) {
1520 // Note we can't modify Bundles stored in mBaseUserRestrictions directly, so create
1521 // a copy.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001522 final Bundle newRestrictions = UserRestrictionsUtils.clone(
1523 mBaseUserRestrictions.get(userId));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001524 newRestrictions.putBoolean(key, value);
1525
Fyodor Kupolov82402752015-10-28 14:54:51 -07001526 updateUserRestrictionsInternalLR(newRestrictions, userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001527 }
1528 }
1529
Makoto Onuki068c54a2015-10-13 14:34:03 -07001530 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001531 * Optionally updating user restrictions, calculate the effective user restrictions and also
1532 * propagate to other services and system settings.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001533 *
Pavel Grafov6a40f092016-10-25 15:46:51 +01001534 * @param newBaseRestrictions User restrictions to set.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001535 * If null, will not update user restrictions and only does the propagation.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001536 * @param userId target user ID.
1537 */
1538 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001539 private void updateUserRestrictionsInternalLR(
Pavel Grafov6a40f092016-10-25 15:46:51 +01001540 @Nullable Bundle newBaseRestrictions, int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001541 final Bundle prevAppliedRestrictions = UserRestrictionsUtils.nonNull(
1542 mAppliedUserRestrictions.get(userId));
1543
1544 // Update base restrictions.
Pavel Grafov6a40f092016-10-25 15:46:51 +01001545 if (newBaseRestrictions != null) {
1546 // If newBaseRestrictions == the current one, it's probably a bug.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001547 final Bundle prevBaseRestrictions = mBaseUserRestrictions.get(userId);
1548
Pavel Grafov6a40f092016-10-25 15:46:51 +01001549 Preconditions.checkState(prevBaseRestrictions != newBaseRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001550 Preconditions.checkState(mCachedEffectiveUserRestrictions.get(userId)
Pavel Grafov6a40f092016-10-25 15:46:51 +01001551 != newBaseRestrictions);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001552
Pavel Grafov6a40f092016-10-25 15:46:51 +01001553 if (updateRestrictionsIfNeededLR(userId, newBaseRestrictions, mBaseUserRestrictions)) {
Amith Yamasani12747872015-12-07 14:19:49 -08001554 scheduleWriteUser(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001555 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001556 }
1557
Fyodor Kupolov82402752015-10-28 14:54:51 -07001558 final Bundle effective = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001559
Makoto Onuki759a7632015-10-28 16:43:10 -07001560 mCachedEffectiveUserRestrictions.put(userId, effective);
1561
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001562 // Apply the new restrictions.
Makoto Onuki4f160732015-10-27 17:15:38 -07001563 if (DBG) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001564 debug("Applying user restrictions: userId=" + userId
1565 + " new=" + effective + " prev=" + prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001566 }
1567
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001568 if (mAppOpsService != null) { // We skip it until system-ready.
Fyodor Kupolovec30ca32016-06-16 15:09:29 -07001569 mHandler.post(new Runnable() {
1570 @Override
1571 public void run() {
1572 try {
1573 mAppOpsService.setUserRestrictions(effective, mUserRestriconToken, userId);
1574 } catch (RemoteException e) {
1575 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
1576 }
1577 }
1578 });
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001579 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001580
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001581 propagateUserRestrictionsLR(userId, effective, prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001582
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001583 mAppliedUserRestrictions.put(userId, new Bundle(effective));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001584 }
1585
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001586 private void propagateUserRestrictionsLR(final int userId,
Makoto Onukid45a4a22015-11-02 17:17:38 -08001587 Bundle newRestrictions, Bundle prevRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001588 // Note this method doesn't touch any state, meaning it doesn't require mRestrictionsLock
1589 // actually, but we still need some kind of synchronization otherwise we might end up
1590 // calling listeners out-of-order, thus "LR".
1591
1592 if (UserRestrictionsUtils.areEqual(newRestrictions, prevRestrictions)) {
1593 return;
1594 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08001595
1596 final Bundle newRestrictionsFinal = new Bundle(newRestrictions);
1597 final Bundle prevRestrictionsFinal = new Bundle(prevRestrictions);
1598
1599 mHandler.post(new Runnable() {
1600 @Override
1601 public void run() {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07001602 UserRestrictionsUtils.applyUserRestrictions(
1603 mContext, userId, newRestrictionsFinal, prevRestrictionsFinal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001604
Makoto Onukid45a4a22015-11-02 17:17:38 -08001605 final UserRestrictionsListener[] listeners;
1606 synchronized (mUserRestrictionsListeners) {
1607 listeners = new UserRestrictionsListener[mUserRestrictionsListeners.size()];
1608 mUserRestrictionsListeners.toArray(listeners);
1609 }
1610 for (int i = 0; i < listeners.length; i++) {
1611 listeners[i].onUserRestrictionsChanged(userId,
1612 newRestrictionsFinal, prevRestrictionsFinal);
1613 }
Makoto Onukie72f81b2017-03-16 14:08:19 -07001614
1615 final Intent broadcast = new Intent(UserManager.ACTION_USER_RESTRICTIONS_CHANGED)
1616 .setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
1617 mContext.sendBroadcastAsUser(broadcast, UserHandle.of(userId));
Makoto Onukid45a4a22015-11-02 17:17:38 -08001618 }
1619 });
1620 }
1621
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001622 // Package private for the inner class.
1623 void applyUserRestrictionsLR(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001624 updateUserRestrictionsInternalLR(null, userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001625 }
1626
1627 @GuardedBy("mRestrictionsLock")
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001628 // Package private for the inner class.
1629 void applyUserRestrictionsForAllUsersLR() {
1630 if (DBG) {
1631 debug("applyUserRestrictionsForAllUsersLR");
1632 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001633 // First, invalidate all cached values.
Makoto Onuki4f160732015-10-27 17:15:38 -07001634 mCachedEffectiveUserRestrictions.clear();
1635
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001636 // We don't want to call into ActivityManagerService while taking a lock, so we'll call
Makoto Onuki068c54a2015-10-13 14:34:03 -07001637 // it on a handler.
1638 final Runnable r = new Runnable() {
1639 @Override
1640 public void run() {
1641 // Then get the list of running users.
1642 final int[] runningUsers;
1643 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001644 runningUsers = ActivityManager.getService().getRunningUserIds();
Makoto Onuki068c54a2015-10-13 14:34:03 -07001645 } catch (RemoteException e) {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001646 Log.w(LOG_TAG, "Unable to access ActivityManagerService");
Makoto Onuki068c54a2015-10-13 14:34:03 -07001647 return;
1648 }
1649 // Then re-calculate the effective restrictions and apply, only for running users.
1650 // It's okay if a new user has started after the getRunningUserIds() call,
1651 // because we'll do the same thing (re-calculate the restrictions and apply)
1652 // when we start a user.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001653 synchronized (mRestrictionsLock) {
1654 for (int i = 0; i < runningUsers.length; i++) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001655 applyUserRestrictionsLR(runningUsers[i]);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001656 }
1657 }
1658 }
1659 };
1660 mHandler.post(r);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001661 }
1662
Amith Yamasani258848d2012-08-10 17:06:33 -07001663 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001664 * Check if we've hit the limit of how many users can be created.
1665 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001666 private boolean isUserLimitReached() {
1667 int count;
1668 synchronized (mUsersLock) {
1669 count = getAliveUsersExcludingGuestsCountLU();
1670 }
1671 return count >= UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001672 }
1673
1674 @Override
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001675 public boolean canAddMoreManagedProfiles(int userId, boolean allowedToRemoveOne) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001676 checkManageUsersPermission("check if more managed profiles can be added.");
1677 if (ActivityManager.isLowRamDeviceStatic()) {
1678 return false;
1679 }
Fyodor Kupolovb6157992015-06-05 15:32:28 -07001680 if (!mContext.getPackageManager().hasSystemFeature(
1681 PackageManager.FEATURE_MANAGED_USERS)) {
1682 return false;
1683 }
Nicolas Prevotb8186812015-08-06 15:00:03 +01001684 // Limit number of managed profiles that can be created
Benjamin Franzc8776152017-01-06 14:16:41 +00001685 final int managedProfilesCount = getProfiles(userId, false).size() - 1;
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001686 final int profilesRemovedCount = managedProfilesCount > 0 && allowedToRemoveOne ? 1 : 0;
Kenny Guy02c89902016-11-15 19:36:38 +00001687 if (managedProfilesCount - profilesRemovedCount >= getMaxManagedProfiles()) {
Nicolas Prevotb8186812015-08-06 15:00:03 +01001688 return false;
1689 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001690 synchronized(mUsersLock) {
1691 UserInfo userInfo = getUserInfoLU(userId);
yuanhao47f9f7c2017-01-18 09:54:45 +08001692 if (userInfo == null || !userInfo.canHaveProfile()) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001693 return false;
1694 }
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001695 int usersCountAfterRemoving = getAliveUsersExcludingGuestsCountLU()
1696 - profilesRemovedCount;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001697 // We allow creating a managed profile in the special case where there is only one user.
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001698 return usersCountAfterRemoving == 1
1699 || usersCountAfterRemoving < UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001700 }
1701 }
1702
Fyodor Kupolov82402752015-10-28 14:54:51 -07001703 private int getAliveUsersExcludingGuestsCountLU() {
Amith Yamasanif584f012014-05-19 17:57:25 -07001704 int aliveUserCount = 0;
1705 final int totalUserCount = mUsers.size();
1706 // Skip over users being removed
1707 for (int i = 0; i < totalUserCount; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001708 UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov6e99d3f2016-11-01 17:18:41 -07001709 if (!mRemovingUserIds.get(user.id) && !user.isGuest()) {
Amith Yamasanif584f012014-05-19 17:57:25 -07001710 aliveUserCount++;
1711 }
1712 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001713 return aliveUserCount;
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001714 }
1715
1716 /**
Amith Yamasani195263742012-08-21 15:40:12 -07001717 * Enforces that only the system UID or root's UID or apps that have the
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001718 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} and
1719 * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL INTERACT_ACROSS_USERS_FULL}
1720 * permissions can make certain calls to the UserManager.
1721 *
1722 * @param message used as message if SecurityException is thrown
1723 * @throws SecurityException if the caller does not have enough privilege.
1724 */
1725 private static final void checkManageUserAndAcrossUsersFullPermission(String message) {
1726 final int uid = Binder.getCallingUid();
1727 if (uid != Process.SYSTEM_UID && uid != 0
1728 && ActivityManager.checkComponentPermission(
1729 Manifest.permission.MANAGE_USERS,
1730 uid, -1, true) != PackageManager.PERMISSION_GRANTED
1731 && ActivityManager.checkComponentPermission(
1732 Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1733 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
1734 throw new SecurityException(
1735 "You need MANAGE_USERS and INTERACT_ACROSS_USERS_FULL permission to: "
1736 + message);
1737 }
1738 }
1739
1740 /**
1741 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001742 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -07001743 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -07001744 *
1745 * @param message used as message if SecurityException is thrown
1746 * @throws SecurityException if the caller is not system or root
Tony Mak4dc008c2016-03-16 10:46:49 +00001747 * @see #hasManageUsersPermission()
Amith Yamasani258848d2012-08-10 17:06:33 -07001748 */
Amith Yamasanibe465322014-04-24 13:45:17 -07001749 private static final void checkManageUsersPermission(String message) {
Tony Mak4dc008c2016-03-16 10:46:49 +00001750 if (!hasManageUsersPermission()) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001751 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
1752 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -04001753 }
1754
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001755 /**
Sudheer Shankaf5cea032016-06-08 17:13:24 -07001756 * Enforces that only the system UID or root's UID or apps that have the
1757 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or
1758 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS}
1759 * can make certain calls to the UserManager.
1760 *
1761 * @param message used as message if SecurityException is thrown
1762 * @throws SecurityException if the caller is not system or root
1763 * @see #hasManageOrCreateUsersPermission()
1764 */
1765 private static final void checkManageOrCreateUsersPermission(String message) {
1766 if (!hasManageOrCreateUsersPermission()) {
1767 throw new SecurityException(
1768 "You either need MANAGE_USERS or CREATE_USERS permission to: " + message);
1769 }
1770 }
1771
1772 /**
1773 * Similar to {@link #checkManageOrCreateUsersPermission(String)} but when the caller is tries
1774 * to create user/profiles other than what is allowed for
1775 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS} permission, then it will only
1776 * allow callers with {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} permission.
1777 */
1778 private static final void checkManageOrCreateUsersPermission(int creationFlags) {
1779 if ((creationFlags & ~ALLOWED_FLAGS_FOR_CREATE_USERS_PERMISSION) == 0) {
1780 if (!hasManageOrCreateUsersPermission()) {
1781 throw new SecurityException("You either need MANAGE_USERS or CREATE_USERS "
1782 + "permission to create an user with flags: " + creationFlags);
1783 }
1784 } else if (!hasManageUsersPermission()) {
1785 throw new SecurityException("You need MANAGE_USERS permission to create an user "
1786 + " with flags: " + creationFlags);
1787 }
1788 }
1789
1790 /**
Tony Mak4dc008c2016-03-16 10:46:49 +00001791 * @return whether the calling UID is system UID or root's UID or the calling app has the
1792 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}.
1793 */
1794 private static final boolean hasManageUsersPermission() {
1795 final int callingUid = Binder.getCallingUid();
1796 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
1797 || callingUid == Process.ROOT_UID
1798 || ActivityManager.checkComponentPermission(
1799 android.Manifest.permission.MANAGE_USERS,
1800 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED;
1801 }
1802
1803 /**
Sudheer Shankaf5cea032016-06-08 17:13:24 -07001804 * @return whether the calling UID is system UID or root's UID or the calling app has the
1805 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or
1806 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS}.
1807 */
1808 private static final boolean hasManageOrCreateUsersPermission() {
1809 final int callingUid = Binder.getCallingUid();
1810 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
1811 || callingUid == Process.ROOT_UID
1812 || ActivityManager.checkComponentPermission(
1813 android.Manifest.permission.MANAGE_USERS,
1814 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED
1815 || ActivityManager.checkComponentPermission(
1816 android.Manifest.permission.CREATE_USERS,
1817 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED;
1818 }
1819
1820 /**
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001821 * Enforces that only the system UID or root's UID (on any user) can make certain calls to the
1822 * UserManager.
1823 *
1824 * @param message used as message if SecurityException is thrown
1825 * @throws SecurityException if the caller is not system or root
1826 */
1827 private static void checkSystemOrRoot(String message) {
1828 final int uid = Binder.getCallingUid();
1829 if (!UserHandle.isSameApp(uid, Process.SYSTEM_UID) && uid != Process.ROOT_UID) {
1830 throw new SecurityException("Only system may: " + message);
1831 }
1832 }
1833
Fyodor Kupolov82402752015-10-28 14:54:51 -07001834 private void writeBitmapLP(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001835 try {
1836 File dir = new File(mUsersDir, Integer.toString(info.id));
1837 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +01001838 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001839 if (!dir.exists()) {
1840 dir.mkdir();
1841 FileUtils.setPermissions(
1842 dir.getPath(),
1843 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
1844 -1, -1);
1845 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001846 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +01001847 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001848 && tmp.renameTo(file) && SELinux.restorecon(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -07001849 info.iconPath = file.getAbsolutePath();
1850 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001851 try {
1852 os.close();
1853 } catch (IOException ioe) {
1854 // What the ... !
1855 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001856 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001857 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001858 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001859 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001860 }
1861
Amith Yamasani0b285492011-04-14 17:35:23 -07001862 /**
1863 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
1864 * cache it elsewhere.
1865 * @return the array of user ids.
1866 */
Dianne Hackborn1676c852012-09-10 14:52:30 -07001867 public int[] getUserIds() {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001868 synchronized (mUsersLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001869 return mUserIds;
1870 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001871 }
1872
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001873 private void readUserListLP() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001874 if (!mUserListFile.exists()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001875 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001876 return;
1877 }
1878 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001879 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001880 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001881 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001882 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001883 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001884 int type;
1885 while ((type = parser.next()) != XmlPullParser.START_TAG
1886 && type != XmlPullParser.END_DOCUMENT) {
Amith Yamasani12747872015-12-07 14:19:49 -08001887 // Skip
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001888 }
1889
1890 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001891 Slog.e(LOG_TAG, "Unable to read user list");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001892 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001893 return;
1894 }
1895
Amith Yamasani2a003292012-08-14 18:25:45 -07001896 mNextSerialNumber = -1;
1897 if (parser.getName().equals(TAG_USERS)) {
1898 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
1899 if (lastSerialNumber != null) {
1900 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
1901 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001902 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
1903 if (versionNumber != null) {
1904 mUserVersion = Integer.parseInt(versionNumber);
1905 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001906 }
1907
Pavel Grafov6a40f092016-10-25 15:46:51 +01001908 // Pre-O global user restriction were stored as a single bundle (as opposed to per-user
1909 // currently), take care of it in case of upgrade.
1910 Bundle oldDevicePolicyGlobalUserRestrictions = null;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001911
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001912 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301913 if (type == XmlPullParser.START_TAG) {
1914 final String name = parser.getName();
1915 if (name.equals(TAG_USER)) {
1916 String id = parser.getAttributeValue(null, ATTR_ID);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001917
Amith Yamasani12747872015-12-07 14:19:49 -08001918 UserData userData = readUserLP(Integer.parseInt(id));
1919
1920 if (userData != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001921 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001922 mUsers.put(userData.info.id, userData);
1923 if (mNextSerialNumber < 0
1924 || mNextSerialNumber <= userData.info.id) {
1925 mNextSerialNumber = userData.info.id + 1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001926 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301927 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001928 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301929 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -08001930 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1931 && type != XmlPullParser.END_TAG) {
1932 if (type == XmlPullParser.START_TAG) {
1933 if (parser.getName().equals(TAG_RESTRICTIONS)) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001934 synchronized (mGuestRestrictions) {
Fyodor Kupoloveafee022017-03-15 17:09:04 -07001935 UserRestrictionsUtils
1936 .readRestrictions(parser, mGuestRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001937 }
Amith Yamasanida0b1682014-11-21 12:58:17 -08001938 }
1939 break;
1940 }
1941 }
Pavel Grafov6a40f092016-10-25 15:46:51 +01001942 } else if (name.equals(TAG_DEVICE_OWNER_USER_ID)
1943 // Legacy name, should only be encountered when upgrading from pre-O.
1944 || name.equals(TAG_GLOBAL_RESTRICTION_OWNER_ID)) {
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001945 String ownerUserId = parser.getAttributeValue(null, ATTR_ID);
1946 if (ownerUserId != null) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001947 mDeviceOwnerUserId = Integer.parseInt(ownerUserId);
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001948 }
Pavel Grafov6a40f092016-10-25 15:46:51 +01001949 } else if (name.equals(TAG_DEVICE_POLICY_RESTRICTIONS)) {
1950 // Should only happen when upgrading from pre-O (version < 7).
1951 oldDevicePolicyGlobalUserRestrictions =
1952 UserRestrictionsUtils.readRestrictions(parser);
Amith Yamasani258848d2012-08-10 17:06:33 -07001953 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001954 }
1955 }
Pavel Grafov6a40f092016-10-25 15:46:51 +01001956
Fyodor Kupolov82402752015-10-28 14:54:51 -07001957 updateUserIds();
Pavel Grafov6a40f092016-10-25 15:46:51 +01001958 upgradeIfNecessaryLP(oldDevicePolicyGlobalUserRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001959 } catch (IOException | XmlPullParserException e) {
1960 fallbackToSingleUserLP();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001961 } finally {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001962 IoUtils.closeQuietly(fis);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001963 }
1964 }
1965
Amith Yamasani6f34b412012-10-22 18:19:27 -07001966 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -08001967 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Pavel Grafov6a40f092016-10-25 15:46:51 +01001968 * @param oldGlobalUserRestrictions Pre-O global device policy restrictions.
Amith Yamasani6f34b412012-10-22 18:19:27 -07001969 */
Pavel Grafov6a40f092016-10-25 15:46:51 +01001970 private void upgradeIfNecessaryLP(Bundle oldGlobalUserRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001971 final int originalVersion = mUserVersion;
Amith Yamasani6f34b412012-10-22 18:19:27 -07001972 int userVersion = mUserVersion;
1973 if (userVersion < 1) {
1974 // Assign a proper name for the owner, if not initialized correctly before
Amith Yamasani12747872015-12-07 14:19:49 -08001975 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
1976 if ("Primary".equals(userData.info.name)) {
1977 userData.info.name =
1978 mContext.getResources().getString(com.android.internal.R.string.owner_name);
1979 scheduleWriteUser(userData);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001980 }
1981 userVersion = 1;
1982 }
1983
Amith Yamasanibc9625052012-11-15 14:39:18 -08001984 if (userVersion < 2) {
1985 // Owner should be marked as initialized
Amith Yamasani12747872015-12-07 14:19:49 -08001986 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
1987 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1988 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
1989 scheduleWriteUser(userData);
Amith Yamasanibc9625052012-11-15 14:39:18 -08001990 }
1991 userVersion = 2;
1992 }
1993
Amith Yamasani350962c2013-08-06 11:18:53 -07001994
Amith Yamasani5e486f52013-08-07 11:06:44 -07001995 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -07001996 userVersion = 4;
1997 }
1998
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001999 if (userVersion < 5) {
2000 initDefaultGuestRestrictions();
2001 userVersion = 5;
2002 }
2003
Fyodor Kupolov1c363152015-09-02 13:27:21 -07002004 if (userVersion < 6) {
2005 final boolean splitSystemUser = UserManager.isSplitSystemUser();
Fyodor Kupolov82402752015-10-28 14:54:51 -07002006 synchronized (mUsersLock) {
2007 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002008 UserData userData = mUsers.valueAt(i);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002009 // In non-split mode, only user 0 can have restricted profiles
Amith Yamasani12747872015-12-07 14:19:49 -08002010 if (!splitSystemUser && userData.info.isRestricted()
2011 && (userData.info.restrictedProfileParentId
2012 == UserInfo.NO_PROFILE_GROUP_ID)) {
2013 userData.info.restrictedProfileParentId = UserHandle.USER_SYSTEM;
2014 scheduleWriteUser(userData);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002015 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07002016 }
2017 }
2018 userVersion = 6;
2019 }
2020
Pavel Grafov6a40f092016-10-25 15:46:51 +01002021 if (userVersion < 7) {
2022 // Previously only one user could enforce global restrictions, now it is per-user.
2023 synchronized (mRestrictionsLock) {
2024 if (!UserRestrictionsUtils.isEmpty(oldGlobalUserRestrictions)
2025 && mDeviceOwnerUserId != UserHandle.USER_NULL) {
2026 mDevicePolicyGlobalUserRestrictions.put(
2027 mDeviceOwnerUserId, oldGlobalUserRestrictions);
2028 }
2029 // ENSURE_VERIFY_APPS is now enforced globally even if put by profile owner, so move
2030 // it from local to global bundle for all users who set it.
2031 UserRestrictionsUtils.moveRestriction(UserManager.ENSURE_VERIFY_APPS,
2032 mDevicePolicyLocalUserRestrictions, mDevicePolicyGlobalUserRestrictions
2033 );
2034 }
2035 userVersion = 7;
2036 }
2037
Amith Yamasani6f34b412012-10-22 18:19:27 -07002038 if (userVersion < USER_VERSION) {
2039 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
2040 + USER_VERSION);
2041 } else {
2042 mUserVersion = userVersion;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002043
2044 if (originalVersion < mUserVersion) {
2045 writeUserListLP();
2046 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07002047 }
2048 }
2049
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002050 private void fallbackToSingleUserLP() {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07002051 int flags = UserInfo.FLAG_INITIALIZED;
2052 // In split system user mode, the admin and primary flags are assigned to the first human
2053 // user.
2054 if (!UserManager.isSplitSystemUser()) {
2055 flags |= UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY;
2056 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -07002057 // Create the system user
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07002058 UserInfo system = new UserInfo(UserHandle.USER_SYSTEM, null, null, flags);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002059 UserData userData = putUserInfo(system);
Amith Yamasani634cf312012-10-04 17:34:21 -07002060 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -04002061 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -08002062
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05002063 Bundle restrictions = new Bundle();
Mahaver Chopra3d9805d2016-07-07 16:25:05 +01002064 try {
2065 final String[] defaultFirstUserRestrictions = mContext.getResources().getStringArray(
2066 com.android.internal.R.array.config_defaultFirstUserRestrictions);
2067 for (String userRestriction : defaultFirstUserRestrictions) {
2068 if (UserRestrictionsUtils.isValidRestriction(userRestriction)) {
2069 restrictions.putBoolean(userRestriction, true);
2070 }
2071 }
2072 } catch (Resources.NotFoundException e) {
2073 Log.e(LOG_TAG, "Couldn't find resource: config_defaultFirstUserRestrictions", e);
2074 }
2075
Pavel Grafov6a40f092016-10-25 15:46:51 +01002076 if (!restrictions.isEmpty()) {
2077 synchronized (mRestrictionsLock) {
2078 mBaseUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions);
2079 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07002080 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08002081
Fyodor Kupolov82402752015-10-28 14:54:51 -07002082 updateUserIds();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07002083 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002084
Amith Yamasani12747872015-12-07 14:19:49 -08002085 writeUserLP(userData);
Jeff Sharkeycd575992016-03-29 14:12:49 -06002086 writeUserListLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002087 }
2088
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07002089 private String getOwnerName() {
2090 return mContext.getResources().getString(com.android.internal.R.string.owner_name);
2091 }
2092
Amith Yamasani12747872015-12-07 14:19:49 -08002093 private void scheduleWriteUser(UserData UserData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002094 if (DBG) {
2095 debug("scheduleWriteUser");
2096 }
Makoto Onuki9e935a32015-11-06 14:24:24 -08002097 // No need to wrap it within a lock -- worst case, we'll just post the same message
2098 // twice.
Amith Yamasani12747872015-12-07 14:19:49 -08002099 if (!mHandler.hasMessages(WRITE_USER_MSG, UserData)) {
2100 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, UserData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002101 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
2102 }
2103 }
2104
Amith Yamasani12747872015-12-07 14:19:49 -08002105 private void writeUserLP(UserData userData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002106 if (DBG) {
Amith Yamasani12747872015-12-07 14:19:49 -08002107 debug("writeUserLP " + userData);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002108 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002109 FileOutputStream fos = null;
Amith Yamasani12747872015-12-07 14:19:49 -08002110 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userData.info.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002111 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07002112 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002113 final BufferedOutputStream bos = new BufferedOutputStream(fos);
Kenny Guy02c89902016-11-15 19:36:38 +00002114 writeUserLP(userData, bos);
Amith Yamasani2a003292012-08-14 18:25:45 -07002115 userFile.finishWrite(fos);
2116 } catch (Exception ioe) {
Jeff Sharkeycd575992016-03-29 14:12:49 -06002117 Slog.e(LOG_TAG, "Error writing user info " + userData.info.id, ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -07002118 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002119 }
2120 }
2121
2122 /*
Kenny Guy02c89902016-11-15 19:36:38 +00002123 * Writes the user file in this format:
2124 *
2125 * <user flags="20039023" id="0">
2126 * <name>Primary</name>
2127 * </user>
2128 */
2129 @VisibleForTesting
2130 void writeUserLP(UserData userData, OutputStream os)
2131 throws IOException, XmlPullParserException {
2132 // XmlSerializer serializer = XmlUtils.serializerInstance();
2133 final XmlSerializer serializer = new FastXmlSerializer();
2134 serializer.setOutput(os, StandardCharsets.UTF_8.name());
2135 serializer.startDocument(null, true);
2136 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2137
2138 final UserInfo userInfo = userData.info;
2139 serializer.startTag(null, TAG_USER);
2140 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
2141 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
2142 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
2143 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
2144 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
2145 Long.toString(userInfo.lastLoggedInTime));
2146 if (userInfo.lastLoggedInFingerprint != null) {
2147 serializer.attribute(null, ATTR_LAST_LOGGED_IN_FINGERPRINT,
2148 userInfo.lastLoggedInFingerprint);
2149 }
2150 if (userInfo.iconPath != null) {
2151 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
2152 }
2153 if (userInfo.partial) {
2154 serializer.attribute(null, ATTR_PARTIAL, "true");
2155 }
2156 if (userInfo.guestToRemove) {
2157 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
2158 }
2159 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
2160 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
2161 Integer.toString(userInfo.profileGroupId));
2162 }
2163 serializer.attribute(null, ATTR_PROFILE_BADGE,
2164 Integer.toString(userInfo.profileBadge));
2165 if (userInfo.restrictedProfileParentId != UserInfo.NO_PROFILE_GROUP_ID) {
2166 serializer.attribute(null, ATTR_RESTRICTED_PROFILE_PARENT_ID,
2167 Integer.toString(userInfo.restrictedProfileParentId));
2168 }
2169 // Write seed data
2170 if (userData.persistSeedData) {
2171 if (userData.seedAccountName != null) {
2172 serializer.attribute(null, ATTR_SEED_ACCOUNT_NAME, userData.seedAccountName);
2173 }
2174 if (userData.seedAccountType != null) {
2175 serializer.attribute(null, ATTR_SEED_ACCOUNT_TYPE, userData.seedAccountType);
2176 }
2177 }
2178 if (userInfo.name != null) {
2179 serializer.startTag(null, TAG_NAME);
2180 serializer.text(userInfo.name);
2181 serializer.endTag(null, TAG_NAME);
2182 }
2183 synchronized (mRestrictionsLock) {
2184 UserRestrictionsUtils.writeRestrictions(serializer,
2185 mBaseUserRestrictions.get(userInfo.id), TAG_RESTRICTIONS);
2186 UserRestrictionsUtils.writeRestrictions(serializer,
2187 mDevicePolicyLocalUserRestrictions.get(userInfo.id),
2188 TAG_DEVICE_POLICY_RESTRICTIONS);
Pavel Grafov6a40f092016-10-25 15:46:51 +01002189 UserRestrictionsUtils.writeRestrictions(serializer,
2190 mDevicePolicyGlobalUserRestrictions.get(userInfo.id),
2191 TAG_DEVICE_POLICY_GLOBAL_RESTRICTIONS);
Kenny Guy02c89902016-11-15 19:36:38 +00002192 }
2193
2194 if (userData.account != null) {
2195 serializer.startTag(null, TAG_ACCOUNT);
2196 serializer.text(userData.account);
2197 serializer.endTag(null, TAG_ACCOUNT);
2198 }
2199
2200 if (userData.persistSeedData && userData.seedAccountOptions != null) {
2201 serializer.startTag(null, TAG_SEED_ACCOUNT_OPTIONS);
2202 userData.seedAccountOptions.saveToXml(serializer);
2203 serializer.endTag(null, TAG_SEED_ACCOUNT_OPTIONS);
2204 }
2205
2206 serializer.endTag(null, TAG_USER);
2207
2208 serializer.endDocument();
2209 }
2210
2211 /*
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002212 * Writes the user list file in this format:
2213 *
Amith Yamasani2a003292012-08-14 18:25:45 -07002214 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002215 * <user id="0"></user>
2216 * <user id="2"></user>
2217 * </users>
2218 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002219 private void writeUserListLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002220 if (DBG) {
2221 debug("writeUserList");
2222 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002223 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07002224 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002225 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07002226 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002227 final BufferedOutputStream bos = new BufferedOutputStream(fos);
2228
2229 // XmlSerializer serializer = XmlUtils.serializerInstance();
2230 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002231 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002232 serializer.startDocument(null, true);
2233 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2234
2235 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -07002236 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -07002237 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002238
Adam Lesinskieddeb492014-09-08 17:50:03 -07002239 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002240 synchronized (mGuestRestrictions) {
2241 UserRestrictionsUtils
2242 .writeRestrictions(serializer, mGuestRestrictions, TAG_RESTRICTIONS);
2243 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05302244 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Pavel Grafov6a40f092016-10-25 15:46:51 +01002245 serializer.startTag(null, TAG_DEVICE_OWNER_USER_ID);
2246 serializer.attribute(null, ATTR_ID, Integer.toString(mDeviceOwnerUserId));
2247 serializer.endTag(null, TAG_DEVICE_OWNER_USER_ID);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002248 int[] userIdsToWrite;
2249 synchronized (mUsersLock) {
2250 userIdsToWrite = new int[mUsers.size()];
2251 for (int i = 0; i < userIdsToWrite.length; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002252 UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002253 userIdsToWrite[i] = user.id;
2254 }
2255 }
2256 for (int id : userIdsToWrite) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002257 serializer.startTag(null, TAG_USER);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002258 serializer.attribute(null, ATTR_ID, Integer.toString(id));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002259 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002260 }
2261
2262 serializer.endTag(null, TAG_USERS);
2263
2264 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07002265 userListFile.finishWrite(fos);
2266 } catch (Exception e) {
2267 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -07002268 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002269 }
2270 }
2271
Amith Yamasani12747872015-12-07 14:19:49 -08002272 private UserData readUserLP(int id) {
Kenny Guy02c89902016-11-15 19:36:38 +00002273 FileInputStream fis = null;
2274 try {
2275 AtomicFile userFile =
2276 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
2277 fis = userFile.openRead();
2278 return readUserLP(id, fis);
2279 } catch (IOException ioe) {
2280 Slog.e(LOG_TAG, "Error reading user list");
2281 } catch (XmlPullParserException pe) {
2282 Slog.e(LOG_TAG, "Error reading user list");
2283 } finally {
2284 IoUtils.closeQuietly(fis);
2285 }
2286 return null;
2287 }
2288
2289 @VisibleForTesting
2290 UserData readUserLP(int id, InputStream is) throws IOException,
2291 XmlPullParserException {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002292 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -07002293 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002294 String name = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -08002295 String account = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002296 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -07002297 long creationTime = 0L;
2298 long lastLoggedInTime = 0L;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002299 String lastLoggedInFingerprint = null;
Kenny Guy2a764942014-04-02 13:29:20 +01002300 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Kenny Guy02c89902016-11-15 19:36:38 +00002301 int profileBadge = 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002302 int restrictedProfileParentId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002303 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -07002304 boolean guestToRemove = false;
Amith Yamasani12747872015-12-07 14:19:49 -08002305 boolean persistSeedData = false;
2306 String seedAccountName = null;
2307 String seedAccountType = null;
2308 PersistableBundle seedAccountOptions = null;
Pavel Grafov6a40f092016-10-25 15:46:51 +01002309 Bundle baseRestrictions = null;
2310 Bundle localRestrictions = null;
2311 Bundle globalRestrictions = null;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002312
Kenny Guy02c89902016-11-15 19:36:38 +00002313 XmlPullParser parser = Xml.newPullParser();
2314 parser.setInput(is, StandardCharsets.UTF_8.name());
2315 int type;
2316 while ((type = parser.next()) != XmlPullParser.START_TAG
2317 && type != XmlPullParser.END_DOCUMENT) {
2318 // Skip
2319 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002320
Kenny Guy02c89902016-11-15 19:36:38 +00002321 if (type != XmlPullParser.START_TAG) {
2322 Slog.e(LOG_TAG, "Unable to read user " + id);
2323 return null;
2324 }
2325
2326 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
2327 int storedId = readIntAttribute(parser, ATTR_ID, -1);
2328 if (storedId != id) {
2329 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002330 return null;
2331 }
Kenny Guy02c89902016-11-15 19:36:38 +00002332 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
2333 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
2334 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
2335 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
2336 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
2337 lastLoggedInFingerprint = parser.getAttributeValue(null,
2338 ATTR_LAST_LOGGED_IN_FINGERPRINT);
2339 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
2340 UserInfo.NO_PROFILE_GROUP_ID);
2341 profileBadge = readIntAttribute(parser, ATTR_PROFILE_BADGE, 0);
2342 restrictedProfileParentId = readIntAttribute(parser,
2343 ATTR_RESTRICTED_PROFILE_PARENT_ID, UserInfo.NO_PROFILE_GROUP_ID);
2344 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
2345 if ("true".equals(valueString)) {
2346 partial = true;
2347 }
2348 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
2349 if ("true".equals(valueString)) {
2350 guestToRemove = true;
2351 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002352
Kenny Guy02c89902016-11-15 19:36:38 +00002353 seedAccountName = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_NAME);
2354 seedAccountType = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_TYPE);
2355 if (seedAccountName != null || seedAccountType != null) {
2356 persistSeedData = true;
2357 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002358
Kenny Guy02c89902016-11-15 19:36:38 +00002359 int outerDepth = parser.getDepth();
2360 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2361 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2362 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2363 continue;
2364 }
2365 String tag = parser.getName();
2366 if (TAG_NAME.equals(tag)) {
2367 type = parser.next();
2368 if (type == XmlPullParser.TEXT) {
2369 name = parser.getText();
2370 }
2371 } else if (TAG_RESTRICTIONS.equals(tag)) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01002372 baseRestrictions = UserRestrictionsUtils.readRestrictions(parser);
Kenny Guy02c89902016-11-15 19:36:38 +00002373 } else if (TAG_DEVICE_POLICY_RESTRICTIONS.equals(tag)) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01002374 localRestrictions = UserRestrictionsUtils.readRestrictions(parser);
2375 } else if (TAG_DEVICE_POLICY_GLOBAL_RESTRICTIONS.equals(tag)) {
2376 globalRestrictions = UserRestrictionsUtils.readRestrictions(parser);
Kenny Guy02c89902016-11-15 19:36:38 +00002377 } else if (TAG_ACCOUNT.equals(tag)) {
2378 type = parser.next();
2379 if (type == XmlPullParser.TEXT) {
2380 account = parser.getText();
2381 }
2382 } else if (TAG_SEED_ACCOUNT_OPTIONS.equals(tag)) {
2383 seedAccountOptions = PersistableBundle.restoreFromXml(parser);
Amith Yamasani12747872015-12-07 14:19:49 -08002384 persistSeedData = true;
2385 }
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08002386 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002387 }
Kenny Guy02c89902016-11-15 19:36:38 +00002388
2389 // Create the UserInfo object that gets passed around
2390 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
2391 userInfo.serialNumber = serialNumber;
2392 userInfo.creationTime = creationTime;
2393 userInfo.lastLoggedInTime = lastLoggedInTime;
2394 userInfo.lastLoggedInFingerprint = lastLoggedInFingerprint;
2395 userInfo.partial = partial;
2396 userInfo.guestToRemove = guestToRemove;
2397 userInfo.profileGroupId = profileGroupId;
2398 userInfo.profileBadge = profileBadge;
2399 userInfo.restrictedProfileParentId = restrictedProfileParentId;
2400
2401 // Create the UserData object that's internal to this class
2402 UserData userData = new UserData();
2403 userData.info = userInfo;
2404 userData.account = account;
2405 userData.seedAccountName = seedAccountName;
2406 userData.seedAccountType = seedAccountType;
2407 userData.persistSeedData = persistSeedData;
2408 userData.seedAccountOptions = seedAccountOptions;
2409
2410 synchronized (mRestrictionsLock) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01002411 if (baseRestrictions != null) {
2412 mBaseUserRestrictions.put(id, baseRestrictions);
2413 }
2414 if (localRestrictions != null) {
2415 mDevicePolicyLocalUserRestrictions.put(id, localRestrictions);
2416 }
2417 if (globalRestrictions != null) {
2418 mDevicePolicyGlobalUserRestrictions.put(id, globalRestrictions);
2419 }
Kenny Guy02c89902016-11-15 19:36:38 +00002420 }
2421 return userData;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002422 }
2423
Amith Yamasani920ace02012-09-20 22:15:37 -07002424 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
2425 String valueString = parser.getAttributeValue(null, attr);
2426 if (valueString == null) return defaultValue;
2427 try {
2428 return Integer.parseInt(valueString);
2429 } catch (NumberFormatException nfe) {
2430 return defaultValue;
2431 }
2432 }
2433
2434 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
2435 String valueString = parser.getAttributeValue(null, attr);
2436 if (valueString == null) return defaultValue;
2437 try {
2438 return Long.parseLong(valueString);
2439 } catch (NumberFormatException nfe) {
2440 return defaultValue;
2441 }
2442 }
2443
Amith Yamasanib82add22013-07-09 11:24:44 -07002444 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002445 * Removes the app restrictions file for a specific package and user id, if it exists.
2446 */
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07002447 private static void cleanAppRestrictionsForPackageLAr(String pkg, int userId) {
2448 File dir = Environment.getUserSystemDirectory(userId);
2449 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
2450 if (resFile.exists()) {
2451 resFile.delete();
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002452 }
2453 }
2454
Kenny Guya52dc3e2014-02-11 15:33:14 +00002455 @Override
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002456 public UserInfo createProfileForUser(String name, int flags, int userId,
2457 String[] disallowedPackages) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002458 checkManageOrCreateUsersPermission(flags);
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002459 return createUserInternal(name, flags, userId, disallowedPackages);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002460 }
2461
Amith Yamasani258848d2012-08-10 17:06:33 -07002462 @Override
Tony Mak6dc428f2016-10-10 15:48:27 +01002463 public UserInfo createProfileForUserEvenWhenDisallowed(String name, int flags, int userId,
2464 String[] disallowedPackages) {
2465 checkManageOrCreateUsersPermission(flags);
2466 return createUserInternalUnchecked(name, flags, userId, disallowedPackages);
2467 }
2468
2469 @Override
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00002470 public boolean removeUserEvenWhenDisallowed(@UserIdInt int userHandle) {
2471 checkManageOrCreateUsersPermission("Only the system can remove users");
2472 return removeUserUnchecked(userHandle);
2473 }
2474
2475 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07002476 public UserInfo createUser(String name, int flags) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002477 checkManageOrCreateUsersPermission(flags);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00002478 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002479 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07002480
Jessica Hummelbe81c802014-04-22 15:49:22 +01002481 private UserInfo createUserInternal(String name, int flags, int parentId) {
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002482 return createUserInternal(name, flags, parentId, null);
2483 }
2484
2485 private UserInfo createUserInternal(String name, int flags, int parentId,
2486 String[] disallowedPackages) {
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002487 String restriction = ((flags & UserInfo.FLAG_MANAGED_PROFILE) != 0)
2488 ? UserManager.DISALLOW_ADD_MANAGED_PROFILE
2489 : UserManager.DISALLOW_ADD_USER;
2490 if (hasUserRestriction(restriction, UserHandle.getCallingUserId())) {
2491 Log.w(LOG_TAG, "Cannot add user. " + restriction + " is enabled.");
Julia Reynolds75175022014-06-26 16:35:00 -04002492 return null;
2493 }
Tony Mak6dc428f2016-10-10 15:48:27 +01002494 return createUserInternalUnchecked(name, flags, parentId, disallowedPackages);
2495 }
2496
2497 private UserInfo createUserInternalUnchecked(String name, int flags, int parentId,
2498 String[] disallowedPackages) {
Suprabh Shuklac5e057c2016-08-08 16:22:44 -07002499 DeviceStorageMonitorInternal dsm = LocalServices
2500 .getService(DeviceStorageMonitorInternal.class);
2501 if (dsm.isMemoryLow()) {
2502 Log.w(LOG_TAG, "Cannot add user. Not enough space on disk.");
2503 return null;
2504 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07002505 if (ActivityManager.isLowRamDeviceStatic()) {
2506 return null;
2507 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07002508 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Nicolas Prevot12678a92015-05-13 12:15:03 -07002509 final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002510 final boolean isRestricted = (flags & UserInfo.FLAG_RESTRICTED) != 0;
Amith Yamasani52c21e32016-05-31 09:12:20 -07002511 final boolean isDemo = (flags & UserInfo.FLAG_DEMO) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002512 final long ident = Binder.clearCallingIdentity();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002513 UserInfo userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08002514 UserData userData;
Amith Yamasanibb054c92015-07-09 14:16:27 -07002515 final int userId;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002516 try {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002517 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002518 UserData parent = null;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002519 if (parentId != UserHandle.USER_NULL) {
2520 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002521 parent = getUserDataLU(parentId);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00002522 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002523 if (parent == null) return null;
2524 }
2525 if (isManagedProfile && !canAddMoreManagedProfiles(parentId, false)) {
2526 Log.e(LOG_TAG, "Cannot add more managed profiles for user " + parentId);
2527 return null;
2528 }
Amith Yamasani52c21e32016-05-31 09:12:20 -07002529 if (!isGuest && !isManagedProfile && !isDemo && isUserLimitReached()) {
2530 // If we're not adding a guest/demo user or a managed profile and the limit has
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002531 // been reached, cannot add a user.
2532 return null;
2533 }
2534 // If we're adding a guest and there already exists one, bail.
2535 if (isGuest && findCurrentGuestUser() != null) {
2536 return null;
2537 }
2538 // In legacy mode, restricted profile's parent can only be the owner user
2539 if (isRestricted && !UserManager.isSplitSystemUser()
2540 && (parentId != UserHandle.USER_SYSTEM)) {
2541 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
2542 return null;
2543 }
2544 if (isRestricted && UserManager.isSplitSystemUser()) {
2545 if (parent == null) {
2546 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be "
2547 + "specified");
Nicolas Prevot12678a92015-05-13 12:15:03 -07002548 return null;
2549 }
Amith Yamasani12747872015-12-07 14:19:49 -08002550 if (!parent.info.canHaveProfile()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002551 Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be "
2552 + "created for the specified parent user id " + parentId);
Amith Yamasani95ab7842014-08-11 17:09:26 -07002553 return null;
2554 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002555 }
2556 // In split system user mode, we assign the first human user the primary flag.
2557 // And if there is no device owner, we also assign the admin flag to primary user.
2558 if (UserManager.isSplitSystemUser()
2559 && !isGuest && !isManagedProfile && getPrimaryUser() == null) {
2560 flags |= UserInfo.FLAG_PRIMARY;
Makoto Onukie7927da2015-11-25 10:05:17 -08002561 synchronized (mUsersLock) {
2562 if (!mIsDeviceManaged) {
2563 flags |= UserInfo.FLAG_ADMIN;
2564 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07002565 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002566 }
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002567
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002568 userId = getNextAvailableId();
2569 Environment.getUserSystemDirectory(userId).mkdirs();
Lenka Trochtova02fee152015-12-22 14:26:18 +01002570 boolean ephemeralGuests = Resources.getSystem()
2571 .getBoolean(com.android.internal.R.bool.config_guestUserEphemeral);
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002572
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002573 synchronized (mUsersLock) {
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002574 // Add ephemeral flag to guests/users if required. Also inherit it from parent.
2575 if ((isGuest && ephemeralGuests) || mForceEphemeralUsers
2576 || (parent != null && parent.info.isEphemeral())) {
2577 flags |= UserInfo.FLAG_EPHEMERAL;
2578 }
2579
2580 userInfo = new UserInfo(userId, name, null, flags);
2581 userInfo.serialNumber = mNextSerialNumber++;
2582 long now = System.currentTimeMillis();
2583 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
2584 userInfo.partial = true;
Fyodor Kupolov83c24242016-03-31 13:30:42 -07002585 userInfo.lastLoggedInFingerprint = Build.FINGERPRINT;
Kenny Guy02c89902016-11-15 19:36:38 +00002586 if (isManagedProfile && parentId != UserHandle.USER_NULL) {
2587 userInfo.profileBadge = getFreeProfileBadgeLU(parentId);
2588 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002589 userData = new UserData();
2590 userData.info = userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08002591 mUsers.put(userId, userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002592 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06002593 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002594 writeUserListLP();
2595 if (parent != null) {
2596 if (isManagedProfile) {
Amith Yamasani12747872015-12-07 14:19:49 -08002597 if (parent.info.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
2598 parent.info.profileGroupId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002599 writeUserLP(parent);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002600 }
Amith Yamasani12747872015-12-07 14:19:49 -08002601 userInfo.profileGroupId = parent.info.profileGroupId;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002602 } else if (isRestricted) {
Amith Yamasani12747872015-12-07 14:19:49 -08002603 if (parent.info.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) {
2604 parent.info.restrictedProfileParentId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002605 writeUserLP(parent);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002606 }
Amith Yamasani12747872015-12-07 14:19:49 -08002607 userInfo.restrictedProfileParentId = parent.info.restrictedProfileParentId;
Makoto Onuki068c54a2015-10-13 14:34:03 -07002608 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002609 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07002610 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002611 final StorageManager storage = mContext.getSystemService(StorageManager.class);
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002612 storage.createUserKey(userId, userInfo.serialNumber, userInfo.isEphemeral());
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -08002613 mUserDataPreparer.prepareUserData(userId, userInfo.serialNumber,
Jeff Sharkey47f71082016-02-01 17:03:54 -07002614 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002615 mPm.createNewUser(userId, disallowedPackages);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002616 userInfo.partial = false;
2617 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002618 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002619 }
2620 updateUserIds();
2621 Bundle restrictions = new Bundle();
Fyodor Kupolove04462c2015-11-30 15:02:53 -08002622 if (isGuest) {
2623 synchronized (mGuestRestrictions) {
2624 restrictions.putAll(mGuestRestrictions);
2625 }
2626 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002627 synchronized (mRestrictionsLock) {
2628 mBaseUserRestrictions.append(userId, restrictions);
2629 }
Fyodor Kupolov5fd967d2016-07-12 14:46:19 -07002630 mPm.onNewUserCreated(userId);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002631 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
2632 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
2633 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
2634 android.Manifest.permission.MANAGE_USERS);
Christine Franks88220562017-05-24 11:11:21 -07002635 MetricsLogger.count(mContext, isGuest ? TRON_GUEST_CREATED
2636 : (isDemo ? TRON_DEMO_CREATED : TRON_USER_CREATED), 1);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002637 } finally {
2638 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07002639 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002640 return userInfo;
2641 }
2642
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002643 @VisibleForTesting
2644 UserData putUserInfo(UserInfo userInfo) {
2645 final UserData userData = new UserData();
2646 userData.info = userInfo;
2647 synchronized (mUsers) {
2648 mUsers.put(userInfo.id, userData);
2649 }
2650 return userData;
2651 }
2652
2653 @VisibleForTesting
2654 void removeUserInfo(int userId) {
2655 synchronized (mUsers) {
2656 mUsers.remove(userId);
2657 }
2658 }
2659
Amith Yamasani0b285492011-04-14 17:35:23 -07002660 /**
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002661 * @hide
2662 */
Amith Yamasani12747872015-12-07 14:19:49 -08002663 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002664 public UserInfo createRestrictedProfile(String name, int parentUserId) {
Sudheer Shanka53d41472016-06-16 09:11:08 -07002665 checkManageOrCreateUsersPermission("setupRestrictedProfile");
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002666 final UserInfo user = createProfileForUser(
2667 name, UserInfo.FLAG_RESTRICTED, parentUserId, null);
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002668 if (user == null) {
2669 return null;
2670 }
Fyodor Kupolov9e912ba2016-02-09 18:29:43 -08002671 long identity = Binder.clearCallingIdentity();
2672 try {
2673 setUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, true, user.id);
2674 // Change the setting before applying the DISALLOW_SHARE_LOCATION restriction, otherwise
2675 // the putIntForUser() will fail.
2676 android.provider.Settings.Secure.putIntForUser(mContext.getContentResolver(),
2677 android.provider.Settings.Secure.LOCATION_MODE,
2678 android.provider.Settings.Secure.LOCATION_MODE_OFF, user.id);
2679 setUserRestriction(UserManager.DISALLOW_SHARE_LOCATION, true, user.id);
2680 } finally {
2681 Binder.restoreCallingIdentity(identity);
2682 }
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002683 return user;
2684 }
2685
2686 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07002687 * Find the current guest user. If the Guest user is partial,
2688 * then do not include it in the results as it is about to die.
Adam Lesinskieddeb492014-09-08 17:50:03 -07002689 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002690 private UserInfo findCurrentGuestUser() {
2691 synchronized (mUsersLock) {
2692 final int size = mUsers.size();
2693 for (int i = 0; i < size; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002694 final UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002695 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
2696 return user;
2697 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002698 }
2699 }
2700 return null;
2701 }
2702
2703 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07002704 * Mark this guest user for deletion to allow us to create another guest
2705 * and switch to that user before actually removing this guest.
2706 * @param userHandle the userid of the current guest
2707 * @return whether the user could be marked for deletion
2708 */
Amith Yamasani12747872015-12-07 14:19:49 -08002709 @Override
Amith Yamasani1df14732014-08-29 21:37:27 -07002710 public boolean markGuestForDeletion(int userHandle) {
2711 checkManageUsersPermission("Only the system can remove users");
2712 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
2713 UserManager.DISALLOW_REMOVE_USER, false)) {
2714 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
2715 return false;
2716 }
2717
2718 long ident = Binder.clearCallingIdentity();
2719 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002720 final UserData userData;
Amith Yamasani1df14732014-08-29 21:37:27 -07002721 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002722 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002723 userData = mUsers.get(userHandle);
2724 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002725 return false;
2726 }
Amith Yamasani1df14732014-08-29 21:37:27 -07002727 }
Amith Yamasani12747872015-12-07 14:19:49 -08002728 if (!userData.info.isGuest()) {
Amith Yamasani1df14732014-08-29 21:37:27 -07002729 return false;
2730 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002731 // We set this to a guest user that is to be removed. This is a temporary state
2732 // where we are allowed to add new Guest users, even if this one is still not
2733 // removed. This user will still show up in getUserInfo() calls.
2734 // If we don't get around to removing this Guest user, it will be purged on next
2735 // startup.
Amith Yamasani12747872015-12-07 14:19:49 -08002736 userData.info.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07002737 // Mark it as disabled, so that it isn't returned any more when
2738 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002739 userData.info.flags |= UserInfo.FLAG_DISABLED;
2740 writeUserLP(userData);
Amith Yamasani1df14732014-08-29 21:37:27 -07002741 }
2742 } finally {
2743 Binder.restoreCallingIdentity(ident);
2744 }
2745 return true;
2746 }
2747
2748 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002749 * Removes a user and all data directories created for that user. This method should be called
2750 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07002751 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07002752 */
Amith Yamasani12747872015-12-07 14:19:49 -08002753 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -07002754 public boolean removeUser(int userHandle) {
Fyodor Kupolov4593e422016-10-27 11:00:29 -07002755 Slog.i(LOG_TAG, "removeUser u" + userHandle);
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002756 checkManageOrCreateUsersPermission("Only the system can remove users");
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002757
2758 final boolean isManagedProfile;
2759 synchronized (mUsersLock) {
2760 UserInfo userInfo = getUserInfoLU(userHandle);
2761 isManagedProfile = userInfo != null && userInfo.isManagedProfile();
2762 }
2763 String restriction = isManagedProfile
2764 ? UserManager.DISALLOW_REMOVE_MANAGED_PROFILE : UserManager.DISALLOW_REMOVE_USER;
2765 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(restriction, false)) {
2766 Log.w(LOG_TAG, "Cannot remove user. " + restriction + " is enabled.");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04002767 return false;
2768 }
Nicolas Prevotdf1b87d2016-10-25 13:57:08 +01002769 return removeUserUnchecked(userHandle);
2770 }
Julia Reynolds4ac5f852014-06-23 17:38:51 -04002771
Nicolas Prevotdf1b87d2016-10-25 13:57:08 +01002772 private boolean removeUserUnchecked(int userHandle) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002773 long ident = Binder.clearCallingIdentity();
2774 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002775 final UserData userData;
Fyodor Kupolov0df68cd2015-10-01 13:54:22 -07002776 int currentUser = ActivityManager.getCurrentUser();
2777 if (currentUser == userHandle) {
2778 Log.w(LOG_TAG, "Current user cannot be removed");
2779 return false;
2780 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002781 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002782 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002783 userData = mUsers.get(userHandle);
2784 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002785 return false;
2786 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002787
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002788 addRemovingUserIdLocked(userHandle);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002789 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002790
Kenny Guyee58b4f2014-05-23 15:19:53 +01002791 // Set this to a partially created user, so that the user will be purged
2792 // on next startup, in case the runtime stops now before stopping and
2793 // removing the user completely.
Amith Yamasani12747872015-12-07 14:19:49 -08002794 userData.info.partial = true;
Kenny Guyee58b4f2014-05-23 15:19:53 +01002795 // Mark it as disabled, so that it isn't returned any more when
2796 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002797 userData.info.flags |= UserInfo.FLAG_DISABLED;
2798 writeUserLP(userData);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002799 }
Fyodor Kupolov6c96f7f2017-06-28 18:22:59 -07002800 try {
2801 mAppOpsService.removeUser(userHandle);
2802 } catch (RemoteException e) {
2803 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
2804 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002805
Amith Yamasani12747872015-12-07 14:19:49 -08002806 if (userData.info.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
2807 && userData.info.isManagedProfile()) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002808 // Send broadcast to notify system that the user removed was a
2809 // managed user.
Amith Yamasani12747872015-12-07 14:19:49 -08002810 sendProfileRemovedBroadcast(userData.info.profileGroupId, userData.info.id);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002811 }
2812
2813 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
2814 int res;
2815 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08002816 res = ActivityManager.getService().stopUser(userHandle, /* force= */ true,
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07002817 new IStopUserCallback.Stub() {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002818 @Override
2819 public void userStopped(int userId) {
2820 finishRemoveUser(userId);
2821 }
2822 @Override
2823 public void userStopAborted(int userId) {
2824 }
2825 });
2826 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002827 return false;
2828 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002829 return res == ActivityManager.USER_OP_SUCCESS;
2830 } finally {
2831 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002832 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002833 }
2834
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002835 @VisibleForTesting
2836 void addRemovingUserIdLocked(int userId) {
2837 // We remember deleted user IDs to prevent them from being
2838 // reused during the current boot; they can still be reused
2839 // after a reboot or recycling of userIds.
2840 mRemovingUserIds.put(userId, true);
2841 mRecentlyRemovedIds.add(userId);
2842 // Keep LRU queue of recently removed IDs for recycling
2843 if (mRecentlyRemovedIds.size() > MAX_RECENTLY_REMOVED_IDS_SIZE) {
2844 mRecentlyRemovedIds.removeFirst();
2845 }
2846 }
2847
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002848 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07002849 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002850 // Let other services shutdown any activity and clean up their state before completely
2851 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002852 long ident = Binder.clearCallingIdentity();
2853 try {
2854 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
2855 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002856 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
2857 android.Manifest.permission.MANAGE_USERS,
2858
2859 new BroadcastReceiver() {
2860 @Override
2861 public void onReceive(Context context, Intent intent) {
2862 if (DBG) {
2863 Slog.i(LOG_TAG,
2864 "USER_REMOVED broadcast sent, cleaning up user data "
2865 + userHandle);
2866 }
2867 new Thread() {
Amith Yamasani12747872015-12-07 14:19:49 -08002868 @Override
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002869 public void run() {
Amith Yamasani515d4062015-09-28 11:30:06 -07002870 // Clean up any ActivityManager state
2871 LocalServices.getService(ActivityManagerInternal.class)
2872 .onUserRemoved(userHandle);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002873 removeUserState(userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002874 }
2875 }.start();
2876 }
2877 },
2878
2879 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002880 } finally {
2881 Binder.restoreCallingIdentity(ident);
2882 }
Amith Yamasani2a003292012-08-14 18:25:45 -07002883 }
2884
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002885 private void removeUserState(final int userHandle) {
Paul Crowley91293792016-03-25 15:23:07 -07002886 try {
2887 mContext.getSystemService(StorageManager.class).destroyUserKey(userHandle);
2888 } catch (IllegalStateException e) {
2889 // This may be simply because the user was partially created.
2890 Slog.i(LOG_TAG,
2891 "Destroying key for user " + userHandle + " failed, continuing anyway", e);
2892 }
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002893
Amith Yamasanid04aaa32016-06-13 12:09:36 -07002894 // Cleanup gatekeeper secure user id
2895 try {
2896 final IGateKeeperService gk = GateKeeper.getService();
2897 if (gk != null) {
2898 gk.clearSecureUserId(userHandle);
2899 }
2900 } catch (Exception ex) {
2901 Slog.w(LOG_TAG, "unable to clear GK secure user id");
2902 }
2903
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002904 // Cleanup package manager settings
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002905 mPm.cleanUpUser(this, userHandle);
Amith Yamasanid04aaa32016-06-13 12:09:36 -07002906
2907 // Clean up all data before removing metadata
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -08002908 mUserDataPreparer.destroyUserData(userHandle,
Amith Yamasanid04aaa32016-06-13 12:09:36 -07002909 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2910
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002911 // Remove this user from the list
Fyodor Kupolov82402752015-10-28 14:54:51 -07002912 synchronized (mUsersLock) {
2913 mUsers.remove(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08002914 mIsUserManaged.delete(userHandle);
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00002915 }
2916 synchronized (mUserStates) {
2917 mUserStates.delete(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08002918 }
2919 synchronized (mRestrictionsLock) {
2920 mBaseUserRestrictions.remove(userHandle);
2921 mAppliedUserRestrictions.remove(userHandle);
2922 mCachedEffectiveUserRestrictions.remove(userHandle);
2923 mDevicePolicyLocalUserRestrictions.remove(userHandle);
Pavel Grafov6a40f092016-10-25 15:46:51 +01002924 if (mDevicePolicyGlobalUserRestrictions.get(userHandle) != null) {
2925 mDevicePolicyGlobalUserRestrictions.remove(userHandle);
2926 applyUserRestrictionsForAllUsersLR();
2927 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002928 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002929 // Update the user list
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002930 synchronized (mPackagesLock) {
2931 writeUserListLP();
2932 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06002933 // Remove user file
2934 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
2935 userFile.delete();
Fyodor Kupolov82402752015-10-28 14:54:51 -07002936 updateUserIds();
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002937 if (RELEASE_DELETED_USER_ID) {
2938 synchronized (mUsers) {
2939 mRemovingUserIds.delete(userHandle);
2940 }
2941 }
Amith Yamasani61f57372012-08-31 12:12:28 -07002942 }
2943
Kenny Guyf8d3a232014-05-15 16:09:52 +01002944 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01002945 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01002946 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
2947 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002948 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
Jeff Sharkeyaf6ec292015-12-17 11:19:00 -07002949 managedProfileIntent.putExtra(Intent.EXTRA_USER_HANDLE, removedUserId);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002950 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01002951 }
2952
Amith Yamasani2a003292012-08-14 18:25:45 -07002953 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002954 public Bundle getApplicationRestrictions(String packageName) {
2955 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
2956 }
2957
2958 @Override
2959 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002960 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07002961 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07002962 checkSystemOrRoot("get application restrictions for other user/app " + packageName);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002963 }
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07002964 synchronized (mAppRestrictionsLock) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002965 // Read the restrictions from XML
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07002966 return readApplicationRestrictionsLAr(packageName, userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002967 }
2968 }
2969
2970 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002971 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002972 int userId) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00002973 checkSystemOrRoot("set application restrictions");
Fyodor Kupolov0d88d542016-04-19 11:37:22 -07002974 if (restrictions != null) {
2975 restrictions.setDefusable(true);
2976 }
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07002977 synchronized (mAppRestrictionsLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01002978 if (restrictions == null || restrictions.isEmpty()) {
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07002979 cleanAppRestrictionsForPackageLAr(packageName, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01002980 } else {
2981 // Write the restrictions to XML
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07002982 writeApplicationRestrictionsLAr(packageName, restrictions, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01002983 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002984 }
Robin Lee66e5d962014-04-09 16:44:21 +01002985
Fyodor Kupolovd2846122016-02-11 18:06:34 -08002986 // Notify package of changes via an intent - only sent to explicitly registered receivers.
2987 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
2988 changeIntent.setPackage(packageName);
2989 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
2990 mContext.sendBroadcastAsUser(changeIntent, UserHandle.of(userId));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002991 }
2992
2993 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07002994 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002995 try {
2996 return mContext.getPackageManager().getApplicationInfo(packageName,
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07002997 PackageManager.MATCH_ANY_USER).uid;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002998 } catch (NameNotFoundException nnfe) {
2999 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07003000 } finally {
3001 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003002 }
3003 }
3004
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003005 @GuardedBy("mAppRestrictionsLock")
3006 private static Bundle readApplicationRestrictionsLAr(String packageName, int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003007 AtomicFile restrictionsFile =
3008 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
3009 packageToRestrictionsFileName(packageName)));
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003010 return readApplicationRestrictionsLAr(restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003011 }
3012
3013 @VisibleForTesting
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003014 @GuardedBy("mAppRestrictionsLock")
3015 static Bundle readApplicationRestrictionsLAr(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07003016 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003017 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07003018 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07003019 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07003020 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003021
3022 FileInputStream fis = null;
3023 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003024 fis = restrictionsFile.openRead();
3025 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01003026 parser.setInput(fis, StandardCharsets.UTF_8.name());
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003027 XmlUtils.nextElement(parser);
3028 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003029 Slog.e(LOG_TAG, "Unable to read restrictions file "
3030 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07003031 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003032 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003033 while (parser.next() != XmlPullParser.END_DOCUMENT) {
3034 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003035 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003036 } catch (IOException|XmlPullParserException e) {
3037 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003038 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003039 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003040 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07003041 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003042 }
3043
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003044 private static void readEntry(Bundle restrictions, ArrayList<String> values,
3045 XmlPullParser parser) throws XmlPullParserException, IOException {
3046 int type = parser.getEventType();
3047 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
3048 String key = parser.getAttributeValue(null, ATTR_KEY);
3049 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
3050 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
3051 if (multiple != null) {
3052 values.clear();
3053 int count = Integer.parseInt(multiple);
3054 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
3055 if (type == XmlPullParser.START_TAG
3056 && parser.getName().equals(TAG_VALUE)) {
3057 values.add(parser.nextText().trim());
3058 count--;
3059 }
3060 }
3061 String [] valueStrings = new String[values.size()];
3062 values.toArray(valueStrings);
3063 restrictions.putStringArray(key, valueStrings);
3064 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
3065 restrictions.putBundle(key, readBundleEntry(parser, values));
3066 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
3067 final int outerDepth = parser.getDepth();
3068 ArrayList<Bundle> bundleList = new ArrayList<>();
3069 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
3070 Bundle childBundle = readBundleEntry(parser, values);
3071 bundleList.add(childBundle);
3072 }
3073 restrictions.putParcelableArray(key,
3074 bundleList.toArray(new Bundle[bundleList.size()]));
3075 } else {
3076 String value = parser.nextText().trim();
3077 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
3078 restrictions.putBoolean(key, Boolean.parseBoolean(value));
3079 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
3080 restrictions.putInt(key, Integer.parseInt(value));
3081 } else {
3082 restrictions.putString(key, value);
3083 }
3084 }
3085 }
3086 }
3087
3088 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
3089 throws IOException, XmlPullParserException {
3090 Bundle childBundle = new Bundle();
3091 final int outerDepth = parser.getDepth();
3092 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
3093 readEntry(childBundle, values, parser);
3094 }
3095 return childBundle;
3096 }
3097
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003098 @GuardedBy("mAppRestrictionsLock")
3099 private static void writeApplicationRestrictionsLAr(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07003100 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003101 AtomicFile restrictionsFile = new AtomicFile(
3102 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07003103 packageToRestrictionsFileName(packageName)));
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003104 writeApplicationRestrictionsLAr(restrictions, restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003105 }
3106
3107 @VisibleForTesting
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003108 @GuardedBy("mAppRestrictionsLock")
3109 static void writeApplicationRestrictionsLAr(Bundle restrictions, AtomicFile restrictionsFile) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003110 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003111 try {
3112 fos = restrictionsFile.startWrite();
3113 final BufferedOutputStream bos = new BufferedOutputStream(fos);
3114
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003115 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01003116 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003117 serializer.startDocument(null, true);
3118 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
3119
3120 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003121 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003122 serializer.endTag(null, TAG_RESTRICTIONS);
3123
3124 serializer.endDocument();
3125 restrictionsFile.finishWrite(fos);
3126 } catch (Exception e) {
3127 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003128 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
3129 }
3130 }
3131
3132 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
3133 throws IOException {
3134 for (String key : restrictions.keySet()) {
3135 Object value = restrictions.get(key);
3136 serializer.startTag(null, TAG_ENTRY);
3137 serializer.attribute(null, ATTR_KEY, key);
3138
3139 if (value instanceof Boolean) {
3140 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
3141 serializer.text(value.toString());
3142 } else if (value instanceof Integer) {
3143 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
3144 serializer.text(value.toString());
3145 } else if (value == null || value instanceof String) {
3146 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
3147 serializer.text(value != null ? (String) value : "");
3148 } else if (value instanceof Bundle) {
3149 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
3150 writeBundle((Bundle) value, serializer);
3151 } else if (value instanceof Parcelable[]) {
3152 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
3153 Parcelable[] array = (Parcelable[]) value;
3154 for (Parcelable parcelable : array) {
3155 if (!(parcelable instanceof Bundle)) {
3156 throw new IllegalArgumentException("bundle-array can only hold Bundles");
3157 }
3158 serializer.startTag(null, TAG_ENTRY);
3159 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
3160 writeBundle((Bundle) parcelable, serializer);
3161 serializer.endTag(null, TAG_ENTRY);
3162 }
3163 } else {
3164 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
3165 String[] values = (String[]) value;
3166 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
3167 for (String choice : values) {
3168 serializer.startTag(null, TAG_VALUE);
3169 serializer.text(choice != null ? choice : "");
3170 serializer.endTag(null, TAG_VALUE);
3171 }
3172 }
3173 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003174 }
3175 }
3176
3177 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07003178 public int getUserSerialNumber(int userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003179 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07003180 if (!exists(userHandle)) return -1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003181 return getUserInfoLU(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07003182 }
3183 }
3184
3185 @Override
Fyodor Kupolov605b12a2017-05-10 15:58:09 -07003186 public boolean isUserNameSet(int userHandle) {
3187 synchronized (mUsersLock) {
3188 UserInfo userInfo = getUserInfoLU(userHandle);
3189 return userInfo != null && userInfo.name != null;
3190 }
3191 }
3192
3193 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07003194 public int getUserHandle(int userSerialNumber) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003195 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07003196 for (int userId : mUserIds) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003197 UserInfo info = getUserInfoLU(userId);
Kenny Guy945f8832015-02-10 15:17:26 +00003198 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07003199 }
3200 // Not found
3201 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07003202 }
3203 }
3204
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003205 @Override
3206 public long getUserCreationTime(int userHandle) {
3207 int callingUserId = UserHandle.getCallingUserId();
3208 UserInfo userInfo = null;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003209 synchronized (mUsersLock) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003210 if (callingUserId == userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003211 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003212 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003213 UserInfo parent = getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003214 if (parent != null && parent.id == callingUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003215 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003216 }
3217 }
3218 }
3219 if (userInfo == null) {
3220 throw new SecurityException("userHandle can only be the calling user or a managed "
3221 + "profile associated with this user");
3222 }
3223 return userInfo.creationTime;
3224 }
3225
Amith Yamasani0b285492011-04-14 17:35:23 -07003226 /**
3227 * Caches the list of user ids in an array, adjusting the array size when necessary.
3228 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07003229 private void updateUserIds() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003230 int num = 0;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003231 synchronized (mUsersLock) {
3232 final int userSize = mUsers.size();
3233 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003234 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003235 num++;
3236 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003237 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07003238 final int[] newUsers = new int[num];
3239 int n = 0;
3240 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003241 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003242 newUsers[n++] = mUsers.keyAt(i);
3243 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003244 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07003245 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07003246 }
3247 }
3248
3249 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003250 * Called right before a user is started. This gives us a chance to prepare
3251 * app storage and apply any user restrictions.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003252 */
3253 public void onBeforeStartUser(int userId) {
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003254 UserInfo userInfo = getUserInfo(userId);
3255 if (userInfo == null) {
3256 return;
3257 }
3258 final int userSerial = userInfo.serialNumber;
3259 // Migrate only if build fingerprints mismatch
3260 boolean migrateAppsData = !Build.FINGERPRINT.equals(userInfo.lastLoggedInFingerprint);
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -08003261 mUserDataPreparer.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_DE);
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003262 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_DE, migrateAppsData);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003263
3264 if (userId != UserHandle.USER_SYSTEM) {
3265 synchronized (mRestrictionsLock) {
3266 applyUserRestrictionsLR(userId);
3267 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003268 }
3269 }
3270
3271 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003272 * Called right before a user is unlocked. This gives us a chance to prepare
3273 * app storage.
3274 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003275 public void onBeforeUnlockUser(@UserIdInt int userId) {
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003276 UserInfo userInfo = getUserInfo(userId);
3277 if (userInfo == null) {
3278 return;
3279 }
3280 final int userSerial = userInfo.serialNumber;
3281 // Migrate only if build fingerprints mismatch
3282 boolean migrateAppsData = !Build.FINGERPRINT.equals(userInfo.lastLoggedInFingerprint);
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -08003283 mUserDataPreparer.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_CE);
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003284 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_CE, migrateAppsData);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003285 }
3286
3287 /**
Fyodor Kupolov50979d12017-01-27 17:36:32 -08003288 * Examine all users present on given mounted volume, and destroy data
3289 * belonging to users that are no longer valid, or whose user ID has been
3290 * recycled.
3291 */
3292 void reconcileUsers(String volumeUuid) {
3293 mUserDataPreparer.reconcileUsers(volumeUuid, getUsers(true /* excludeDying */));
3294 }
3295
3296 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07003297 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasanieb437d42016-04-29 09:31:25 -07003298 * This is called with ActivityManagerService lock held.
Amith Yamasani920ace02012-09-20 22:15:37 -07003299 * @param userId the user that was just foregrounded
3300 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003301 public void onUserLoggedIn(@UserIdInt int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -08003302 UserData userData = getUserDataNoChecks(userId);
3303 if (userData == null || userData.info.partial) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003304 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
3305 return;
3306 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003307
3308 final long now = System.currentTimeMillis();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003309 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani12747872015-12-07 14:19:49 -08003310 userData.info.lastLoggedInTime = now;
Amith Yamasani920ace02012-09-20 22:15:37 -07003311 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003312 userData.info.lastLoggedInFingerprint = Build.FINGERPRINT;
3313 scheduleWriteUser(userData);
Amith Yamasani920ace02012-09-20 22:15:37 -07003314 }
3315
3316 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07003317 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani0b285492011-04-14 17:35:23 -07003318 */
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003319 @VisibleForTesting
3320 int getNextAvailableId() {
3321 int nextId;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003322 synchronized (mUsersLock) {
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003323 nextId = scanNextAvailableIdLocked();
3324 if (nextId >= 0) {
3325 return nextId;
3326 }
3327 // All ids up to MAX_USER_ID were used. Remove all mRemovingUserIds,
3328 // except most recently removed
3329 if (mRemovingUserIds.size() > 0) {
3330 Slog.i(LOG_TAG, "All available IDs are used. Recycling LRU ids.");
3331 mRemovingUserIds.clear();
3332 for (Integer recentlyRemovedId : mRecentlyRemovedIds) {
3333 mRemovingUserIds.put(recentlyRemovedId, true);
Amith Yamasani195263742012-08-21 15:40:12 -07003334 }
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003335 nextId = scanNextAvailableIdLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003336 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003337 }
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003338 if (nextId < 0) {
3339 throw new IllegalStateException("No user id available!");
3340 }
3341 return nextId;
3342 }
3343
3344 private int scanNextAvailableIdLocked() {
3345 for (int i = MIN_USER_ID; i < MAX_USER_ID; i++) {
3346 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
3347 return i;
3348 }
3349 }
3350 return -1;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003351 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003352
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003353 private static String packageToRestrictionsFileName(String packageName) {
Amith Yamasanifc95e702013-09-26 13:20:17 -07003354 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
3355 }
3356
Amith Yamasani920ace02012-09-20 22:15:37 -07003357 @Override
Amith Yamasani12747872015-12-07 14:19:49 -08003358 public void setSeedAccountData(int userId, String accountName, String accountType,
3359 PersistableBundle accountOptions, boolean persist) {
3360 checkManageUsersPermission("Require MANAGE_USERS permission to set user seed data");
3361 synchronized (mPackagesLock) {
3362 final UserData userData;
3363 synchronized (mUsersLock) {
3364 userData = getUserDataLU(userId);
3365 if (userData == null) {
3366 Slog.e(LOG_TAG, "No such user for settings seed data u=" + userId);
3367 return;
3368 }
3369 userData.seedAccountName = accountName;
3370 userData.seedAccountType = accountType;
3371 userData.seedAccountOptions = accountOptions;
3372 userData.persistSeedData = persist;
3373 }
3374 if (persist) {
3375 writeUserLP(userData);
3376 }
3377 }
3378 }
3379
3380 @Override
3381 public String getSeedAccountName() throws RemoteException {
3382 checkManageUsersPermission("Cannot get seed account information");
3383 synchronized (mUsersLock) {
3384 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3385 return userData.seedAccountName;
3386 }
3387 }
3388
3389 @Override
3390 public String getSeedAccountType() throws RemoteException {
3391 checkManageUsersPermission("Cannot get seed account information");
3392 synchronized (mUsersLock) {
3393 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3394 return userData.seedAccountType;
3395 }
3396 }
3397
3398 @Override
3399 public PersistableBundle getSeedAccountOptions() throws RemoteException {
3400 checkManageUsersPermission("Cannot get seed account information");
3401 synchronized (mUsersLock) {
3402 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3403 return userData.seedAccountOptions;
3404 }
3405 }
3406
3407 @Override
3408 public void clearSeedAccountData() throws RemoteException {
3409 checkManageUsersPermission("Cannot clear seed account information");
3410 synchronized (mPackagesLock) {
3411 UserData userData;
3412 synchronized (mUsersLock) {
3413 userData = getUserDataLU(UserHandle.getCallingUserId());
3414 if (userData == null) return;
3415 userData.clearSeedAccountData();
3416 }
3417 writeUserLP(userData);
3418 }
3419 }
3420
3421 @Override
3422 public boolean someUserHasSeedAccount(String accountName, String accountType)
3423 throws RemoteException {
3424 checkManageUsersPermission("Cannot check seed account information");
3425 synchronized (mUsersLock) {
3426 final int userSize = mUsers.size();
3427 for (int i = 0; i < userSize; i++) {
3428 final UserData data = mUsers.valueAt(i);
3429 if (data.info.isInitialized()) continue;
3430 if (data.seedAccountName == null || !data.seedAccountName.equals(accountName)) {
3431 continue;
3432 }
3433 if (data.seedAccountType == null || !data.seedAccountType.equals(accountType)) {
3434 continue;
3435 }
3436 return true;
3437 }
3438 }
3439 return false;
3440 }
3441
3442 @Override
Todd Kennedy60459ab2015-10-30 11:32:16 -07003443 public void onShellCommand(FileDescriptor in, FileDescriptor out,
Dianne Hackborn354736e2016-08-22 17:00:05 -07003444 FileDescriptor err, String[] args, ShellCallback callback,
3445 ResultReceiver resultReceiver) {
3446 (new Shell()).exec(this, in, out, err, args, callback, resultReceiver);
Todd Kennedy60459ab2015-10-30 11:32:16 -07003447 }
3448
3449 int onShellCommand(Shell shell, String cmd) {
3450 if (cmd == null) {
3451 return shell.handleDefaultCommands(cmd);
3452 }
3453
3454 final PrintWriter pw = shell.getOutPrintWriter();
3455 try {
3456 switch(cmd) {
3457 case "list":
3458 return runList(pw);
3459 }
3460 } catch (RemoteException e) {
3461 pw.println("Remote exception: " + e);
3462 }
3463 return -1;
3464 }
3465
3466 private int runList(PrintWriter pw) throws RemoteException {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003467 final IActivityManager am = ActivityManager.getService();
Todd Kennedy60459ab2015-10-30 11:32:16 -07003468 final List<UserInfo> users = getUsers(false);
3469 if (users == null) {
3470 pw.println("Error: couldn't get users");
3471 return 1;
3472 } else {
3473 pw.println("Users:");
3474 for (int i = 0; i < users.size(); i++) {
Jeff Sharkeye17ac152015-11-06 22:40:29 -08003475 String running = am.isUserRunning(users.get(i).id, 0) ? " running" : "";
Todd Kennedy60459ab2015-10-30 11:32:16 -07003476 pw.println("\t" + users.get(i).toString() + running);
3477 }
3478 return 0;
3479 }
3480 }
3481
3482 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -07003483 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06003484 if (!DumpUtils.checkDumpPermission(mContext, LOG_TAG, pw)) return;
Amith Yamasani920ace02012-09-20 22:15:37 -07003485
3486 long now = System.currentTimeMillis();
3487 StringBuilder sb = new StringBuilder();
3488 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003489 synchronized (mUsersLock) {
3490 pw.println("Users:");
3491 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003492 UserData userData = mUsers.valueAt(i);
3493 if (userData == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003494 continue;
3495 }
Amith Yamasani12747872015-12-07 14:19:49 -08003496 UserInfo userInfo = userData.info;
3497 final int userId = userInfo.id;
3498 pw.print(" "); pw.print(userInfo);
3499 pw.print(" serialNo="); pw.print(userInfo.serialNumber);
Makoto Onukie7927da2015-11-25 10:05:17 -08003500 if (mRemovingUserIds.get(userId)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003501 pw.print(" <removing> ");
3502 }
Amith Yamasani12747872015-12-07 14:19:49 -08003503 if (userInfo.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003504 pw.print(" <partial>");
3505 }
3506 pw.println();
Makoto Onuki88aef752017-03-29 16:52:03 -07003507 pw.print(" State: ");
3508 final int state;
3509 synchronized (mUserStates) {
3510 state = mUserStates.get(userId, -1);
3511 }
3512 pw.println(UserState.stateToString(state));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003513 pw.print(" Created: ");
Amith Yamasani12747872015-12-07 14:19:49 -08003514 if (userInfo.creationTime == 0) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003515 pw.println("<unknown>");
3516 } else {
3517 sb.setLength(0);
Amith Yamasani12747872015-12-07 14:19:49 -08003518 TimeUtils.formatDuration(now - userInfo.creationTime, sb);
Fyodor Kupolov82402752015-10-28 14:54:51 -07003519 sb.append(" ago");
3520 pw.println(sb);
3521 }
3522 pw.print(" Last logged in: ");
Amith Yamasani12747872015-12-07 14:19:49 -08003523 if (userInfo.lastLoggedInTime == 0) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003524 pw.println("<unknown>");
3525 } else {
3526 sb.setLength(0);
Amith Yamasani12747872015-12-07 14:19:49 -08003527 TimeUtils.formatDuration(now - userInfo.lastLoggedInTime, sb);
Fyodor Kupolov82402752015-10-28 14:54:51 -07003528 sb.append(" ago");
3529 pw.println(sb);
3530 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003531 pw.print(" Last logged in fingerprint: ");
3532 pw.println(userInfo.lastLoggedInFingerprint);
Makoto Onukie7927da2015-11-25 10:05:17 -08003533 pw.print(" Has profile owner: ");
3534 pw.println(mIsUserManaged.get(userId));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003535 pw.println(" Restrictions:");
3536 synchronized (mRestrictionsLock) {
3537 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003538 pw, " ", mBaseUserRestrictions.get(userInfo.id));
Pavel Grafov6a40f092016-10-25 15:46:51 +01003539 pw.println(" Device policy global restrictions:");
3540 UserRestrictionsUtils.dumpRestrictions(
3541 pw, " ", mDevicePolicyGlobalUserRestrictions.get(userInfo.id));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003542 pw.println(" Device policy local restrictions:");
3543 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003544 pw, " ", mDevicePolicyLocalUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003545 pw.println(" Effective restrictions:");
3546 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003547 pw, " ", mCachedEffectiveUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003548 }
Amith Yamasani12747872015-12-07 14:19:49 -08003549
3550 if (userData.account != null) {
3551 pw.print(" Account name: " + userData.account);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08003552 pw.println();
3553 }
Amith Yamasani12747872015-12-07 14:19:49 -08003554
3555 if (userData.seedAccountName != null) {
3556 pw.print(" Seed account name: " + userData.seedAccountName);
3557 pw.println();
3558 if (userData.seedAccountType != null) {
3559 pw.print(" account type: " + userData.seedAccountType);
3560 pw.println();
3561 }
3562 if (userData.seedAccountOptions != null) {
3563 pw.print(" account options exist");
3564 pw.println();
3565 }
3566 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003567 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003568 }
Amith Yamasani12747872015-12-07 14:19:49 -08003569 pw.println();
Pavel Grafov6a40f092016-10-25 15:46:51 +01003570 pw.println(" Device owner id:" + mDeviceOwnerUserId);
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01003571 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003572 pw.println(" Guest restrictions:");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003573 synchronized (mGuestRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003574 UserRestrictionsUtils.dumpRestrictions(pw, " ", mGuestRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003575 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003576 synchronized (mUsersLock) {
3577 pw.println();
3578 pw.println(" Device managed: " + mIsDeviceManaged);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003579 if (mRemovingUserIds.size() > 0) {
3580 pw.println();
3581 pw.println(" Recently removed userIds: " + mRecentlyRemovedIds);
3582 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003583 }
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003584 synchronized (mUserStates) {
3585 pw.println(" Started users state: " + mUserStates);
3586 }
Amith Yamasani12747872015-12-07 14:19:49 -08003587 // Dump some capabilities
3588 pw.println();
3589 pw.println(" Max users: " + UserManager.getMaxSupportedUsers());
3590 pw.println(" Supports switchable users: " + UserManager.supportsMultipleUsers());
Lenka Trochtova02fee152015-12-22 14:26:18 +01003591 pw.println(" All guests ephemeral: " + Resources.getSystem().getBoolean(
3592 com.android.internal.R.bool.config_guestUserEphemeral));
Amith Yamasani920ace02012-09-20 22:15:37 -07003593 }
3594 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08003595
3596 final class MainHandler extends Handler {
3597
3598 @Override
3599 public void handleMessage(Message msg) {
3600 switch (msg.what) {
3601 case WRITE_USER_MSG:
3602 removeMessages(WRITE_USER_MSG, msg.obj);
3603 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08003604 int userId = ((UserData) msg.obj).info.id;
3605 UserData userData = getUserDataNoChecks(userId);
3606 if (userData != null) {
3607 writeUserLP(userData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08003608 }
3609 }
3610 }
3611 }
3612 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07003613
3614 /**
3615 * @param userId
3616 * @return whether the user has been initialized yet
3617 */
Todd Kennedy0eb97382017-10-03 16:57:22 -07003618 boolean isUserInitialized(int userId) {
3619 return mLocalService.isUserInitialized(userId);
Amith Yamasanibb054c92015-07-09 14:16:27 -07003620 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003621
3622 private class LocalService extends UserManagerInternal {
Makoto Onuki068c54a2015-10-13 14:34:03 -07003623 @Override
Pavel Grafov6a40f092016-10-25 15:46:51 +01003624 public void setDevicePolicyUserRestrictions(int userId, @Nullable Bundle restrictions,
3625 boolean isDeviceOwner, int cameraRestrictionScope) {
3626 UserManagerService.this.setDevicePolicyUserRestrictionsInner(userId, restrictions,
3627 isDeviceOwner, cameraRestrictionScope);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003628 }
3629
3630 @Override
3631 public Bundle getBaseUserRestrictions(int userId) {
3632 synchronized (mRestrictionsLock) {
3633 return mBaseUserRestrictions.get(userId);
3634 }
3635 }
3636
3637 @Override
3638 public void setBaseUserRestrictionsByDpmsForMigration(
3639 int userId, Bundle baseRestrictions) {
3640 synchronized (mRestrictionsLock) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01003641 if (updateRestrictionsIfNeededLR(
3642 userId, new Bundle(baseRestrictions), mBaseUserRestrictions)) {
3643 invalidateEffectiveUserRestrictionsLR(userId);
3644 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003645 }
3646
Amith Yamasani12747872015-12-07 14:19:49 -08003647 final UserData userData = getUserDataNoChecks(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003648 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08003649 if (userData != null) {
3650 writeUserLP(userData);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003651 } else {
3652 Slog.w(LOG_TAG, "UserInfo not found for " + userId);
3653 }
3654 }
3655 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08003656
3657 @Override
3658 public boolean getUserRestriction(int userId, String key) {
3659 return getUserRestrictions(userId).getBoolean(key);
3660 }
3661
3662 @Override
3663 public void addUserRestrictionsListener(UserRestrictionsListener listener) {
3664 synchronized (mUserRestrictionsListeners) {
3665 mUserRestrictionsListeners.add(listener);
3666 }
3667 }
3668
3669 @Override
3670 public void removeUserRestrictionsListener(UserRestrictionsListener listener) {
3671 synchronized (mUserRestrictionsListeners) {
3672 mUserRestrictionsListeners.remove(listener);
3673 }
3674 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003675
3676 @Override
3677 public void setDeviceManaged(boolean isManaged) {
3678 synchronized (mUsersLock) {
3679 mIsDeviceManaged = isManaged;
3680 }
3681 }
3682
3683 @Override
3684 public void setUserManaged(int userId, boolean isManaged) {
3685 synchronized (mUsersLock) {
3686 mIsUserManaged.put(userId, isManaged);
3687 }
3688 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01003689
3690 @Override
3691 public void setUserIcon(int userId, Bitmap bitmap) {
3692 long ident = Binder.clearCallingIdentity();
3693 try {
3694 synchronized (mPackagesLock) {
3695 UserData userData = getUserDataNoChecks(userId);
3696 if (userData == null || userData.info.partial) {
3697 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
3698 return;
3699 }
3700 writeBitmapLP(userData.info, bitmap);
3701 writeUserLP(userData);
3702 }
3703 sendUserInfoChangedBroadcast(userId);
3704 } finally {
3705 Binder.restoreCallingIdentity(ident);
3706 }
3707 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01003708
3709 @Override
3710 public void setForceEphemeralUsers(boolean forceEphemeralUsers) {
3711 synchronized (mUsersLock) {
3712 mForceEphemeralUsers = forceEphemeralUsers;
3713 }
3714 }
3715
3716 @Override
3717 public void removeAllUsers() {
3718 if (UserHandle.USER_SYSTEM == ActivityManager.getCurrentUser()) {
3719 // Remove the non-system users straight away.
3720 removeNonSystemUsers();
3721 } else {
3722 // Switch to the system user first and then remove the other users.
3723 BroadcastReceiver userSwitchedReceiver = new BroadcastReceiver() {
3724 @Override
3725 public void onReceive(Context context, Intent intent) {
3726 int userId =
3727 intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3728 if (userId != UserHandle.USER_SYSTEM) {
3729 return;
3730 }
3731 mContext.unregisterReceiver(this);
3732 removeNonSystemUsers();
3733 }
3734 };
3735 IntentFilter userSwitchedFilter = new IntentFilter();
3736 userSwitchedFilter.addAction(Intent.ACTION_USER_SWITCHED);
3737 mContext.registerReceiver(
3738 userSwitchedReceiver, userSwitchedFilter, null, mHandler);
3739
3740 // Switch to the system user.
3741 ActivityManager am =
3742 (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
3743 am.switchUser(UserHandle.USER_SYSTEM);
3744 }
3745 }
phweisse9c44062016-02-10 12:57:38 +01003746
3747 @Override
Lenka Trochtova1ddda472016-02-12 10:42:12 +01003748 public void onEphemeralUserStop(int userId) {
3749 synchronized (mUsersLock) {
3750 UserInfo userInfo = getUserInfoLU(userId);
3751 if (userInfo != null && userInfo.isEphemeral()) {
3752 // Do not allow switching back to the ephemeral user again as the user is going
3753 // to be deleted.
3754 userInfo.flags |= UserInfo.FLAG_DISABLED;
3755 if (userInfo.isGuest()) {
3756 // Indicate that the guest will be deleted after it stops.
3757 userInfo.guestToRemove = true;
3758 }
3759 }
3760 }
3761 }
3762
3763 @Override
Alex Chaub6a9f942017-11-07 11:28:56 +08003764 public UserInfo createUserEvenWhenDisallowed(String name, int flags,
3765 String[] disallowedPackages) {
3766 UserInfo user = createUserInternalUnchecked(name, flags, UserHandle.USER_NULL,
3767 disallowedPackages);
phweisse9c44062016-02-10 12:57:38 +01003768 // Keep this in sync with UserManager.createUser
Christine Franks97a54802017-08-09 10:06:43 -07003769 if (user != null && !user.isAdmin() && !user.isDemo()) {
phweisse9c44062016-02-10 12:57:38 +01003770 setUserRestriction(UserManager.DISALLOW_SMS, true, user.id);
3771 setUserRestriction(UserManager.DISALLOW_OUTGOING_CALLS, true, user.id);
3772 }
3773 return user;
3774 }
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003775
3776 @Override
Nicolas Prevotdf1b87d2016-10-25 13:57:08 +01003777 public boolean removeUserEvenWhenDisallowed(int userId) {
3778 return removeUserUnchecked(userId);
3779 }
3780
3781 @Override
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003782 public boolean isUserRunning(int userId) {
3783 synchronized (mUserStates) {
3784 return mUserStates.get(userId, -1) >= 0;
3785 }
3786 }
3787
3788 @Override
3789 public void setUserState(int userId, int userState) {
3790 synchronized (mUserStates) {
3791 mUserStates.put(userId, userState);
3792 }
3793 }
3794
3795 @Override
3796 public void removeUserState(int userId) {
3797 synchronized (mUserStates) {
3798 mUserStates.delete(userId);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003799 }
3800 }
3801
3802 @Override
Michael Wachenschwanz3f2b6552017-05-15 13:53:09 -07003803 public int[] getUserIds() {
3804 return UserManagerService.this.getUserIds();
3805 }
3806
3807 @Override
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003808 public boolean isUserUnlockingOrUnlocked(int userId) {
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07003809 int state;
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003810 synchronized (mUserStates) {
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07003811 state = mUserStates.get(userId, -1);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003812 }
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07003813 // Special case, in the stopping/shutdown state user key can still be unlocked
3814 if (state == UserState.STATE_STOPPING || state == UserState.STATE_SHUTDOWN) {
3815 return StorageManager.isUserKeyUnlocked(userId);
3816 }
3817 return (state == UserState.STATE_RUNNING_UNLOCKING)
3818 || (state == UserState.STATE_RUNNING_UNLOCKED);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003819 }
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08003820
3821 @Override
3822 public boolean isUserUnlocked(int userId) {
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07003823 int state;
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08003824 synchronized (mUserStates) {
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07003825 state = mUserStates.get(userId, -1);
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08003826 }
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07003827 // Special case, in the stopping/shutdown state user key can still be unlocked
3828 if (state == UserState.STATE_STOPPING || state == UserState.STATE_SHUTDOWN) {
3829 return StorageManager.isUserKeyUnlocked(userId);
3830 }
3831 return state == UserState.STATE_RUNNING_UNLOCKED;
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08003832 }
Todd Kennedy0eb97382017-10-03 16:57:22 -07003833
3834 @Override
3835 public boolean isUserInitialized(int userId) {
3836 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
3837 }
3838
3839 @Override
3840 public boolean exists(int userId) {
3841 return getUserInfoNoChecks(userId) != null;
3842 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01003843 }
3844
3845 /* Remove all the users except of the system one. */
3846 private void removeNonSystemUsers() {
3847 ArrayList<UserInfo> usersToRemove = new ArrayList<>();
3848 synchronized (mUsersLock) {
3849 final int userSize = mUsers.size();
3850 for (int i = 0; i < userSize; i++) {
3851 UserInfo ui = mUsers.valueAt(i).info;
3852 if (ui.id != UserHandle.USER_SYSTEM) {
3853 usersToRemove.add(ui);
3854 }
3855 }
3856 }
3857 for (UserInfo ui: usersToRemove) {
3858 removeUser(ui.id);
3859 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003860 }
Todd Kennedy60459ab2015-10-30 11:32:16 -07003861
3862 private class Shell extends ShellCommand {
3863 @Override
3864 public int onCommand(String cmd) {
3865 return onShellCommand(this, cmd);
3866 }
3867
3868 @Override
3869 public void onHelp() {
3870 final PrintWriter pw = getOutPrintWriter();
3871 pw.println("User manager (user) commands:");
3872 pw.println(" help");
3873 pw.println(" Print this help text.");
3874 pw.println("");
3875 pw.println(" list");
3876 pw.println(" Prints all users on the system.");
3877 }
3878 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003879
3880 private static void debug(String message) {
3881 Log.d(LOG_TAG, message +
3882 (DBG_WITH_STACKTRACE ? " called at\n" + Debug.getCallers(10, " ") : ""));
3883 }
Kenny Guy02c89902016-11-15 19:36:38 +00003884
3885 @VisibleForTesting
3886 static int getMaxManagedProfiles() {
3887 // Allow overriding max managed profiles on debuggable builds for testing
3888 // of multiple profiles.
3889 if (!Build.IS_DEBUGGABLE) {
3890 return MAX_MANAGED_PROFILES;
3891 } else {
3892 return SystemProperties.getInt("persist.sys.max_profiles",
3893 MAX_MANAGED_PROFILES);
3894 }
3895 }
3896
3897 @VisibleForTesting
3898 int getFreeProfileBadgeLU(int parentUserId) {
3899 int maxManagedProfiles = getMaxManagedProfiles();
3900 boolean[] usedBadges = new boolean[maxManagedProfiles];
3901 final int userSize = mUsers.size();
3902 for (int i = 0; i < userSize; i++) {
3903 UserInfo ui = mUsers.valueAt(i).info;
3904 // Check which badge indexes are already used by this profile group.
3905 if (ui.isManagedProfile()
3906 && ui.profileGroupId == parentUserId
3907 && !mRemovingUserIds.get(ui.id)
3908 && ui.profileBadge < maxManagedProfiles) {
3909 usedBadges[ui.profileBadge] = true;
3910 }
3911 }
3912 for (int i = 0; i < maxManagedProfiles; i++) {
3913 if (!usedBadges[i]) {
3914 return i;
3915 }
3916 }
3917 return 0;
3918 }
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07003919
3920 /**
3921 * Checks if the given user has a managed profile associated with it.
3922 * @param userId The parent user
3923 * @return
3924 */
3925 boolean hasManagedProfile(int userId) {
3926 synchronized (mUsersLock) {
3927 UserInfo userInfo = getUserInfoLU(userId);
3928 final int userSize = mUsers.size();
3929 for (int i = 0; i < userSize; i++) {
3930 UserInfo profile = mUsers.valueAt(i).info;
3931 if (userId != profile.id && isProfileOf(userInfo, profile)) {
3932 return true;
3933 }
3934 }
3935 return false;
3936 }
3937 }
Tony Makd390ae92017-12-28 13:23:10 +00003938
3939 /**
3940 * Check if the calling package name matches with the calling UID, throw
3941 * {@link SecurityException} if not.
3942 */
3943 private void verifyCallingPackage(String callingPackage, int callingUid) {
3944 int packageUid = mPm.getPackageUid(callingPackage, 0, UserHandle.getUserId(callingUid));
3945 if (packageUid != callingUid) {
3946 throw new SecurityException("Specified package " + callingPackage
3947 + " does not match the calling uid " + callingUid);
3948 }
3949 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003950}