blob: 2e4732469cea445b10295eecde03614cca70c734 [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;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070041import android.content.pm.UserInfo;
Lenka Trochtova02fee152015-12-22 14:26:18 +010042import android.content.res.Resources;
Amith Yamasanie928d7d2012-09-17 21:46:51 -070043import android.graphics.Bitmap;
Amith Yamasani258848d2012-08-10 17:06:33 -070044import android.os.Binder;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -060045import android.os.Build;
Amith Yamasanie4cf7342012-12-17 11:12:09 -080046import android.os.Bundle;
Makoto Onuki1a2cd742015-11-16 13:51:27 -080047import android.os.Debug;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070048import android.os.Environment;
49import android.os.FileUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080050import android.os.Handler;
Svet Ganov9cea80cd2016-02-16 11:47:00 -080051import android.os.IBinder;
Tony Mak64fd8c02017-12-01 19:11:59 +000052import android.os.IProgressListener;
Amith Yamasani258848d2012-08-10 17:06:33 -070053import android.os.IUserManager;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -080054import android.os.Message;
Adrian Roos1bdff912015-02-17 15:51:35 +010055import android.os.ParcelFileDescriptor;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070056import android.os.Parcelable;
Amith Yamasani12747872015-12-07 14:19:49 -080057import android.os.PersistableBundle;
Amith Yamasani258848d2012-08-10 17:06:33 -070058import android.os.Process;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070059import android.os.RemoteException;
Todd Kennedy60459ab2015-10-30 11:32:16 -070060import android.os.ResultReceiver;
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +010061import android.os.SELinux;
Jason Monk62062992014-05-06 09:55:28 -040062import android.os.ServiceManager;
Dianne Hackborn354736e2016-08-22 17:00:05 -070063import android.os.ShellCallback;
Todd Kennedy60459ab2015-10-30 11:32:16 -070064import android.os.ShellCommand;
Kenny Guy02c89902016-11-15 19:36:38 +000065import android.os.SystemProperties;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070066import android.os.UserHandle;
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070067import android.os.UserManager;
Pavel Grafov6a40f092016-10-25 15:46:51 +010068import android.os.UserManager.EnforcingUser;
Makoto Onuki068c54a2015-10-13 14:34:03 -070069import android.os.UserManagerInternal;
Makoto Onukid45a4a22015-11-02 17:17:38 -080070import android.os.UserManagerInternal.UserRestrictionsListener;
Paul Crowley85e4e812015-05-19 12:42:00 +010071import android.os.storage.StorageManager;
Amith Yamasanid04aaa32016-06-13 12:09:36 -070072import android.security.GateKeeper;
73import android.service.gatekeeper.IGateKeeperService;
Amith Yamasani2a003292012-08-14 18:25:45 -070074import android.util.AtomicFile;
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -070075import android.util.IntArray;
Amith Yamasani655d0e22013-06-12 14:19:10 -070076import android.util.Log;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070077import android.util.Slog;
78import android.util.SparseArray;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080079import android.util.SparseBooleanArray;
Amith Yamasaniea1b9d72016-05-27 15:57:38 +000080import android.util.SparseIntArray;
Amith Yamasani920ace02012-09-20 22:15:37 -070081import android.util.TimeUtils;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070082import android.util.Xml;
83
Makoto Onuki068c54a2015-10-13 14:34:03 -070084import com.android.internal.annotations.GuardedBy;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070085import com.android.internal.annotations.VisibleForTesting;
Jason Monk62062992014-05-06 09:55:28 -040086import com.android.internal.app.IAppOpsService;
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -080087import com.android.internal.logging.MetricsLogger;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -060088import com.android.internal.util.DumpUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080089import com.android.internal.util.FastXmlSerializer;
Makoto Onuki068c54a2015-10-13 14:34:03 -070090import com.android.internal.util.Preconditions;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070091import com.android.internal.util.XmlUtils;
Clara Bayarri10ad84a2015-12-01 17:38:05 +000092import com.android.internal.widget.LockPatternUtils;
Amith Yamasani515d4062015-09-28 11:30:06 -070093import com.android.server.LocalServices;
Jeff Sharkey5f3e9342017-03-13 14:53:11 -060094import com.android.server.LockGuard;
Amith Yamasanid04aaa32016-06-13 12:09:36 -070095import com.android.server.SystemService;
Amith Yamasaniea1b9d72016-05-27 15:57:38 +000096import com.android.server.am.UserState;
Suprabh Shuklac5e057c2016-08-08 16:22:44 -070097import com.android.server.storage.DeviceStorageMonitorInternal;
Tony Mak6dc428f2016-10-10 15:48:27 +010098
Jeff Sharkey47f71082016-02-01 17:03:54 -070099import libcore.io.IoUtils;
100import libcore.util.Objects;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800101
102import org.xmlpull.v1.XmlPullParser;
103import org.xmlpull.v1.XmlPullParserException;
104import org.xmlpull.v1.XmlSerializer;
105
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700106import java.io.BufferedOutputStream;
107import java.io.File;
Amith Yamasani920ace02012-09-20 22:15:37 -0700108import java.io.FileDescriptor;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700109import java.io.FileInputStream;
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700110import java.io.FileNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700111import java.io.FileOutputStream;
Tony Mak64fd8c02017-12-01 19:11:59 +0000112import java.io.IOException;
Kenny Guy02c89902016-11-15 19:36:38 +0000113import java.io.InputStream;
114import java.io.OutputStream;
Amith Yamasani920ace02012-09-20 22:15:37 -0700115import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100116import java.nio.charset.StandardCharsets;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700117import java.util.ArrayList;
Pavel Grafov6a40f092016-10-25 15:46:51 +0100118import java.util.Collections;
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700119import java.util.LinkedList;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700120import java.util.List;
121
Makoto Onuki068c54a2015-10-13 14:34:03 -0700122/**
123 * Service for {@link UserManager}.
124 *
125 * Method naming convention:
Fyodor Kupolov82402752015-10-28 14:54:51 -0700126 * <ul>
Fyodor Kupolovd31cee92017-09-05 16:31:08 -0700127 * <li> Methods suffixed with "LAr" should be called within the {@link #mAppRestrictionsLock} lock.
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800128 * <li> Methods suffixed with "LP" should be called within the {@link #mPackagesLock} lock.
Fyodor Kupolov82402752015-10-28 14:54:51 -0700129 * <li> Methods suffixed with "LR" should be called within the {@link #mRestrictionsLock} lock.
130 * <li> Methods suffixed with "LU" should be called within the {@link #mUsersLock} lock.
131 * </ul>
Makoto Onuki068c54a2015-10-13 14:34:03 -0700132 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700133public class UserManagerService extends IUserManager.Stub {
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700134
Amith Yamasani2a003292012-08-14 18:25:45 -0700135 private static final String LOG_TAG = "UserManagerService";
Makoto Onuki81c61ea2016-01-22 11:22:26 -0800136 static final boolean DBG = false; // DO NOT SUBMIT WITH TRUE
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800137 private static final boolean DBG_WITH_STACKTRACE = false; // DO NOT SUBMIT WITH TRUE
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700138 // Can be used for manual testing of id recycling
139 private static final boolean RELEASE_DELETED_USER_ID = false; // DO NOT SUBMIT WITH TRUE
Amith Yamasani16389312012-10-17 21:20:14 -0700140
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700141 private static final String TAG_NAME = "name";
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800142 private static final String TAG_ACCOUNT = "account";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700143 private static final String ATTR_FLAGS = "flags";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700144 private static final String ATTR_ICON_PATH = "icon";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700145 private static final String ATTR_ID = "id";
Amith Yamasani920ace02012-09-20 22:15:37 -0700146 private static final String ATTR_CREATION_TIME = "created";
147 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -0600148 private static final String ATTR_LAST_LOGGED_IN_FINGERPRINT = "lastLoggedInFingerprint";
Amith Yamasani2a003292012-08-14 18:25:45 -0700149 private static final String ATTR_SERIAL_NO = "serialNumber";
150 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700151 private static final String ATTR_PARTIAL = "partial";
Adam Lesinskieddeb492014-09-08 17:50:03 -0700152 private static final String ATTR_GUEST_TO_REMOVE = "guestToRemove";
Amith Yamasani6f34b412012-10-22 18:19:27 -0700153 private static final String ATTR_USER_VERSION = "version";
Kenny Guy2a764942014-04-02 13:29:20 +0100154 private static final String ATTR_PROFILE_GROUP_ID = "profileGroupId";
Kenny Guy02c89902016-11-15 19:36:38 +0000155 private static final String ATTR_PROFILE_BADGE = "profileBadge";
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700156 private static final String ATTR_RESTRICTED_PROFILE_PARENT_ID = "restrictedProfileParentId";
Amith Yamasani12747872015-12-07 14:19:49 -0800157 private static final String ATTR_SEED_ACCOUNT_NAME = "seedAccountName";
158 private static final String ATTR_SEED_ACCOUNT_TYPE = "seedAccountType";
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530159 private static final String TAG_GUEST_RESTRICTIONS = "guestRestrictions";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700160 private static final String TAG_USERS = "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700161 private static final String TAG_USER = "user";
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800162 private static final String TAG_RESTRICTIONS = "restrictions";
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800163 private static final String TAG_DEVICE_POLICY_RESTRICTIONS = "device_policy_restrictions";
Pavel Grafov6a40f092016-10-25 15:46:51 +0100164 private static final String TAG_DEVICE_POLICY_GLOBAL_RESTRICTIONS =
165 "device_policy_global_restrictions";
166 /** Legacy name for device owner id tag. */
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +0100167 private static final String TAG_GLOBAL_RESTRICTION_OWNER_ID = "globalRestrictionOwnerUserId";
Pavel Grafov6a40f092016-10-25 15:46:51 +0100168 private static final String TAG_DEVICE_OWNER_USER_ID = "deviceOwnerUserId";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800169 private static final String TAG_ENTRY = "entry";
170 private static final String TAG_VALUE = "value";
Amith Yamasani12747872015-12-07 14:19:49 -0800171 private static final String TAG_SEED_ACCOUNT_OPTIONS = "seedAccountOptions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800172 private static final String ATTR_KEY = "key";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700173 private static final String ATTR_VALUE_TYPE = "type";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800174 private static final String ATTR_MULTIPLE = "m";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700175
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700176 private static final String ATTR_TYPE_STRING_ARRAY = "sa";
177 private static final String ATTR_TYPE_STRING = "s";
178 private static final String ATTR_TYPE_BOOLEAN = "b";
Amith Yamasani5b5aa402014-06-01 20:10:14 -0700179 private static final String ATTR_TYPE_INTEGER = "i";
Fyodor Kupolov262f9952015-03-23 18:55:11 -0700180 private static final String ATTR_TYPE_BUNDLE = "B";
181 private static final String ATTR_TYPE_BUNDLE_ARRAY = "BA";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700182
Amith Yamasani0b285492011-04-14 17:35:23 -0700183 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700184 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700185 private static final String USER_PHOTO_FILENAME = "photo.png";
Adrian Roos1bdff912015-02-17 15:51:35 +0100186 private static final String USER_PHOTO_FILENAME_TMP = USER_PHOTO_FILENAME + ".tmp";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700187
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800188 private static final String RESTRICTIONS_FILE_PREFIX = "res_";
Amith Yamasanifc95e702013-09-26 13:20:17 -0700189 private static final String XML_SUFFIX = ".xml";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800190
Sudheer Shankaf5cea032016-06-08 17:13:24 -0700191 private static final int ALLOWED_FLAGS_FOR_CREATE_USERS_PERMISSION =
192 UserInfo.FLAG_MANAGED_PROFILE
193 | UserInfo.FLAG_EPHEMERAL
194 | UserInfo.FLAG_RESTRICTED
Sudheer Shanka234d1af2016-08-26 15:42:53 -0700195 | UserInfo.FLAG_GUEST
196 | UserInfo.FLAG_DEMO;
Sudheer Shankaf5cea032016-06-08 17:13:24 -0700197
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700198 @VisibleForTesting
199 static final int MIN_USER_ID = 10;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700200 // We need to keep process uid within Integer.MAX_VALUE.
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700201 @VisibleForTesting
202 static final int MAX_USER_ID = Integer.MAX_VALUE / UserHandle.PER_USER_RANGE;
203
204 // Max size of the queue of recently removed users
205 @VisibleForTesting
206 static final int MAX_RECENTLY_REMOVED_IDS_SIZE = 100;
Amith Yamasani634cf312012-10-04 17:34:21 -0700207
Pavel Grafov6a40f092016-10-25 15:46:51 +0100208 private static final int USER_VERSION = 7;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700209
Amith Yamasani920ace02012-09-20 22:15:37 -0700210 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
211
Nicolas Prevotb8186812015-08-06 15:00:03 +0100212 // Maximum number of managed profiles permitted per user is 1. This cannot be increased
Amith Yamasani95ab7842014-08-11 17:09:26 -0700213 // without first making sure that the rest of the framework is prepared for it.
Kenny Guy02c89902016-11-15 19:36:38 +0000214 @VisibleForTesting
215 static final int MAX_MANAGED_PROFILES = 1;
Amith Yamasani95ab7842014-08-11 17:09:26 -0700216
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800217 static final int WRITE_USER_MSG = 1;
218 static final int WRITE_USER_DELAY = 2*1000; // 2 seconds
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530219
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -0800220 // Tron counters
221 private static final String TRON_GUEST_CREATED = "users_guest_created";
222 private static final String TRON_USER_CREATED = "users_user_created";
Christine Franks88220562017-05-24 11:11:21 -0700223 private static final String TRON_DEMO_CREATED = "users_demo_created";
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -0800224
Dianne Hackborn4428e172012-08-24 17:43:05 -0700225 private final Context mContext;
226 private final PackageManagerService mPm;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700227 private final Object mPackagesLock;
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800228 private final UserDataPreparer mUserDataPreparer;
Fyodor Kupolov82402752015-10-28 14:54:51 -0700229 // Short-term lock for internal state, when interaction/sync with PM is not required
Jeff Sharkey5f3e9342017-03-13 14:53:11 -0600230 private final Object mUsersLock = LockGuard.installNewLock(LockGuard.INDEX_USER);
Fyodor Kupolov82402752015-10-28 14:54:51 -0700231 private final Object mRestrictionsLock = new Object();
Fyodor Kupolovd31cee92017-09-05 16:31:08 -0700232 // Used for serializing access to app restriction files
233 private final Object mAppRestrictionsLock = new Object();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700234
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800235 private final Handler mHandler;
236
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700237 private final File mUsersDir;
238 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700239
Svet Ganov9cea80cd2016-02-16 11:47:00 -0800240 private static final IBinder mUserRestriconToken = new Binder();
241
Makoto Onuki068c54a2015-10-13 14:34:03 -0700242 /**
Amith Yamasani12747872015-12-07 14:19:49 -0800243 * User-related information that is used for persisting to flash. Only UserInfo is
244 * directly exposed to other system apps.
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800245 */
Kenny Guy02c89902016-11-15 19:36:38 +0000246 @VisibleForTesting
247 static class UserData {
Amith Yamasani12747872015-12-07 14:19:49 -0800248 // Basic user information and properties
249 UserInfo info;
250 // Account name used when there is a strong association between a user and an account
251 String account;
252 // Account information for seeding into a newly created user. This could also be
253 // used for login validation for an existing user, for updating their credentials.
254 // In the latter case, data may not need to be persisted as it is only valid for the
255 // current login session.
256 String seedAccountName;
257 String seedAccountType;
258 PersistableBundle seedAccountOptions;
259 // Whether to perist the seed account information to be available after a boot
260 boolean persistSeedData;
261
262 void clearSeedAccountData() {
263 seedAccountName = null;
264 seedAccountType = null;
265 seedAccountOptions = null;
266 persistSeedData = false;
267 }
268 }
269
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800270 @GuardedBy("mUsersLock")
Amith Yamasani12747872015-12-07 14:19:49 -0800271 private final SparseArray<UserData> mUsers = new SparseArray<>();
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800272
273 /**
Makoto Onuki068c54a2015-10-13 14:34:03 -0700274 * User restrictions set via UserManager. This doesn't include restrictions set by
Pavel Grafov6a40f092016-10-25 15:46:51 +0100275 * device owner / profile owners. Only non-empty restriction bundles are stored.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700276 *
277 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
278 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
279 * maybe shared between {@link #mBaseUserRestrictions} and
280 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
281 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700282 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700283 */
284 @GuardedBy("mRestrictionsLock")
285 private final SparseArray<Bundle> mBaseUserRestrictions = new SparseArray<>();
286
287 /**
288 * Cached user restrictions that are in effect -- i.e. {@link #mBaseUserRestrictions} combined
289 * with device / profile owner restrictions. We'll initialize it lazily; use
290 * {@link #getEffectiveUserRestrictions} to access it.
291 *
292 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
293 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
294 * maybe shared between {@link #mBaseUserRestrictions} and
295 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
296 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700297 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700298 */
299 @GuardedBy("mRestrictionsLock")
300 private final SparseArray<Bundle> mCachedEffectiveUserRestrictions = new SparseArray<>();
301
Makoto Onuki4f160732015-10-27 17:15:38 -0700302 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800303 * User restrictions that have already been applied in
304 * {@link #updateUserRestrictionsInternalLR(Bundle, int)}. We use it to detect restrictions
305 * that have changed since the last
306 * {@link #updateUserRestrictionsInternalLR(Bundle, int)} call.
Makoto Onuki4f160732015-10-27 17:15:38 -0700307 */
308 @GuardedBy("mRestrictionsLock")
309 private final SparseArray<Bundle> mAppliedUserRestrictions = new SparseArray<>();
310
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800311 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800312 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
Pavel Grafov6a40f092016-10-25 15:46:51 +0100313 * that should be applied to all users, including guests. Only non-empty restriction bundles are
314 * stored.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800315 */
316 @GuardedBy("mRestrictionsLock")
Pavel Grafov6a40f092016-10-25 15:46:51 +0100317 private final SparseArray<Bundle> mDevicePolicyGlobalUserRestrictions = new SparseArray<>();
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800318
319 /**
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +0100320 * Id of the user that set global restrictions.
321 */
322 @GuardedBy("mRestrictionsLock")
Pavel Grafov6a40f092016-10-25 15:46:51 +0100323 private int mDeviceOwnerUserId = UserHandle.USER_NULL;
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +0100324
325 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800326 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
Pavel Grafov6a40f092016-10-25 15:46:51 +0100327 * for each user. Only non-empty restriction bundles are stored.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800328 */
329 @GuardedBy("mRestrictionsLock")
330 private final SparseArray<Bundle> mDevicePolicyLocalUserRestrictions = new SparseArray<>();
331
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800332 @GuardedBy("mGuestRestrictions")
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530333 private final Bundle mGuestRestrictions = new Bundle();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800334
335 /**
336 * Set of user IDs being actively removed. Removed IDs linger in this set
337 * for several seconds to work around a VFS caching issue.
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700338 * Use {@link #addRemovingUserIdLocked(int)} to add elements to this array
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800339 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700340 @GuardedBy("mUsersLock")
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800341 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700342
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700343 /**
344 * Queue of recently removed userIds. Used for recycling of userIds
345 */
346 @GuardedBy("mUsersLock")
347 private final LinkedList<Integer> mRecentlyRemovedIds = new LinkedList<>();
348
Fyodor Kupolov82402752015-10-28 14:54:51 -0700349 @GuardedBy("mUsersLock")
Amith Yamasani0b285492011-04-14 17:35:23 -0700350 private int[] mUserIds;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800351 @GuardedBy("mPackagesLock")
Amith Yamasani2a003292012-08-14 18:25:45 -0700352 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700353 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700354
Jason Monk62062992014-05-06 09:55:28 -0400355 private IAppOpsService mAppOpsService;
356
Makoto Onuki068c54a2015-10-13 14:34:03 -0700357 private final LocalService mLocalService;
358
Makoto Onukie7927da2015-11-25 10:05:17 -0800359 @GuardedBy("mUsersLock")
360 private boolean mIsDeviceManaged;
361
362 @GuardedBy("mUsersLock")
363 private final SparseBooleanArray mIsUserManaged = new SparseBooleanArray();
364
Makoto Onukid45a4a22015-11-02 17:17:38 -0800365 @GuardedBy("mUserRestrictionsListeners")
366 private final ArrayList<UserRestrictionsListener> mUserRestrictionsListeners =
367 new ArrayList<>();
368
Clara Bayarria1771112015-12-18 16:29:18 +0000369 private final LockPatternUtils mLockPatternUtils;
370
Ricky Waib1dd80b2016-06-07 18:00:55 +0100371 private final String ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK =
372 "com.android.server.pm.DISABLE_QUIET_MODE_AFTER_UNLOCK";
373
374 private final BroadcastReceiver mDisableQuietModeCallback = new BroadcastReceiver() {
375 @Override
376 public void onReceive(Context context, Intent intent) {
Tony Mak64fd8c02017-12-01 19:11:59 +0000377 if (!ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK.equals(intent.getAction())) {
378 return;
Ricky Waib1dd80b2016-06-07 18:00:55 +0100379 }
Tony Mak64fd8c02017-12-01 19:11:59 +0000380 final IntentSender target = intent.getParcelableExtra(Intent.EXTRA_INTENT);
381 final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_ID, UserHandle.USER_NULL);
382 setQuietModeEnabled(userHandle, false, target);
Ricky Waib1dd80b2016-06-07 18:00:55 +0100383 }
384 };
385
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +0100386 /**
Tony Mak64fd8c02017-12-01 19:11:59 +0000387 * Start an {@link IntentSender} when user is unlocked after disabling quiet mode.
388 *
Tony Makb7e6fd42017-12-05 19:40:28 +0000389 * @see {@link #trySetQuietModeEnabled(boolean, int, IntentSender)}
Tony Mak64fd8c02017-12-01 19:11:59 +0000390 */
391 private class DisableQuietModeUserUnlockedCallback extends IProgressListener.Stub {
392 private final IntentSender mTarget;
393
394 public DisableQuietModeUserUnlockedCallback(IntentSender target) {
395 Preconditions.checkNotNull(target);
396 mTarget = target;
397 }
398
399 @Override
400 public void onStarted(int id, Bundle extras) {}
401
402 @Override
403 public void onProgress(int id, int progress, Bundle extras) {}
404
405 @Override
406 public void onFinished(int id, Bundle extras) {
407 try {
408 mContext.startIntentSender(mTarget, null, 0, 0, 0);
409 } catch (IntentSender.SendIntentException e) {
410 Slog.e(LOG_TAG, "Failed to start the target in the callback", e);
411 }
412 }
413 }
414
415 /**
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +0100416 * Whether all users should be created ephemeral.
417 */
418 @GuardedBy("mUsersLock")
419 private boolean mForceEphemeralUsers;
420
Amith Yamasaniea1b9d72016-05-27 15:57:38 +0000421 @GuardedBy("mUserStates")
422 private final SparseIntArray mUserStates = new SparseIntArray();
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -0700423
Amith Yamasani258848d2012-08-10 17:06:33 -0700424 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700425
Dianne Hackborn4428e172012-08-24 17:43:05 -0700426 public static UserManagerService getInstance() {
427 synchronized (UserManagerService.class) {
428 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700429 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700430 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700431
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700432 public static class LifeCycle extends SystemService {
433
434 private UserManagerService mUms;
435
436 /**
437 * @param context
438 */
439 public LifeCycle(Context context) {
440 super(context);
441 }
442
443 @Override
444 public void onStart() {
445 mUms = UserManagerService.getInstance();
446 publishBinderService(Context.USER_SERVICE, mUms);
447 }
448
449 @Override
450 public void onBootPhase(int phase) {
451 if (phase == SystemService.PHASE_ACTIVITY_MANAGER_READY) {
452 mUms.cleanupPartialUsers();
453 }
454 }
455 }
456
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700457 // TODO b/28848102 Add support for test dependencies injection
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800458 @VisibleForTesting
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700459 UserManagerService(Context context) {
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800460 this(context, null, null, new Object(), context.getCacheDir());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700461 }
462
Dianne Hackborn4428e172012-08-24 17:43:05 -0700463 /**
464 * Called by package manager to create the service. This is closely
465 * associated with the package manager, and the given lock is the
466 * package manager's own lock.
467 */
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800468 UserManagerService(Context context, PackageManagerService pm, UserDataPreparer userDataPreparer,
469 Object packagesLock) {
470 this(context, pm, userDataPreparer, packagesLock, Environment.getDataDirectory());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700471 }
472
Dianne Hackborn4428e172012-08-24 17:43:05 -0700473 private UserManagerService(Context context, PackageManagerService pm,
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800474 UserDataPreparer userDataPreparer, Object packagesLock, File dataDir) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700475 mContext = context;
476 mPm = pm;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700477 mPackagesLock = packagesLock;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800478 mHandler = new MainHandler();
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800479 mUserDataPreparer = userDataPreparer;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800480 synchronized (mPackagesLock) {
481 mUsersDir = new File(dataDir, USER_INFO_DIR);
482 mUsersDir.mkdirs();
483 // Make zeroth user directory, for services to migrate their files to that location
484 File userZeroDir = new File(mUsersDir, String.valueOf(UserHandle.USER_SYSTEM));
485 userZeroDir.mkdirs();
486 FileUtils.setPermissions(mUsersDir.toString(),
487 FileUtils.S_IRWXU | FileUtils.S_IRWXG | FileUtils.S_IROTH | FileUtils.S_IXOTH,
488 -1, -1);
489 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
490 initDefaultGuestRestrictions();
491 readUserListLP();
492 sInstance = this;
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700493 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700494 mLocalService = new LocalService();
495 LocalServices.addService(UserManagerInternal.class, mLocalService);
Clara Bayarria1771112015-12-18 16:29:18 +0000496 mLockPatternUtils = new LockPatternUtils(mContext);
Amith Yamasaniea1b9d72016-05-27 15:57:38 +0000497 mUserStates.put(UserHandle.USER_SYSTEM, UserState.STATE_BOOTING);
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700498 }
499
500 void systemReady() {
Jason Monk62062992014-05-06 09:55:28 -0400501 mAppOpsService = IAppOpsService.Stub.asInterface(
502 ServiceManager.getService(Context.APP_OPS_SERVICE));
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800503
504 synchronized (mRestrictionsLock) {
505 applyUserRestrictionsLR(UserHandle.USER_SYSTEM);
Jason Monk62062992014-05-06 09:55:28 -0400506 }
Samuel Tand9453b82016-03-14 15:57:02 -0700507
508 UserInfo currentGuestUser = findCurrentGuestUser();
509 if (currentGuestUser != null && !hasUserRestriction(
510 UserManager.DISALLOW_CONFIG_WIFI, currentGuestUser.id)) {
511 // If a guest user currently exists, apply the DISALLOW_CONFIG_WIFI option
512 // to it, in case this guest was created in a previous version where this
513 // user restriction was not a default guest restriction.
514 setUserRestriction(UserManager.DISALLOW_CONFIG_WIFI, true, currentGuestUser.id);
515 }
Amith Yamasanieb437d42016-04-29 09:31:25 -0700516
Ricky Waib1dd80b2016-06-07 18:00:55 +0100517 mContext.registerReceiver(mDisableQuietModeCallback,
518 new IntentFilter(ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK),
519 null, mHandler);
Amith Yamasani258848d2012-08-10 17:06:33 -0700520 }
521
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700522 void cleanupPartialUsers() {
523 // Prune out any partially created, partially removed and ephemeral users.
524 ArrayList<UserInfo> partials = new ArrayList<>();
525 synchronized (mUsersLock) {
526 final int userSize = mUsers.size();
527 for (int i = 0; i < userSize; i++) {
528 UserInfo ui = mUsers.valueAt(i).info;
529 if ((ui.partial || ui.guestToRemove || ui.isEphemeral()) && i != 0) {
530 partials.add(ui);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700531 addRemovingUserIdLocked(ui.id);
Amith Yamasaniae261892016-06-27 10:40:09 -0700532 ui.partial = true;
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700533 }
534 }
535 }
536 final int partialsSize = partials.size();
537 for (int i = 0; i < partialsSize; i++) {
538 UserInfo ui = partials.get(i);
539 Slog.w(LOG_TAG, "Removing partially created user " + ui.id
540 + " (name=" + ui.name + ")");
541 removeUserState(ui.id);
542 }
543 }
544
Amith Yamasani258848d2012-08-10 17:06:33 -0700545 @Override
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800546 public String getUserAccount(int userId) {
547 checkManageUserAndAcrossUsersFullPermission("get user account");
548 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800549 return mUsers.get(userId).account;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800550 }
551 }
552
553 @Override
554 public void setUserAccount(int userId, String accountName) {
555 checkManageUserAndAcrossUsersFullPermission("set user account");
Amith Yamasani12747872015-12-07 14:19:49 -0800556 UserData userToUpdate = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800557 synchronized (mPackagesLock) {
558 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800559 final UserData userData = mUsers.get(userId);
560 if (userData == null) {
561 Slog.e(LOG_TAG, "User not found for setting user account: u" + userId);
562 return;
563 }
564 String currentAccount = userData.account;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800565 if (!Objects.equal(currentAccount, accountName)) {
Amith Yamasani12747872015-12-07 14:19:49 -0800566 userData.account = accountName;
567 userToUpdate = userData;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800568 }
569 }
570
571 if (userToUpdate != null) {
572 writeUserLP(userToUpdate);
573 }
574 }
575 }
576
577 @Override
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700578 public UserInfo getPrimaryUser() {
579 checkManageUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700580 synchronized (mUsersLock) {
Amith Yamasani515d4062015-09-28 11:30:06 -0700581 final int userSize = mUsers.size();
582 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800583 UserInfo ui = mUsers.valueAt(i).info;
Xiaohui Chend3e9e182015-11-18 13:37:32 -0800584 if (ui.isPrimary() && !mRemovingUserIds.get(ui.id)) {
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700585 return ui;
586 }
587 }
588 }
589 return null;
590 }
591
592 @Override
Xiaohui Chen594f2082015-08-18 11:04:20 -0700593 public @NonNull List<UserInfo> getUsers(boolean excludeDying) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -0700594 checkManageOrCreateUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700595 synchronized (mUsersLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700596 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasani515d4062015-09-28 11:30:06 -0700597 final int userSize = mUsers.size();
598 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800599 UserInfo ui = mUsers.valueAt(i).info;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700600 if (ui.partial) {
601 continue;
602 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800603 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Amith Yamasani6f48d6e2016-03-23 14:28:25 -0700604 users.add(userWithName(ui));
Amith Yamasani920ace02012-09-20 22:15:37 -0700605 }
Amith Yamasani13593602012-03-22 16:16:17 -0700606 }
607 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700608 }
Amith Yamasani13593602012-03-22 16:16:17 -0700609 }
610
Amith Yamasani258848d2012-08-10 17:06:33 -0700611 @Override
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100612 public List<UserInfo> getProfiles(int userId, boolean enabledOnly) {
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700613 boolean returnFullInfo = true;
Amith Yamasani4f582632014-02-19 14:31:52 -0800614 if (userId != UserHandle.getCallingUserId()) {
Sudheer Shanka74680912016-07-29 11:03:37 -0700615 checkManageOrCreateUsersPermission("getting profiles related to user " + userId);
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700616 } else {
617 returnFullInfo = hasManageUsersPermission();
Amith Yamasani4f582632014-02-19 14:31:52 -0800618 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700619 final long ident = Binder.clearCallingIdentity();
620 try {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700621 synchronized (mUsersLock) {
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700622 return getProfilesLU(userId, enabledOnly, returnFullInfo);
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100623 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700624 } finally {
625 Binder.restoreCallingIdentity(ident);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000626 }
627 }
628
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700629 @Override
630 public int[] getProfileIds(int userId, boolean enabledOnly) {
631 if (userId != UserHandle.getCallingUserId()) {
bohu12d23a12016-09-26 16:20:07 -0700632 checkManageOrCreateUsersPermission("getting profiles related to user " + userId);
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700633 }
634 final long ident = Binder.clearCallingIdentity();
635 try {
636 synchronized (mUsersLock) {
637 return getProfileIdsLU(userId, enabledOnly).toArray();
638 }
639 } finally {
640 Binder.restoreCallingIdentity(ident);
641 }
642 }
643
Amith Yamasanibe465322014-04-24 13:45:17 -0700644 /** Assume permissions already checked and caller's identity cleared */
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700645 private List<UserInfo> getProfilesLU(int userId, boolean enabledOnly, boolean fullInfo) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700646 IntArray profileIds = getProfileIdsLU(userId, enabledOnly);
647 ArrayList<UserInfo> users = new ArrayList<>(profileIds.size());
648 for (int i = 0; i < profileIds.size(); i++) {
649 int profileId = profileIds.get(i);
650 UserInfo userInfo = mUsers.get(profileId).info;
651 // If full info is not required - clear PII data to prevent 3P apps from reading it
652 if (!fullInfo) {
653 userInfo = new UserInfo(userInfo);
654 userInfo.name = null;
655 userInfo.iconPath = null;
656 } else {
657 userInfo = userWithName(userInfo);
658 }
659 users.add(userInfo);
660 }
661 return users;
662 }
663
664 /**
665 * Assume permissions already checked and caller's identity cleared
666 */
667 private IntArray getProfileIdsLU(int userId, boolean enabledOnly) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700668 UserInfo user = getUserInfoLU(userId);
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700669 IntArray result = new IntArray(mUsers.size());
Amith Yamasanidda003f2014-08-28 18:06:51 -0700670 if (user == null) {
671 // Probably a dying user
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700672 return result;
Amith Yamasanidda003f2014-08-28 18:06:51 -0700673 }
Amith Yamasani515d4062015-09-28 11:30:06 -0700674 final int userSize = mUsers.size();
675 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800676 UserInfo profile = mUsers.valueAt(i).info;
Amith Yamasanibe465322014-04-24 13:45:17 -0700677 if (!isProfileOf(user, profile)) {
678 continue;
679 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100680 if (enabledOnly && !profile.isEnabled()) {
681 continue;
Amith Yamasanibe465322014-04-24 13:45:17 -0700682 }
Amith Yamasani70fcf0c2014-07-11 08:40:19 -0700683 if (mRemovingUserIds.get(profile.id)) {
684 continue;
685 }
Tony Mak80189cd2016-04-05 17:21:42 +0100686 if (profile.partial) {
687 continue;
688 }
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700689 result.add(profile.id);
Amith Yamasanibe465322014-04-24 13:45:17 -0700690 }
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700691 return result;
Amith Yamasanibe465322014-04-24 13:45:17 -0700692 }
693
Jessica Hummelbe81c802014-04-22 15:49:22 +0100694 @Override
Andres Moralesc5548c02015-08-05 10:23:12 -0700695 public int getCredentialOwnerProfile(int userHandle) {
696 checkManageUsersPermission("get the credential owner");
Clara Bayarria1771112015-12-18 16:29:18 +0000697 if (!mLockPatternUtils.isSeparateProfileChallengeEnabled(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700698 synchronized (mUsersLock) {
699 UserInfo profileParent = getProfileParentLU(userHandle);
Andres Moralesc5548c02015-08-05 10:23:12 -0700700 if (profileParent != null) {
701 return profileParent.id;
702 }
703 }
704 }
705
706 return userHandle;
707 }
708
709 @Override
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700710 public boolean isSameProfileGroup(int userId, int otherUserId) {
711 if (userId == otherUserId) return true;
712 checkManageUsersPermission("check if in the same profile group");
Fyodor Kupolov0fb772e2016-10-13 16:27:34 -0700713 return isSameProfileGroupNoChecks(userId, otherUserId);
714 }
715
716 private boolean isSameProfileGroupNoChecks(int userId, int otherUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700717 synchronized (mUsersLock) {
718 UserInfo userInfo = getUserInfoLU(userId);
719 if (userInfo == null || userInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
720 return false;
721 }
722 UserInfo otherUserInfo = getUserInfoLU(otherUserId);
723 if (otherUserInfo == null
724 || otherUserInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
725 return false;
726 }
727 return userInfo.profileGroupId == otherUserInfo.profileGroupId;
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700728 }
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700729 }
730
731 @Override
Jessica Hummelbe81c802014-04-22 15:49:22 +0100732 public UserInfo getProfileParent(int userHandle) {
733 checkManageUsersPermission("get the profile parent");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700734 synchronized (mUsersLock) {
735 return getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700736 }
737 }
738
Jakub Pawlowski0f1f5b72017-11-15 14:50:43 -0800739 @Override
740 public int getProfileParentId(int userHandle) {
741 checkManageUsersPermission("get the profile parent");
742 synchronized (mUsersLock) {
743 UserInfo profileParent = getProfileParentLU(userHandle);
744 if (profileParent == null) {
745 return userHandle;
746 }
747
748 return profileParent.id;
749 }
750 }
751
Fyodor Kupolov82402752015-10-28 14:54:51 -0700752 private UserInfo getProfileParentLU(int userHandle) {
753 UserInfo profile = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700754 if (profile == null) {
755 return null;
756 }
757 int parentUserId = profile.profileGroupId;
Amith Yamasani801e3422017-01-25 11:35:44 -0800758 if (parentUserId == userHandle || parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700759 return null;
760 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700761 return getUserInfoLU(parentUserId);
Jessica Hummelbe81c802014-04-22 15:49:22 +0100762 }
763 }
764
Fyodor Kupolov82402752015-10-28 14:54:51 -0700765 private static boolean isProfileOf(UserInfo user, UserInfo profile) {
Kenny Guy2a764942014-04-02 13:29:20 +0100766 return user.id == profile.id ||
767 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
768 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000769 }
770
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000771 private void broadcastProfileAvailabilityChanges(UserHandle profileHandle,
Rubin Xuf13c9802016-01-21 18:06:00 +0000772 UserHandle parentHandle, boolean inQuietMode) {
Rubin Xue95057a2016-04-01 16:49:25 +0100773 Intent intent = new Intent();
774 if (inQuietMode) {
775 intent.setAction(Intent.ACTION_MANAGED_PROFILE_UNAVAILABLE);
776 } else {
777 intent.setAction(Intent.ACTION_MANAGED_PROFILE_AVAILABLE);
778 }
Rubin Xuf13c9802016-01-21 18:06:00 +0000779 intent.putExtra(Intent.EXTRA_QUIET_MODE, inQuietMode);
780 intent.putExtra(Intent.EXTRA_USER, profileHandle);
781 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileHandle.getIdentifier());
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000782 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Rubin Xuf13c9802016-01-21 18:06:00 +0000783 mContext.sendBroadcastAsUser(intent, parentHandle);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000784 }
785
786 @Override
Tony Makb7e6fd42017-12-05 19:40:28 +0000787 public boolean trySetQuietModeEnabled(
788 boolean enableQuietMode, int userHandle, @Nullable IntentSender target) {
789 if (enableQuietMode && target != null) {
790 throw new IllegalArgumentException(
791 "target should only be specified when we are disabling quiet mode.");
792 }
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000793
Tony Makb7e6fd42017-12-05 19:40:28 +0000794 checkManageUsersPermission("trySetQuietModeEnabled");
795
796 final long identity = Binder.clearCallingIdentity();
797 try {
798 if (enableQuietMode) {
799 setQuietModeEnabled(userHandle, true /* enableQuietMode */, target);
800 return true;
801 } else {
802 boolean needToShowConfirmCredential =
803 mLockPatternUtils.isSecure(userHandle)
804 && !StorageManager.isUserKeyUnlocked(userHandle);
805 if (needToShowConfirmCredential) {
806 showConfirmCredentialToDisableQuietMode(userHandle, target);
807 return false;
808 } else {
809 setQuietModeEnabled(userHandle, false /* enableQuietMode */, target);
810 return true;
811 }
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000812 }
Tony Makb7e6fd42017-12-05 19:40:28 +0000813 } finally {
814 Binder.restoreCallingIdentity(identity);
815 }
816 }
817
818 private void setQuietModeEnabled(
819 int userHandle, boolean enableQuietMode, IntentSender target) {
820 final UserInfo profile, parent;
821 final UserData profileUserData;
822 synchronized (mUsersLock) {
823 profile = getUserInfoLU(userHandle);
824 parent = getProfileParentLU(userHandle);
825
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000826 if (profile == null || !profile.isManagedProfile()) {
827 throw new IllegalArgumentException("User " + userHandle + " is not a profile");
828 }
Tony Makb7e6fd42017-12-05 19:40:28 +0000829 if (profile.isQuietModeEnabled() == enableQuietMode) {
830 Slog.i(LOG_TAG, "Quiet mode is already " + enableQuietMode);
831 return;
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000832 }
Tony Makb7e6fd42017-12-05 19:40:28 +0000833 profile.flags ^= UserInfo.FLAG_QUIET_MODE;
834 profileUserData = getUserDataLU(profile.id);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000835 }
Tony Makb7e6fd42017-12-05 19:40:28 +0000836 synchronized (mPackagesLock) {
837 writeUserLP(profileUserData);
838 }
839 try {
840 if (enableQuietMode) {
841 ActivityManager.getService().stopUser(userHandle, /* force */true, null);
842 LocalServices.getService(ActivityManagerInternal.class)
843 .killForegroundAppsForUser(userHandle);
844 } else {
845 IProgressListener callback = target != null
846 ? new DisableQuietModeUserUnlockedCallback(target)
847 : null;
848 ActivityManager.getService().startUserInBackgroundWithListener(
849 userHandle, callback);
Rubin Xuf13c9802016-01-21 18:06:00 +0000850 }
Tony Makb7e6fd42017-12-05 19:40:28 +0000851 } catch (RemoteException e) {
852 // Should not happen, same process.
853 e.rethrowAsRuntimeException();
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000854 }
Tony Makb7e6fd42017-12-05 19:40:28 +0000855 broadcastProfileAvailabilityChanges(profile.getUserHandle(), parent.getUserHandle(),
856 enableQuietMode);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000857 }
858
859 @Override
860 public boolean isQuietModeEnabled(int userHandle) {
861 synchronized (mPackagesLock) {
862 UserInfo info;
863 synchronized (mUsersLock) {
864 info = getUserInfoLU(userHandle);
865 }
866 if (info == null || !info.isManagedProfile()) {
Rubin Xuf13c9802016-01-21 18:06:00 +0000867 return false;
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000868 }
869 return info.isQuietModeEnabled();
870 }
871 }
872
Tony Makb7e6fd42017-12-05 19:40:28 +0000873 /**
874 * Show confirm credential screen to unlock user in order to turn off quiet mode.
875 */
876 private void showConfirmCredentialToDisableQuietMode(
Tony Mak64fd8c02017-12-01 19:11:59 +0000877 @UserIdInt int userHandle, @Nullable IntentSender target) {
Tony Makb7e6fd42017-12-05 19:40:28 +0000878 // otherwise, we show a profile challenge to trigger decryption of the user
879 final KeyguardManager km = (KeyguardManager) mContext.getSystemService(
880 Context.KEYGUARD_SERVICE);
881 // We should use userHandle not credentialOwnerUserId here, as even if it is unified
882 // lock, confirm screenlock page will know and show personal challenge, and unlock
883 // work profile when personal challenge is correct
884 final Intent unlockIntent = km.createConfirmDeviceCredentialIntent(null, null,
885 userHandle);
886 if (unlockIntent == null) {
887 return;
Benjamin Franzf02420c2016-04-04 18:52:21 +0100888 }
Tony Makb7e6fd42017-12-05 19:40:28 +0000889 final Intent callBackIntent = new Intent(
890 ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK);
891 if (target != null) {
892 callBackIntent.putExtra(Intent.EXTRA_INTENT, target);
Benjamin Franzf02420c2016-04-04 18:52:21 +0100893 }
Tony Makb7e6fd42017-12-05 19:40:28 +0000894 callBackIntent.putExtra(Intent.EXTRA_USER_ID, userHandle);
895 callBackIntent.setPackage(mContext.getPackageName());
896 callBackIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
897 final PendingIntent pendingIntent = PendingIntent.getBroadcast(
898 mContext,
899 0,
900 callBackIntent,
901 PendingIntent.FLAG_CANCEL_CURRENT |
902 PendingIntent.FLAG_ONE_SHOT |
903 PendingIntent.FLAG_IMMUTABLE);
904 // After unlocking the challenge, it will disable quiet mode and run the original
905 // intentSender
906 unlockIntent.putExtra(Intent.EXTRA_INTENT, pendingIntent.getIntentSender());
907 unlockIntent.setFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
908 mContext.startActivity(unlockIntent);
Benjamin Franzf02420c2016-04-04 18:52:21 +0100909 }
910
911 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100912 public void setUserEnabled(int userId) {
913 checkManageUsersPermission("enable user");
914 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700915 UserInfo info;
916 synchronized (mUsersLock) {
917 info = getUserInfoLU(userId);
918 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100919 if (info != null && !info.isEnabled()) {
920 info.flags ^= UserInfo.FLAG_DISABLED;
Amith Yamasani12747872015-12-07 14:19:49 -0800921 writeUserLP(getUserDataLU(info.id));
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100922 }
923 }
924 }
925
Andrew Scull85a63bc2016-10-24 13:47:47 +0100926 /**
927 * Evicts a user's CE key by stopping and restarting the user.
928 *
929 * The key is evicted automatically by the user controller when the user has stopped.
930 */
931 @Override
932 public void evictCredentialEncryptionKey(@UserIdInt int userId) {
933 checkManageUsersPermission("evict CE key");
934 final IActivityManager am = ActivityManagerNative.getDefault();
935 final long identity = Binder.clearCallingIdentity();
936 try {
937 am.restartUserInBackground(userId);
938 } catch (RemoteException re) {
939 throw re.rethrowAsRuntimeException();
940 } finally {
941 Binder.restoreCallingIdentity(identity);
942 }
943 }
944
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100945 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700946 public UserInfo getUserInfo(int userId) {
Sudheer Shankaaccaa082016-06-14 16:22:57 -0700947 checkManageOrCreateUsersPermission("query user");
Tony Mak8673b282016-03-21 21:10:59 +0000948 synchronized (mUsersLock) {
Amith Yamasani6f48d6e2016-03-23 14:28:25 -0700949 return userWithName(getUserInfoLU(userId));
950 }
951 }
952
953 /**
954 * Returns a UserInfo object with the name filled in, for Owner, or the original
955 * if the name is already set.
956 */
957 private UserInfo userWithName(UserInfo orig) {
958 if (orig != null && orig.name == null && orig.id == UserHandle.USER_SYSTEM) {
959 UserInfo withName = new UserInfo(orig);
960 withName.name = getOwnerName();
961 return withName;
962 } else {
963 return orig;
Tony Mak8673b282016-03-21 21:10:59 +0000964 }
965 }
966
967 @Override
Kenny Guy02c89902016-11-15 19:36:38 +0000968 public int getManagedProfileBadge(@UserIdInt int userId) {
969 int callingUserId = UserHandle.getCallingUserId();
970 if (callingUserId != userId && !hasManageUsersPermission()) {
971 if (!isSameProfileGroupNoChecks(callingUserId, userId)) {
972 throw new SecurityException(
973 "You need MANAGE_USERS permission to: check if specified user a " +
974 "managed profile outside your profile group");
975 }
976 }
977 synchronized (mUsersLock) {
978 UserInfo userInfo = getUserInfoLU(userId);
979 return userInfo != null ? userInfo.profileBadge : 0;
980 }
981 }
982
983 @Override
Tony Mak8673b282016-03-21 21:10:59 +0000984 public boolean isManagedProfile(int userId) {
Tony Makb531d082016-03-16 14:49:52 +0000985 int callingUserId = UserHandle.getCallingUserId();
986 if (callingUserId != userId && !hasManageUsersPermission()) {
Fyodor Kupolov0fb772e2016-10-13 16:27:34 -0700987 if (!isSameProfileGroupNoChecks(callingUserId, userId)) {
Fyodor Kupolovc413f702016-10-06 17:11:14 -0700988 throw new SecurityException(
989 "You need MANAGE_USERS permission to: check if specified user a " +
990 "managed profile outside your profile group");
Tony Makb531d082016-03-16 14:49:52 +0000991 }
Tony Mak4dc008c2016-03-16 10:46:49 +0000992 }
Fyodor Kupolov82402752015-10-28 14:54:51 -0700993 synchronized (mUsersLock) {
Amith Yamasani1c41dc82016-06-28 16:13:15 -0700994 UserInfo userInfo = getUserInfoLU(userId);
Tony Mak8673b282016-03-21 21:10:59 +0000995 return userInfo != null && userInfo.isManagedProfile();
Amith Yamasani13593602012-03-22 16:16:17 -0700996 }
997 }
998
Amith Yamasani71e6c692013-03-24 17:39:28 -0700999 @Override
Fyodor Kupolovc413f702016-10-06 17:11:14 -07001000 public boolean isUserUnlockingOrUnlocked(int userId) {
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08001001 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isUserUnlockingOrUnlocked");
Fyodor Kupolovc413f702016-10-06 17:11:14 -07001002 return mLocalService.isUserUnlockingOrUnlocked(userId);
1003 }
1004
1005 @Override
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08001006 public boolean isUserUnlocked(int userId) {
1007 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isUserUnlocked");
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07001008 return mLocalService.isUserUnlocked(userId);
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08001009 }
1010
1011 @Override
1012 public boolean isUserRunning(int userId) {
1013 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isUserRunning");
1014 return mLocalService.isUserRunning(userId);
1015 }
1016
1017 private void checkManageOrInteractPermIfCallerInOtherProfileGroup(int userId, String name) {
1018 int callingUserId = UserHandle.getCallingUserId();
1019 if (callingUserId == userId || isSameProfileGroupNoChecks(callingUserId, userId) ||
1020 hasManageUsersPermission()) {
1021 return;
1022 }
1023 if (ActivityManager.checkComponentPermission(Manifest.permission.INTERACT_ACROSS_USERS,
1024 Binder.getCallingUid(), -1, true) != PackageManager.PERMISSION_GRANTED) {
1025 throw new SecurityException("You need INTERACT_ACROSS_USERS or MANAGE_USERS permission "
1026 + "to: check " + name);
1027 }
1028 }
1029
1030 @Override
Amith Yamasani1c41dc82016-06-28 16:13:15 -07001031 public boolean isDemoUser(int userId) {
1032 int callingUserId = UserHandle.getCallingUserId();
1033 if (callingUserId != userId && !hasManageUsersPermission()) {
1034 throw new SecurityException("You need MANAGE_USERS permission to query if u=" + userId
1035 + " is a demo user");
1036 }
1037 synchronized (mUsersLock) {
1038 UserInfo userInfo = getUserInfoLU(userId);
1039 return userInfo != null && userInfo.isDemo();
1040 }
1041 }
1042
1043 @Override
Amith Yamasani71e6c692013-03-24 17:39:28 -07001044 public boolean isRestricted() {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001045 synchronized (mUsersLock) {
1046 return getUserInfoLU(UserHandle.getCallingUserId()).isRestricted();
Amith Yamasani71e6c692013-03-24 17:39:28 -07001047 }
1048 }
1049
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001050 @Override
1051 public boolean canHaveRestrictedProfile(int userId) {
1052 checkManageUsersPermission("canHaveRestrictedProfile");
Fyodor Kupolov82402752015-10-28 14:54:51 -07001053 synchronized (mUsersLock) {
1054 final UserInfo userInfo = getUserInfoLU(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001055 if (userInfo == null || !userInfo.canHaveProfile()) {
1056 return false;
1057 }
1058 if (!userInfo.isAdmin()) {
1059 return false;
1060 }
Makoto Onukie7927da2015-11-25 10:05:17 -08001061 // restricted profile can be created if there is no DO set and the admin user has no PO;
1062 return !mIsDeviceManaged && !mIsUserManaged.get(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001063 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001064 }
1065
Fyodor Kupolovca177562017-11-09 17:43:01 -08001066 @Override
1067 public boolean hasRestrictedProfiles() {
1068 checkManageUsersPermission("hasRestrictedProfiles");
1069 final int callingUserId = UserHandle.getCallingUserId();
1070 synchronized (mUsersLock) {
1071 final int userSize = mUsers.size();
1072 for (int i = 0; i < userSize; i++) {
1073 UserInfo profile = mUsers.valueAt(i).info;
1074 if (callingUserId != profile.id
1075 && profile.restrictedProfileParentId == callingUserId) {
1076 return true;
1077 }
1078 }
1079 return false;
1080 }
1081 }
1082
Amith Yamasani195263742012-08-21 15:40:12 -07001083 /*
1084 * Should be locked on mUsers before calling this.
1085 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001086 private UserInfo getUserInfoLU(int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -08001087 final UserData userData = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -07001088 // If it is partial and not in the process of being removed, return as unknown user.
Amith Yamasani12747872015-12-07 14:19:49 -08001089 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001090 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
1091 return null;
1092 }
Amith Yamasani12747872015-12-07 14:19:49 -08001093 return userData != null ? userData.info : null;
1094 }
1095
1096 private UserData getUserDataLU(int userId) {
1097 final UserData userData = mUsers.get(userId);
1098 // If it is partial and not in the process of being removed, return as unknown user.
1099 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
1100 return null;
1101 }
1102 return userData;
Amith Yamasani195263742012-08-21 15:40:12 -07001103 }
1104
Fyodor Kupolov82402752015-10-28 14:54:51 -07001105 /**
1106 * Obtains {@link #mUsersLock} and return UserInfo from mUsers.
1107 * <p>No permissions checking or any addition checks are made</p>
1108 */
1109 private UserInfo getUserInfoNoChecks(int userId) {
1110 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001111 final UserData userData = mUsers.get(userId);
1112 return userData != null ? userData.info : null;
1113 }
1114 }
1115
1116 /**
1117 * Obtains {@link #mUsersLock} and return UserData from mUsers.
1118 * <p>No permissions checking or any addition checks are made</p>
1119 */
1120 private UserData getUserDataNoChecks(int userId) {
1121 synchronized (mUsersLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001122 return mUsers.get(userId);
1123 }
1124 }
1125
Amith Yamasani236b2b52015-08-18 14:32:14 -07001126 /** Called by PackageManagerService */
Amith Yamasani13593602012-03-22 16:16:17 -07001127 public boolean exists(int userId) {
Todd Kennedy0eb97382017-10-03 16:57:22 -07001128 return mLocalService.exists(userId);
Amith Yamasani13593602012-03-22 16:16:17 -07001129 }
1130
Amith Yamasani258848d2012-08-10 17:06:33 -07001131 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001132 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001133 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001134 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -07001135 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001136 UserData userData = getUserDataNoChecks(userId);
1137 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001138 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
1139 return;
1140 }
Amith Yamasani12747872015-12-07 14:19:49 -08001141 if (name != null && !name.equals(userData.info.name)) {
1142 userData.info.name = name;
1143 writeUserLP(userData);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001144 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -07001145 }
1146 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001147 if (changed) {
1148 sendUserInfoChangedBroadcast(userId);
1149 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001150 }
1151
Amith Yamasani258848d2012-08-10 17:06:33 -07001152 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001153 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001154 checkManageUsersPermission("update users");
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01001155 if (hasUserRestriction(UserManager.DISALLOW_SET_USER_ICON, userId)) {
1156 Log.w(LOG_TAG, "Cannot set user icon. DISALLOW_SET_USER_ICON is enabled.");
1157 return;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001158 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01001159 mLocalService.setUserIcon(userId, bitmap);
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001160 }
1161
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01001162
1163
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001164 private void sendUserInfoChangedBroadcast(int userId) {
1165 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
1166 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
1167 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -07001168 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001169 }
1170
Amith Yamasani258848d2012-08-10 17:06:33 -07001171 @Override
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001172 public ParcelFileDescriptor getUserIcon(int targetUserId) {
Adrian Roos1bdff912015-02-17 15:51:35 +01001173 String iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001174 synchronized (mPackagesLock) {
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001175 UserInfo targetUserInfo = getUserInfoNoChecks(targetUserId);
1176 if (targetUserInfo == null || targetUserInfo.partial) {
1177 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + targetUserId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001178 return null;
1179 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001180
1181 final int callingUserId = UserHandle.getCallingUserId();
1182 final int callingGroupId = getUserInfoNoChecks(callingUserId).profileGroupId;
1183 final int targetGroupId = targetUserInfo.profileGroupId;
1184 final boolean sameGroup = (callingGroupId != UserInfo.NO_PROFILE_GROUP_ID
1185 && callingGroupId == targetGroupId);
1186 if ((callingUserId != targetUserId) && !sameGroup) {
Nicolas Prevot88cc3462014-05-14 14:51:48 +01001187 checkManageUsersPermission("get the icon of a user who is not related");
1188 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001189
1190 if (targetUserInfo.iconPath == null) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001191 return null;
1192 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001193 iconPath = targetUserInfo.iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001194 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001195
1196 try {
1197 return ParcelFileDescriptor.open(
1198 new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
1199 } catch (FileNotFoundException e) {
1200 Log.e(LOG_TAG, "Couldn't find icon file", e);
1201 }
1202 return null;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001203 }
1204
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001205 public void makeInitialized(int userId) {
1206 checkManageUsersPermission("makeInitialized");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001207 boolean scheduleWriteUser = false;
Amith Yamasani12747872015-12-07 14:19:49 -08001208 UserData userData;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001209 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001210 userData = mUsers.get(userId);
1211 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001212 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001213 return;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001214 }
Amith Yamasani12747872015-12-07 14:19:49 -08001215 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1216 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001217 scheduleWriteUser = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001218 }
1219 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001220 if (scheduleWriteUser) {
Amith Yamasani12747872015-12-07 14:19:49 -08001221 scheduleWriteUser(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001222 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001223 }
1224
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001225 /**
1226 * If default guest restrictions haven't been initialized yet, add the basic
1227 * restrictions.
1228 */
1229 private void initDefaultGuestRestrictions() {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001230 synchronized (mGuestRestrictions) {
1231 if (mGuestRestrictions.isEmpty()) {
Samuel Tand9453b82016-03-14 15:57:02 -07001232 mGuestRestrictions.putBoolean(UserManager.DISALLOW_CONFIG_WIFI, true);
Fyodor Kupolove04462c2015-11-30 15:02:53 -08001233 mGuestRestrictions.putBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, true);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001234 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
1235 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
1236 }
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001237 }
1238 }
1239
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001240 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301241 public Bundle getDefaultGuestRestrictions() {
1242 checkManageUsersPermission("getDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001243 synchronized (mGuestRestrictions) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301244 return new Bundle(mGuestRestrictions);
1245 }
1246 }
1247
1248 @Override
1249 public void setDefaultGuestRestrictions(Bundle restrictions) {
1250 checkManageUsersPermission("setDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001251 synchronized (mGuestRestrictions) {
1252 mGuestRestrictions.clear();
1253 mGuestRestrictions.putAll(restrictions);
1254 }
1255 synchronized (mPackagesLock) {
1256 writeUserListLP();
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301257 }
1258 }
1259
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001260 /**
Pavel Grafov6a40f092016-10-25 15:46:51 +01001261 * See {@link UserManagerInternal#setDevicePolicyUserRestrictions}
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001262 */
Pavel Grafov6a40f092016-10-25 15:46:51 +01001263 private void setDevicePolicyUserRestrictionsInner(int userId, @Nullable Bundle restrictions,
1264 boolean isDeviceOwner, int cameraRestrictionScope) {
1265 final Bundle global = new Bundle();
1266 final Bundle local = new Bundle();
1267
1268 // Sort restrictions into local and global ensuring they don't overlap.
1269 UserRestrictionsUtils.sortToGlobalAndLocal(restrictions, isDeviceOwner,
1270 cameraRestrictionScope, global, local);
1271
1272 boolean globalChanged, localChanged;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001273 synchronized (mRestrictionsLock) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001274 // Update global and local restrictions if they were changed.
1275 globalChanged = updateRestrictionsIfNeededLR(
1276 userId, global, mDevicePolicyGlobalUserRestrictions);
1277 localChanged = updateRestrictionsIfNeededLR(
1278 userId, local, mDevicePolicyLocalUserRestrictions);
1279
1280 if (isDeviceOwner) {
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001281 // Remember the global restriction owner userId to be able to make a distinction
1282 // in getUserRestrictionSource on who set local policies.
Pavel Grafov6a40f092016-10-25 15:46:51 +01001283 mDeviceOwnerUserId = userId;
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001284 } else {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001285 if (mDeviceOwnerUserId == userId) {
Zoltan Szatmary-Ban8a5536d2016-05-27 17:56:44 +01001286 // When profile owner sets restrictions it passes null global bundle and we
1287 // reset global restriction owner userId.
1288 // This means this user used to have DO, but now the DO is gone and the user
1289 // instead has PO.
Pavel Grafov6a40f092016-10-25 15:46:51 +01001290 mDeviceOwnerUserId = UserHandle.USER_NULL;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001291 }
1292 }
1293 }
1294 if (DBG) {
1295 Log.d(LOG_TAG, "setDevicePolicyUserRestrictions: userId=" + userId
1296 + " global=" + global + (globalChanged ? " (changed)" : "")
1297 + " local=" + local + (localChanged ? " (changed)" : "")
1298 );
1299 }
1300 // Don't call them within the mRestrictionsLock.
1301 synchronized (mPackagesLock) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001302 if (localChanged || globalChanged) {
Amith Yamasani12747872015-12-07 14:19:49 -08001303 writeUserLP(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001304 }
1305 }
1306
1307 synchronized (mRestrictionsLock) {
1308 if (globalChanged) {
1309 applyUserRestrictionsForAllUsersLR();
1310 } else if (localChanged) {
1311 applyUserRestrictionsLR(userId);
1312 }
1313 }
1314 }
1315
Pavel Grafov6a40f092016-10-25 15:46:51 +01001316 /**
1317 * Updates restriction bundle for a given user in a given restriction array. If new bundle is
1318 * empty, record is removed from the array.
1319 * @return whether restrictions bundle is different from the old one.
1320 */
1321 private boolean updateRestrictionsIfNeededLR(int userId, @Nullable Bundle restrictions,
1322 SparseArray<Bundle> restrictionsArray) {
1323 final boolean changed =
1324 !UserRestrictionsUtils.areEqual(restrictionsArray.get(userId), restrictions);
1325 if (changed) {
1326 if (!UserRestrictionsUtils.isEmpty(restrictions)) {
1327 restrictionsArray.put(userId, restrictions);
1328 } else {
1329 restrictionsArray.delete(userId);
1330 }
1331 }
1332 return changed;
1333 }
1334
Makoto Onuki068c54a2015-10-13 14:34:03 -07001335 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001336 private Bundle computeEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001337 final Bundle baseRestrictions =
1338 UserRestrictionsUtils.nonNull(mBaseUserRestrictions.get(userId));
Pavel Grafov6a40f092016-10-25 15:46:51 +01001339 final Bundle global = UserRestrictionsUtils.mergeAll(mDevicePolicyGlobalUserRestrictions);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001340 final Bundle local = mDevicePolicyLocalUserRestrictions.get(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001341
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001342 if (UserRestrictionsUtils.isEmpty(global) && UserRestrictionsUtils.isEmpty(local)) {
1343 // Common case first.
1344 return baseRestrictions;
Makoto Onuki068c54a2015-10-13 14:34:03 -07001345 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001346 final Bundle effective = UserRestrictionsUtils.clone(baseRestrictions);
1347 UserRestrictionsUtils.merge(effective, global);
1348 UserRestrictionsUtils.merge(effective, local);
1349
Makoto Onuki068c54a2015-10-13 14:34:03 -07001350 return effective;
1351 }
1352
1353 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001354 private void invalidateEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki068c54a2015-10-13 14:34:03 -07001355 if (DBG) {
1356 Log.d(LOG_TAG, "invalidateEffectiveUserRestrictions userId=" + userId);
1357 }
1358 mCachedEffectiveUserRestrictions.remove(userId);
1359 }
1360
1361 private Bundle getEffectiveUserRestrictions(int userId) {
1362 synchronized (mRestrictionsLock) {
1363 Bundle restrictions = mCachedEffectiveUserRestrictions.get(userId);
1364 if (restrictions == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001365 restrictions = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001366 mCachedEffectiveUserRestrictions.put(userId, restrictions);
1367 }
1368 return restrictions;
Amith Yamasani8cd28b52014-06-08 17:54:27 -07001369 }
1370 }
1371
Makoto Onuki068c54a2015-10-13 14:34:03 -07001372 /** @return a specific user restriction that's in effect currently. */
1373 @Override
1374 public boolean hasUserRestriction(String restrictionKey, int userId) {
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001375 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1376 return false;
1377 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001378 Bundle restrictions = getEffectiveUserRestrictions(userId);
1379 return restrictions != null && restrictions.getBoolean(restrictionKey);
1380 }
1381
1382 /**
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001383 * @hide
1384 *
1385 * Returns who set a user restriction on a user.
1386 * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
1387 * @param restrictionKey the string key representing the restriction
1388 * @param userId the id of the user for whom to retrieve the restrictions.
1389 * @return The source of user restriction. Any combination of
1390 * {@link UserManager#RESTRICTION_NOT_SET},
1391 * {@link UserManager#RESTRICTION_SOURCE_SYSTEM},
1392 * {@link UserManager#RESTRICTION_SOURCE_DEVICE_OWNER}
1393 * and {@link UserManager#RESTRICTION_SOURCE_PROFILE_OWNER}
1394 */
1395 @Override
1396 public int getUserRestrictionSource(String restrictionKey, int userId) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001397 List<EnforcingUser> enforcingUsers = getUserRestrictionSources(restrictionKey, userId);
1398 // Get "bitwise or" of restriction sources for all enforcing users.
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001399 int result = UserManager.RESTRICTION_NOT_SET;
Pavel Grafov6a40f092016-10-25 15:46:51 +01001400 for (int i = enforcingUsers.size() - 1; i >= 0; i--) {
1401 result |= enforcingUsers.get(i).getUserRestrictionSource();
1402 }
1403 return result;
1404 }
1405
1406 @Override
1407 public List<EnforcingUser> getUserRestrictionSources(
1408 String restrictionKey, @UserIdInt int userId) {
1409 checkManageUsersPermission("getUserRestrictionSource");
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001410
1411 // Shortcut for the most common case
1412 if (!hasUserRestriction(restrictionKey, userId)) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001413 return Collections.emptyList();
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001414 }
1415
Pavel Grafov6a40f092016-10-25 15:46:51 +01001416 final List<EnforcingUser> result = new ArrayList<>();
1417
1418 // Check if it is base restriction.
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001419 if (hasBaseUserRestriction(restrictionKey, userId)) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001420 result.add(new EnforcingUser(
1421 UserHandle.USER_NULL, UserManager.RESTRICTION_SOURCE_SYSTEM));
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001422 }
1423
Pavel Grafov6a40f092016-10-25 15:46:51 +01001424 synchronized (mRestrictionsLock) {
1425 // Check if it is set by profile owner.
1426 Bundle profileOwnerRestrictions = mDevicePolicyLocalUserRestrictions.get(userId);
1427 if (UserRestrictionsUtils.contains(profileOwnerRestrictions, restrictionKey)) {
1428 result.add(getEnforcingUserLocked(userId));
1429 }
1430
1431 // Iterate over all users who enforce global restrictions.
1432 for (int i = mDevicePolicyGlobalUserRestrictions.size() - 1; i >= 0; i--) {
1433 Bundle globalRestrictions = mDevicePolicyGlobalUserRestrictions.valueAt(i);
1434 int profileUserId = mDevicePolicyGlobalUserRestrictions.keyAt(i);
1435 if (UserRestrictionsUtils.contains(globalRestrictions, restrictionKey)) {
1436 result.add(getEnforcingUserLocked(profileUserId));
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001437 }
1438 }
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001439 }
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001440 return result;
1441 }
1442
Pavel Grafov6a40f092016-10-25 15:46:51 +01001443 private EnforcingUser getEnforcingUserLocked(@UserIdInt int userId) {
1444 int source = mDeviceOwnerUserId == userId ? UserManager.RESTRICTION_SOURCE_DEVICE_OWNER
1445 : UserManager.RESTRICTION_SOURCE_PROFILE_OWNER;
1446 return new EnforcingUser(userId, source);
1447 }
1448
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001449 /**
Makoto Onuki068c54a2015-10-13 14:34:03 -07001450 * @return UserRestrictions that are in effect currently. This always returns a new
1451 * {@link Bundle}.
1452 */
Amith Yamasani8cd28b52014-06-08 17:54:27 -07001453 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001454 public Bundle getUserRestrictions(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001455 return UserRestrictionsUtils.clone(getEffectiveUserRestrictions(userId));
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001456 }
1457
1458 @Override
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +00001459 public boolean hasBaseUserRestriction(String restrictionKey, int userId) {
1460 checkManageUsersPermission("hasBaseUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001461 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1462 return false;
1463 }
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +00001464 synchronized (mRestrictionsLock) {
1465 Bundle bundle = mBaseUserRestrictions.get(userId);
1466 return (bundle != null && bundle.getBoolean(restrictionKey, false));
1467 }
1468 }
1469
1470 @Override
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001471 public void setUserRestriction(String key, boolean value, int userId) {
Fyodor Kupolovd4b26042015-07-27 14:30:59 -07001472 checkManageUsersPermission("setUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001473 if (!UserRestrictionsUtils.isValidRestriction(key)) {
1474 return;
1475 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001476 synchronized (mRestrictionsLock) {
1477 // Note we can't modify Bundles stored in mBaseUserRestrictions directly, so create
1478 // a copy.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001479 final Bundle newRestrictions = UserRestrictionsUtils.clone(
1480 mBaseUserRestrictions.get(userId));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001481 newRestrictions.putBoolean(key, value);
1482
Fyodor Kupolov82402752015-10-28 14:54:51 -07001483 updateUserRestrictionsInternalLR(newRestrictions, userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001484 }
1485 }
1486
Makoto Onuki068c54a2015-10-13 14:34:03 -07001487 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001488 * Optionally updating user restrictions, calculate the effective user restrictions and also
1489 * propagate to other services and system settings.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001490 *
Pavel Grafov6a40f092016-10-25 15:46:51 +01001491 * @param newBaseRestrictions User restrictions to set.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001492 * If null, will not update user restrictions and only does the propagation.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001493 * @param userId target user ID.
1494 */
1495 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001496 private void updateUserRestrictionsInternalLR(
Pavel Grafov6a40f092016-10-25 15:46:51 +01001497 @Nullable Bundle newBaseRestrictions, int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001498 final Bundle prevAppliedRestrictions = UserRestrictionsUtils.nonNull(
1499 mAppliedUserRestrictions.get(userId));
1500
1501 // Update base restrictions.
Pavel Grafov6a40f092016-10-25 15:46:51 +01001502 if (newBaseRestrictions != null) {
1503 // If newBaseRestrictions == the current one, it's probably a bug.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001504 final Bundle prevBaseRestrictions = mBaseUserRestrictions.get(userId);
1505
Pavel Grafov6a40f092016-10-25 15:46:51 +01001506 Preconditions.checkState(prevBaseRestrictions != newBaseRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001507 Preconditions.checkState(mCachedEffectiveUserRestrictions.get(userId)
Pavel Grafov6a40f092016-10-25 15:46:51 +01001508 != newBaseRestrictions);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001509
Pavel Grafov6a40f092016-10-25 15:46:51 +01001510 if (updateRestrictionsIfNeededLR(userId, newBaseRestrictions, mBaseUserRestrictions)) {
Amith Yamasani12747872015-12-07 14:19:49 -08001511 scheduleWriteUser(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001512 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001513 }
1514
Fyodor Kupolov82402752015-10-28 14:54:51 -07001515 final Bundle effective = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001516
Makoto Onuki759a7632015-10-28 16:43:10 -07001517 mCachedEffectiveUserRestrictions.put(userId, effective);
1518
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001519 // Apply the new restrictions.
Makoto Onuki4f160732015-10-27 17:15:38 -07001520 if (DBG) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001521 debug("Applying user restrictions: userId=" + userId
1522 + " new=" + effective + " prev=" + prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001523 }
1524
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001525 if (mAppOpsService != null) { // We skip it until system-ready.
Fyodor Kupolovec30ca32016-06-16 15:09:29 -07001526 mHandler.post(new Runnable() {
1527 @Override
1528 public void run() {
1529 try {
1530 mAppOpsService.setUserRestrictions(effective, mUserRestriconToken, userId);
1531 } catch (RemoteException e) {
1532 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
1533 }
1534 }
1535 });
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001536 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001537
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001538 propagateUserRestrictionsLR(userId, effective, prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001539
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001540 mAppliedUserRestrictions.put(userId, new Bundle(effective));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001541 }
1542
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001543 private void propagateUserRestrictionsLR(final int userId,
Makoto Onukid45a4a22015-11-02 17:17:38 -08001544 Bundle newRestrictions, Bundle prevRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001545 // Note this method doesn't touch any state, meaning it doesn't require mRestrictionsLock
1546 // actually, but we still need some kind of synchronization otherwise we might end up
1547 // calling listeners out-of-order, thus "LR".
1548
1549 if (UserRestrictionsUtils.areEqual(newRestrictions, prevRestrictions)) {
1550 return;
1551 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08001552
1553 final Bundle newRestrictionsFinal = new Bundle(newRestrictions);
1554 final Bundle prevRestrictionsFinal = new Bundle(prevRestrictions);
1555
1556 mHandler.post(new Runnable() {
1557 @Override
1558 public void run() {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07001559 UserRestrictionsUtils.applyUserRestrictions(
1560 mContext, userId, newRestrictionsFinal, prevRestrictionsFinal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001561
Makoto Onukid45a4a22015-11-02 17:17:38 -08001562 final UserRestrictionsListener[] listeners;
1563 synchronized (mUserRestrictionsListeners) {
1564 listeners = new UserRestrictionsListener[mUserRestrictionsListeners.size()];
1565 mUserRestrictionsListeners.toArray(listeners);
1566 }
1567 for (int i = 0; i < listeners.length; i++) {
1568 listeners[i].onUserRestrictionsChanged(userId,
1569 newRestrictionsFinal, prevRestrictionsFinal);
1570 }
Makoto Onukie72f81b2017-03-16 14:08:19 -07001571
1572 final Intent broadcast = new Intent(UserManager.ACTION_USER_RESTRICTIONS_CHANGED)
1573 .setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
1574 mContext.sendBroadcastAsUser(broadcast, UserHandle.of(userId));
Makoto Onukid45a4a22015-11-02 17:17:38 -08001575 }
1576 });
1577 }
1578
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001579 // Package private for the inner class.
1580 void applyUserRestrictionsLR(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001581 updateUserRestrictionsInternalLR(null, userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001582 }
1583
1584 @GuardedBy("mRestrictionsLock")
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001585 // Package private for the inner class.
1586 void applyUserRestrictionsForAllUsersLR() {
1587 if (DBG) {
1588 debug("applyUserRestrictionsForAllUsersLR");
1589 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001590 // First, invalidate all cached values.
Makoto Onuki4f160732015-10-27 17:15:38 -07001591 mCachedEffectiveUserRestrictions.clear();
1592
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001593 // We don't want to call into ActivityManagerService while taking a lock, so we'll call
Makoto Onuki068c54a2015-10-13 14:34:03 -07001594 // it on a handler.
1595 final Runnable r = new Runnable() {
1596 @Override
1597 public void run() {
1598 // Then get the list of running users.
1599 final int[] runningUsers;
1600 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001601 runningUsers = ActivityManager.getService().getRunningUserIds();
Makoto Onuki068c54a2015-10-13 14:34:03 -07001602 } catch (RemoteException e) {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001603 Log.w(LOG_TAG, "Unable to access ActivityManagerService");
Makoto Onuki068c54a2015-10-13 14:34:03 -07001604 return;
1605 }
1606 // Then re-calculate the effective restrictions and apply, only for running users.
1607 // It's okay if a new user has started after the getRunningUserIds() call,
1608 // because we'll do the same thing (re-calculate the restrictions and apply)
1609 // when we start a user.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001610 synchronized (mRestrictionsLock) {
1611 for (int i = 0; i < runningUsers.length; i++) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001612 applyUserRestrictionsLR(runningUsers[i]);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001613 }
1614 }
1615 }
1616 };
1617 mHandler.post(r);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001618 }
1619
Amith Yamasani258848d2012-08-10 17:06:33 -07001620 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001621 * Check if we've hit the limit of how many users can be created.
1622 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001623 private boolean isUserLimitReached() {
1624 int count;
1625 synchronized (mUsersLock) {
1626 count = getAliveUsersExcludingGuestsCountLU();
1627 }
1628 return count >= UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001629 }
1630
1631 @Override
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001632 public boolean canAddMoreManagedProfiles(int userId, boolean allowedToRemoveOne) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001633 checkManageUsersPermission("check if more managed profiles can be added.");
1634 if (ActivityManager.isLowRamDeviceStatic()) {
1635 return false;
1636 }
Fyodor Kupolovb6157992015-06-05 15:32:28 -07001637 if (!mContext.getPackageManager().hasSystemFeature(
1638 PackageManager.FEATURE_MANAGED_USERS)) {
1639 return false;
1640 }
Nicolas Prevotb8186812015-08-06 15:00:03 +01001641 // Limit number of managed profiles that can be created
Benjamin Franzc8776152017-01-06 14:16:41 +00001642 final int managedProfilesCount = getProfiles(userId, false).size() - 1;
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001643 final int profilesRemovedCount = managedProfilesCount > 0 && allowedToRemoveOne ? 1 : 0;
Kenny Guy02c89902016-11-15 19:36:38 +00001644 if (managedProfilesCount - profilesRemovedCount >= getMaxManagedProfiles()) {
Nicolas Prevotb8186812015-08-06 15:00:03 +01001645 return false;
1646 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001647 synchronized(mUsersLock) {
1648 UserInfo userInfo = getUserInfoLU(userId);
yuanhao47f9f7c2017-01-18 09:54:45 +08001649 if (userInfo == null || !userInfo.canHaveProfile()) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001650 return false;
1651 }
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001652 int usersCountAfterRemoving = getAliveUsersExcludingGuestsCountLU()
1653 - profilesRemovedCount;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001654 // We allow creating a managed profile in the special case where there is only one user.
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001655 return usersCountAfterRemoving == 1
1656 || usersCountAfterRemoving < UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001657 }
1658 }
1659
Fyodor Kupolov82402752015-10-28 14:54:51 -07001660 private int getAliveUsersExcludingGuestsCountLU() {
Amith Yamasanif584f012014-05-19 17:57:25 -07001661 int aliveUserCount = 0;
1662 final int totalUserCount = mUsers.size();
1663 // Skip over users being removed
1664 for (int i = 0; i < totalUserCount; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001665 UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov6e99d3f2016-11-01 17:18:41 -07001666 if (!mRemovingUserIds.get(user.id) && !user.isGuest()) {
Amith Yamasanif584f012014-05-19 17:57:25 -07001667 aliveUserCount++;
1668 }
1669 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001670 return aliveUserCount;
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001671 }
1672
1673 /**
Amith Yamasani195263742012-08-21 15:40:12 -07001674 * Enforces that only the system UID or root's UID or apps that have the
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001675 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} and
1676 * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL INTERACT_ACROSS_USERS_FULL}
1677 * permissions can make certain calls to the UserManager.
1678 *
1679 * @param message used as message if SecurityException is thrown
1680 * @throws SecurityException if the caller does not have enough privilege.
1681 */
1682 private static final void checkManageUserAndAcrossUsersFullPermission(String message) {
1683 final int uid = Binder.getCallingUid();
1684 if (uid != Process.SYSTEM_UID && uid != 0
1685 && ActivityManager.checkComponentPermission(
1686 Manifest.permission.MANAGE_USERS,
1687 uid, -1, true) != PackageManager.PERMISSION_GRANTED
1688 && ActivityManager.checkComponentPermission(
1689 Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1690 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
1691 throw new SecurityException(
1692 "You need MANAGE_USERS and INTERACT_ACROSS_USERS_FULL permission to: "
1693 + message);
1694 }
1695 }
1696
1697 /**
1698 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001699 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -07001700 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -07001701 *
1702 * @param message used as message if SecurityException is thrown
1703 * @throws SecurityException if the caller is not system or root
Tony Mak4dc008c2016-03-16 10:46:49 +00001704 * @see #hasManageUsersPermission()
Amith Yamasani258848d2012-08-10 17:06:33 -07001705 */
Amith Yamasanibe465322014-04-24 13:45:17 -07001706 private static final void checkManageUsersPermission(String message) {
Tony Mak4dc008c2016-03-16 10:46:49 +00001707 if (!hasManageUsersPermission()) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001708 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
1709 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -04001710 }
1711
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001712 /**
Sudheer Shankaf5cea032016-06-08 17:13:24 -07001713 * Enforces that only the system UID or root's UID or apps that have the
1714 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or
1715 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS}
1716 * can make certain calls to the UserManager.
1717 *
1718 * @param message used as message if SecurityException is thrown
1719 * @throws SecurityException if the caller is not system or root
1720 * @see #hasManageOrCreateUsersPermission()
1721 */
1722 private static final void checkManageOrCreateUsersPermission(String message) {
1723 if (!hasManageOrCreateUsersPermission()) {
1724 throw new SecurityException(
1725 "You either need MANAGE_USERS or CREATE_USERS permission to: " + message);
1726 }
1727 }
1728
1729 /**
1730 * Similar to {@link #checkManageOrCreateUsersPermission(String)} but when the caller is tries
1731 * to create user/profiles other than what is allowed for
1732 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS} permission, then it will only
1733 * allow callers with {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} permission.
1734 */
1735 private static final void checkManageOrCreateUsersPermission(int creationFlags) {
1736 if ((creationFlags & ~ALLOWED_FLAGS_FOR_CREATE_USERS_PERMISSION) == 0) {
1737 if (!hasManageOrCreateUsersPermission()) {
1738 throw new SecurityException("You either need MANAGE_USERS or CREATE_USERS "
1739 + "permission to create an user with flags: " + creationFlags);
1740 }
1741 } else if (!hasManageUsersPermission()) {
1742 throw new SecurityException("You need MANAGE_USERS permission to create an user "
1743 + " with flags: " + creationFlags);
1744 }
1745 }
1746
1747 /**
Tony Mak4dc008c2016-03-16 10:46:49 +00001748 * @return whether the calling UID is system UID or root's UID or the calling app has the
1749 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}.
1750 */
1751 private static final boolean hasManageUsersPermission() {
1752 final int callingUid = Binder.getCallingUid();
1753 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
1754 || callingUid == Process.ROOT_UID
1755 || ActivityManager.checkComponentPermission(
1756 android.Manifest.permission.MANAGE_USERS,
1757 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED;
1758 }
1759
1760 /**
Sudheer Shankaf5cea032016-06-08 17:13:24 -07001761 * @return whether the calling UID is system UID or root's UID or the calling app has the
1762 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or
1763 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS}.
1764 */
1765 private static final boolean hasManageOrCreateUsersPermission() {
1766 final int callingUid = Binder.getCallingUid();
1767 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
1768 || callingUid == Process.ROOT_UID
1769 || ActivityManager.checkComponentPermission(
1770 android.Manifest.permission.MANAGE_USERS,
1771 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED
1772 || ActivityManager.checkComponentPermission(
1773 android.Manifest.permission.CREATE_USERS,
1774 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED;
1775 }
1776
1777 /**
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001778 * Enforces that only the system UID or root's UID (on any user) can make certain calls to the
1779 * UserManager.
1780 *
1781 * @param message used as message if SecurityException is thrown
1782 * @throws SecurityException if the caller is not system or root
1783 */
1784 private static void checkSystemOrRoot(String message) {
1785 final int uid = Binder.getCallingUid();
1786 if (!UserHandle.isSameApp(uid, Process.SYSTEM_UID) && uid != Process.ROOT_UID) {
1787 throw new SecurityException("Only system may: " + message);
1788 }
1789 }
1790
Fyodor Kupolov82402752015-10-28 14:54:51 -07001791 private void writeBitmapLP(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001792 try {
1793 File dir = new File(mUsersDir, Integer.toString(info.id));
1794 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +01001795 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001796 if (!dir.exists()) {
1797 dir.mkdir();
1798 FileUtils.setPermissions(
1799 dir.getPath(),
1800 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
1801 -1, -1);
1802 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001803 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +01001804 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001805 && tmp.renameTo(file) && SELinux.restorecon(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -07001806 info.iconPath = file.getAbsolutePath();
1807 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001808 try {
1809 os.close();
1810 } catch (IOException ioe) {
1811 // What the ... !
1812 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001813 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001814 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001815 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001816 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001817 }
1818
Amith Yamasani0b285492011-04-14 17:35:23 -07001819 /**
1820 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
1821 * cache it elsewhere.
1822 * @return the array of user ids.
1823 */
Dianne Hackborn1676c852012-09-10 14:52:30 -07001824 public int[] getUserIds() {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001825 synchronized (mUsersLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001826 return mUserIds;
1827 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001828 }
1829
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001830 private void readUserListLP() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001831 if (!mUserListFile.exists()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001832 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001833 return;
1834 }
1835 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001836 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001837 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001838 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001839 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001840 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001841 int type;
1842 while ((type = parser.next()) != XmlPullParser.START_TAG
1843 && type != XmlPullParser.END_DOCUMENT) {
Amith Yamasani12747872015-12-07 14:19:49 -08001844 // Skip
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001845 }
1846
1847 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001848 Slog.e(LOG_TAG, "Unable to read user list");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001849 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001850 return;
1851 }
1852
Amith Yamasani2a003292012-08-14 18:25:45 -07001853 mNextSerialNumber = -1;
1854 if (parser.getName().equals(TAG_USERS)) {
1855 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
1856 if (lastSerialNumber != null) {
1857 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
1858 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001859 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
1860 if (versionNumber != null) {
1861 mUserVersion = Integer.parseInt(versionNumber);
1862 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001863 }
1864
Pavel Grafov6a40f092016-10-25 15:46:51 +01001865 // Pre-O global user restriction were stored as a single bundle (as opposed to per-user
1866 // currently), take care of it in case of upgrade.
1867 Bundle oldDevicePolicyGlobalUserRestrictions = null;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001868
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001869 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301870 if (type == XmlPullParser.START_TAG) {
1871 final String name = parser.getName();
1872 if (name.equals(TAG_USER)) {
1873 String id = parser.getAttributeValue(null, ATTR_ID);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001874
Amith Yamasani12747872015-12-07 14:19:49 -08001875 UserData userData = readUserLP(Integer.parseInt(id));
1876
1877 if (userData != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001878 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001879 mUsers.put(userData.info.id, userData);
1880 if (mNextSerialNumber < 0
1881 || mNextSerialNumber <= userData.info.id) {
1882 mNextSerialNumber = userData.info.id + 1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001883 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301884 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001885 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301886 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -08001887 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1888 && type != XmlPullParser.END_TAG) {
1889 if (type == XmlPullParser.START_TAG) {
1890 if (parser.getName().equals(TAG_RESTRICTIONS)) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001891 synchronized (mGuestRestrictions) {
Fyodor Kupoloveafee022017-03-15 17:09:04 -07001892 UserRestrictionsUtils
1893 .readRestrictions(parser, mGuestRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001894 }
Amith Yamasanida0b1682014-11-21 12:58:17 -08001895 }
1896 break;
1897 }
1898 }
Pavel Grafov6a40f092016-10-25 15:46:51 +01001899 } else if (name.equals(TAG_DEVICE_OWNER_USER_ID)
1900 // Legacy name, should only be encountered when upgrading from pre-O.
1901 || name.equals(TAG_GLOBAL_RESTRICTION_OWNER_ID)) {
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001902 String ownerUserId = parser.getAttributeValue(null, ATTR_ID);
1903 if (ownerUserId != null) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001904 mDeviceOwnerUserId = Integer.parseInt(ownerUserId);
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001905 }
Pavel Grafov6a40f092016-10-25 15:46:51 +01001906 } else if (name.equals(TAG_DEVICE_POLICY_RESTRICTIONS)) {
1907 // Should only happen when upgrading from pre-O (version < 7).
1908 oldDevicePolicyGlobalUserRestrictions =
1909 UserRestrictionsUtils.readRestrictions(parser);
Amith Yamasani258848d2012-08-10 17:06:33 -07001910 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001911 }
1912 }
Pavel Grafov6a40f092016-10-25 15:46:51 +01001913
Fyodor Kupolov82402752015-10-28 14:54:51 -07001914 updateUserIds();
Pavel Grafov6a40f092016-10-25 15:46:51 +01001915 upgradeIfNecessaryLP(oldDevicePolicyGlobalUserRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001916 } catch (IOException | XmlPullParserException e) {
1917 fallbackToSingleUserLP();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001918 } finally {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001919 IoUtils.closeQuietly(fis);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001920 }
1921 }
1922
Amith Yamasani6f34b412012-10-22 18:19:27 -07001923 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -08001924 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Pavel Grafov6a40f092016-10-25 15:46:51 +01001925 * @param oldGlobalUserRestrictions Pre-O global device policy restrictions.
Amith Yamasani6f34b412012-10-22 18:19:27 -07001926 */
Pavel Grafov6a40f092016-10-25 15:46:51 +01001927 private void upgradeIfNecessaryLP(Bundle oldGlobalUserRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001928 final int originalVersion = mUserVersion;
Amith Yamasani6f34b412012-10-22 18:19:27 -07001929 int userVersion = mUserVersion;
1930 if (userVersion < 1) {
1931 // Assign a proper name for the owner, if not initialized correctly before
Amith Yamasani12747872015-12-07 14:19:49 -08001932 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
1933 if ("Primary".equals(userData.info.name)) {
1934 userData.info.name =
1935 mContext.getResources().getString(com.android.internal.R.string.owner_name);
1936 scheduleWriteUser(userData);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001937 }
1938 userVersion = 1;
1939 }
1940
Amith Yamasanibc9625052012-11-15 14:39:18 -08001941 if (userVersion < 2) {
1942 // Owner should be marked as initialized
Amith Yamasani12747872015-12-07 14:19:49 -08001943 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
1944 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1945 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
1946 scheduleWriteUser(userData);
Amith Yamasanibc9625052012-11-15 14:39:18 -08001947 }
1948 userVersion = 2;
1949 }
1950
Amith Yamasani350962c2013-08-06 11:18:53 -07001951
Amith Yamasani5e486f52013-08-07 11:06:44 -07001952 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -07001953 userVersion = 4;
1954 }
1955
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001956 if (userVersion < 5) {
1957 initDefaultGuestRestrictions();
1958 userVersion = 5;
1959 }
1960
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001961 if (userVersion < 6) {
1962 final boolean splitSystemUser = UserManager.isSplitSystemUser();
Fyodor Kupolov82402752015-10-28 14:54:51 -07001963 synchronized (mUsersLock) {
1964 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001965 UserData userData = mUsers.valueAt(i);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001966 // In non-split mode, only user 0 can have restricted profiles
Amith Yamasani12747872015-12-07 14:19:49 -08001967 if (!splitSystemUser && userData.info.isRestricted()
1968 && (userData.info.restrictedProfileParentId
1969 == UserInfo.NO_PROFILE_GROUP_ID)) {
1970 userData.info.restrictedProfileParentId = UserHandle.USER_SYSTEM;
1971 scheduleWriteUser(userData);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001972 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001973 }
1974 }
1975 userVersion = 6;
1976 }
1977
Pavel Grafov6a40f092016-10-25 15:46:51 +01001978 if (userVersion < 7) {
1979 // Previously only one user could enforce global restrictions, now it is per-user.
1980 synchronized (mRestrictionsLock) {
1981 if (!UserRestrictionsUtils.isEmpty(oldGlobalUserRestrictions)
1982 && mDeviceOwnerUserId != UserHandle.USER_NULL) {
1983 mDevicePolicyGlobalUserRestrictions.put(
1984 mDeviceOwnerUserId, oldGlobalUserRestrictions);
1985 }
1986 // ENSURE_VERIFY_APPS is now enforced globally even if put by profile owner, so move
1987 // it from local to global bundle for all users who set it.
1988 UserRestrictionsUtils.moveRestriction(UserManager.ENSURE_VERIFY_APPS,
1989 mDevicePolicyLocalUserRestrictions, mDevicePolicyGlobalUserRestrictions
1990 );
1991 }
1992 userVersion = 7;
1993 }
1994
Amith Yamasani6f34b412012-10-22 18:19:27 -07001995 if (userVersion < USER_VERSION) {
1996 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
1997 + USER_VERSION);
1998 } else {
1999 mUserVersion = userVersion;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002000
2001 if (originalVersion < mUserVersion) {
2002 writeUserListLP();
2003 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07002004 }
2005 }
2006
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002007 private void fallbackToSingleUserLP() {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07002008 int flags = UserInfo.FLAG_INITIALIZED;
2009 // In split system user mode, the admin and primary flags are assigned to the first human
2010 // user.
2011 if (!UserManager.isSplitSystemUser()) {
2012 flags |= UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY;
2013 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -07002014 // Create the system user
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07002015 UserInfo system = new UserInfo(UserHandle.USER_SYSTEM, null, null, flags);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002016 UserData userData = putUserInfo(system);
Amith Yamasani634cf312012-10-04 17:34:21 -07002017 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -04002018 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -08002019
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05002020 Bundle restrictions = new Bundle();
Mahaver Chopra3d9805d2016-07-07 16:25:05 +01002021 try {
2022 final String[] defaultFirstUserRestrictions = mContext.getResources().getStringArray(
2023 com.android.internal.R.array.config_defaultFirstUserRestrictions);
2024 for (String userRestriction : defaultFirstUserRestrictions) {
2025 if (UserRestrictionsUtils.isValidRestriction(userRestriction)) {
2026 restrictions.putBoolean(userRestriction, true);
2027 }
2028 }
2029 } catch (Resources.NotFoundException e) {
2030 Log.e(LOG_TAG, "Couldn't find resource: config_defaultFirstUserRestrictions", e);
2031 }
2032
Pavel Grafov6a40f092016-10-25 15:46:51 +01002033 if (!restrictions.isEmpty()) {
2034 synchronized (mRestrictionsLock) {
2035 mBaseUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions);
2036 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07002037 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08002038
Fyodor Kupolov82402752015-10-28 14:54:51 -07002039 updateUserIds();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07002040 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002041
Amith Yamasani12747872015-12-07 14:19:49 -08002042 writeUserLP(userData);
Jeff Sharkeycd575992016-03-29 14:12:49 -06002043 writeUserListLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002044 }
2045
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07002046 private String getOwnerName() {
2047 return mContext.getResources().getString(com.android.internal.R.string.owner_name);
2048 }
2049
Amith Yamasani12747872015-12-07 14:19:49 -08002050 private void scheduleWriteUser(UserData UserData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002051 if (DBG) {
2052 debug("scheduleWriteUser");
2053 }
Makoto Onuki9e935a32015-11-06 14:24:24 -08002054 // No need to wrap it within a lock -- worst case, we'll just post the same message
2055 // twice.
Amith Yamasani12747872015-12-07 14:19:49 -08002056 if (!mHandler.hasMessages(WRITE_USER_MSG, UserData)) {
2057 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, UserData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002058 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
2059 }
2060 }
2061
Amith Yamasani12747872015-12-07 14:19:49 -08002062 private void writeUserLP(UserData userData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002063 if (DBG) {
Amith Yamasani12747872015-12-07 14:19:49 -08002064 debug("writeUserLP " + userData);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002065 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002066 FileOutputStream fos = null;
Amith Yamasani12747872015-12-07 14:19:49 -08002067 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userData.info.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002068 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07002069 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002070 final BufferedOutputStream bos = new BufferedOutputStream(fos);
Kenny Guy02c89902016-11-15 19:36:38 +00002071 writeUserLP(userData, bos);
Amith Yamasani2a003292012-08-14 18:25:45 -07002072 userFile.finishWrite(fos);
2073 } catch (Exception ioe) {
Jeff Sharkeycd575992016-03-29 14:12:49 -06002074 Slog.e(LOG_TAG, "Error writing user info " + userData.info.id, ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -07002075 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002076 }
2077 }
2078
2079 /*
Kenny Guy02c89902016-11-15 19:36:38 +00002080 * Writes the user file in this format:
2081 *
2082 * <user flags="20039023" id="0">
2083 * <name>Primary</name>
2084 * </user>
2085 */
2086 @VisibleForTesting
2087 void writeUserLP(UserData userData, OutputStream os)
2088 throws IOException, XmlPullParserException {
2089 // XmlSerializer serializer = XmlUtils.serializerInstance();
2090 final XmlSerializer serializer = new FastXmlSerializer();
2091 serializer.setOutput(os, StandardCharsets.UTF_8.name());
2092 serializer.startDocument(null, true);
2093 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2094
2095 final UserInfo userInfo = userData.info;
2096 serializer.startTag(null, TAG_USER);
2097 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
2098 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
2099 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
2100 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
2101 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
2102 Long.toString(userInfo.lastLoggedInTime));
2103 if (userInfo.lastLoggedInFingerprint != null) {
2104 serializer.attribute(null, ATTR_LAST_LOGGED_IN_FINGERPRINT,
2105 userInfo.lastLoggedInFingerprint);
2106 }
2107 if (userInfo.iconPath != null) {
2108 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
2109 }
2110 if (userInfo.partial) {
2111 serializer.attribute(null, ATTR_PARTIAL, "true");
2112 }
2113 if (userInfo.guestToRemove) {
2114 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
2115 }
2116 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
2117 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
2118 Integer.toString(userInfo.profileGroupId));
2119 }
2120 serializer.attribute(null, ATTR_PROFILE_BADGE,
2121 Integer.toString(userInfo.profileBadge));
2122 if (userInfo.restrictedProfileParentId != UserInfo.NO_PROFILE_GROUP_ID) {
2123 serializer.attribute(null, ATTR_RESTRICTED_PROFILE_PARENT_ID,
2124 Integer.toString(userInfo.restrictedProfileParentId));
2125 }
2126 // Write seed data
2127 if (userData.persistSeedData) {
2128 if (userData.seedAccountName != null) {
2129 serializer.attribute(null, ATTR_SEED_ACCOUNT_NAME, userData.seedAccountName);
2130 }
2131 if (userData.seedAccountType != null) {
2132 serializer.attribute(null, ATTR_SEED_ACCOUNT_TYPE, userData.seedAccountType);
2133 }
2134 }
2135 if (userInfo.name != null) {
2136 serializer.startTag(null, TAG_NAME);
2137 serializer.text(userInfo.name);
2138 serializer.endTag(null, TAG_NAME);
2139 }
2140 synchronized (mRestrictionsLock) {
2141 UserRestrictionsUtils.writeRestrictions(serializer,
2142 mBaseUserRestrictions.get(userInfo.id), TAG_RESTRICTIONS);
2143 UserRestrictionsUtils.writeRestrictions(serializer,
2144 mDevicePolicyLocalUserRestrictions.get(userInfo.id),
2145 TAG_DEVICE_POLICY_RESTRICTIONS);
Pavel Grafov6a40f092016-10-25 15:46:51 +01002146 UserRestrictionsUtils.writeRestrictions(serializer,
2147 mDevicePolicyGlobalUserRestrictions.get(userInfo.id),
2148 TAG_DEVICE_POLICY_GLOBAL_RESTRICTIONS);
Kenny Guy02c89902016-11-15 19:36:38 +00002149 }
2150
2151 if (userData.account != null) {
2152 serializer.startTag(null, TAG_ACCOUNT);
2153 serializer.text(userData.account);
2154 serializer.endTag(null, TAG_ACCOUNT);
2155 }
2156
2157 if (userData.persistSeedData && userData.seedAccountOptions != null) {
2158 serializer.startTag(null, TAG_SEED_ACCOUNT_OPTIONS);
2159 userData.seedAccountOptions.saveToXml(serializer);
2160 serializer.endTag(null, TAG_SEED_ACCOUNT_OPTIONS);
2161 }
2162
2163 serializer.endTag(null, TAG_USER);
2164
2165 serializer.endDocument();
2166 }
2167
2168 /*
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002169 * Writes the user list file in this format:
2170 *
Amith Yamasani2a003292012-08-14 18:25:45 -07002171 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002172 * <user id="0"></user>
2173 * <user id="2"></user>
2174 * </users>
2175 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002176 private void writeUserListLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002177 if (DBG) {
2178 debug("writeUserList");
2179 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002180 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07002181 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002182 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07002183 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002184 final BufferedOutputStream bos = new BufferedOutputStream(fos);
2185
2186 // XmlSerializer serializer = XmlUtils.serializerInstance();
2187 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002188 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002189 serializer.startDocument(null, true);
2190 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2191
2192 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -07002193 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -07002194 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002195
Adam Lesinskieddeb492014-09-08 17:50:03 -07002196 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002197 synchronized (mGuestRestrictions) {
2198 UserRestrictionsUtils
2199 .writeRestrictions(serializer, mGuestRestrictions, TAG_RESTRICTIONS);
2200 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05302201 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Pavel Grafov6a40f092016-10-25 15:46:51 +01002202 serializer.startTag(null, TAG_DEVICE_OWNER_USER_ID);
2203 serializer.attribute(null, ATTR_ID, Integer.toString(mDeviceOwnerUserId));
2204 serializer.endTag(null, TAG_DEVICE_OWNER_USER_ID);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002205 int[] userIdsToWrite;
2206 synchronized (mUsersLock) {
2207 userIdsToWrite = new int[mUsers.size()];
2208 for (int i = 0; i < userIdsToWrite.length; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002209 UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002210 userIdsToWrite[i] = user.id;
2211 }
2212 }
2213 for (int id : userIdsToWrite) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002214 serializer.startTag(null, TAG_USER);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002215 serializer.attribute(null, ATTR_ID, Integer.toString(id));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002216 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002217 }
2218
2219 serializer.endTag(null, TAG_USERS);
2220
2221 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07002222 userListFile.finishWrite(fos);
2223 } catch (Exception e) {
2224 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -07002225 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002226 }
2227 }
2228
Amith Yamasani12747872015-12-07 14:19:49 -08002229 private UserData readUserLP(int id) {
Kenny Guy02c89902016-11-15 19:36:38 +00002230 FileInputStream fis = null;
2231 try {
2232 AtomicFile userFile =
2233 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
2234 fis = userFile.openRead();
2235 return readUserLP(id, fis);
2236 } catch (IOException ioe) {
2237 Slog.e(LOG_TAG, "Error reading user list");
2238 } catch (XmlPullParserException pe) {
2239 Slog.e(LOG_TAG, "Error reading user list");
2240 } finally {
2241 IoUtils.closeQuietly(fis);
2242 }
2243 return null;
2244 }
2245
2246 @VisibleForTesting
2247 UserData readUserLP(int id, InputStream is) throws IOException,
2248 XmlPullParserException {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002249 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -07002250 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002251 String name = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -08002252 String account = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002253 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -07002254 long creationTime = 0L;
2255 long lastLoggedInTime = 0L;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002256 String lastLoggedInFingerprint = null;
Kenny Guy2a764942014-04-02 13:29:20 +01002257 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Kenny Guy02c89902016-11-15 19:36:38 +00002258 int profileBadge = 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002259 int restrictedProfileParentId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002260 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -07002261 boolean guestToRemove = false;
Amith Yamasani12747872015-12-07 14:19:49 -08002262 boolean persistSeedData = false;
2263 String seedAccountName = null;
2264 String seedAccountType = null;
2265 PersistableBundle seedAccountOptions = null;
Pavel Grafov6a40f092016-10-25 15:46:51 +01002266 Bundle baseRestrictions = null;
2267 Bundle localRestrictions = null;
2268 Bundle globalRestrictions = null;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002269
Kenny Guy02c89902016-11-15 19:36:38 +00002270 XmlPullParser parser = Xml.newPullParser();
2271 parser.setInput(is, StandardCharsets.UTF_8.name());
2272 int type;
2273 while ((type = parser.next()) != XmlPullParser.START_TAG
2274 && type != XmlPullParser.END_DOCUMENT) {
2275 // Skip
2276 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002277
Kenny Guy02c89902016-11-15 19:36:38 +00002278 if (type != XmlPullParser.START_TAG) {
2279 Slog.e(LOG_TAG, "Unable to read user " + id);
2280 return null;
2281 }
2282
2283 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
2284 int storedId = readIntAttribute(parser, ATTR_ID, -1);
2285 if (storedId != id) {
2286 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002287 return null;
2288 }
Kenny Guy02c89902016-11-15 19:36:38 +00002289 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
2290 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
2291 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
2292 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
2293 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
2294 lastLoggedInFingerprint = parser.getAttributeValue(null,
2295 ATTR_LAST_LOGGED_IN_FINGERPRINT);
2296 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
2297 UserInfo.NO_PROFILE_GROUP_ID);
2298 profileBadge = readIntAttribute(parser, ATTR_PROFILE_BADGE, 0);
2299 restrictedProfileParentId = readIntAttribute(parser,
2300 ATTR_RESTRICTED_PROFILE_PARENT_ID, UserInfo.NO_PROFILE_GROUP_ID);
2301 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
2302 if ("true".equals(valueString)) {
2303 partial = true;
2304 }
2305 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
2306 if ("true".equals(valueString)) {
2307 guestToRemove = true;
2308 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002309
Kenny Guy02c89902016-11-15 19:36:38 +00002310 seedAccountName = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_NAME);
2311 seedAccountType = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_TYPE);
2312 if (seedAccountName != null || seedAccountType != null) {
2313 persistSeedData = true;
2314 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002315
Kenny Guy02c89902016-11-15 19:36:38 +00002316 int outerDepth = parser.getDepth();
2317 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2318 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2319 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2320 continue;
2321 }
2322 String tag = parser.getName();
2323 if (TAG_NAME.equals(tag)) {
2324 type = parser.next();
2325 if (type == XmlPullParser.TEXT) {
2326 name = parser.getText();
2327 }
2328 } else if (TAG_RESTRICTIONS.equals(tag)) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01002329 baseRestrictions = UserRestrictionsUtils.readRestrictions(parser);
Kenny Guy02c89902016-11-15 19:36:38 +00002330 } else if (TAG_DEVICE_POLICY_RESTRICTIONS.equals(tag)) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01002331 localRestrictions = UserRestrictionsUtils.readRestrictions(parser);
2332 } else if (TAG_DEVICE_POLICY_GLOBAL_RESTRICTIONS.equals(tag)) {
2333 globalRestrictions = UserRestrictionsUtils.readRestrictions(parser);
Kenny Guy02c89902016-11-15 19:36:38 +00002334 } else if (TAG_ACCOUNT.equals(tag)) {
2335 type = parser.next();
2336 if (type == XmlPullParser.TEXT) {
2337 account = parser.getText();
2338 }
2339 } else if (TAG_SEED_ACCOUNT_OPTIONS.equals(tag)) {
2340 seedAccountOptions = PersistableBundle.restoreFromXml(parser);
Amith Yamasani12747872015-12-07 14:19:49 -08002341 persistSeedData = true;
2342 }
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08002343 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002344 }
Kenny Guy02c89902016-11-15 19:36:38 +00002345
2346 // Create the UserInfo object that gets passed around
2347 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
2348 userInfo.serialNumber = serialNumber;
2349 userInfo.creationTime = creationTime;
2350 userInfo.lastLoggedInTime = lastLoggedInTime;
2351 userInfo.lastLoggedInFingerprint = lastLoggedInFingerprint;
2352 userInfo.partial = partial;
2353 userInfo.guestToRemove = guestToRemove;
2354 userInfo.profileGroupId = profileGroupId;
2355 userInfo.profileBadge = profileBadge;
2356 userInfo.restrictedProfileParentId = restrictedProfileParentId;
2357
2358 // Create the UserData object that's internal to this class
2359 UserData userData = new UserData();
2360 userData.info = userInfo;
2361 userData.account = account;
2362 userData.seedAccountName = seedAccountName;
2363 userData.seedAccountType = seedAccountType;
2364 userData.persistSeedData = persistSeedData;
2365 userData.seedAccountOptions = seedAccountOptions;
2366
2367 synchronized (mRestrictionsLock) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01002368 if (baseRestrictions != null) {
2369 mBaseUserRestrictions.put(id, baseRestrictions);
2370 }
2371 if (localRestrictions != null) {
2372 mDevicePolicyLocalUserRestrictions.put(id, localRestrictions);
2373 }
2374 if (globalRestrictions != null) {
2375 mDevicePolicyGlobalUserRestrictions.put(id, globalRestrictions);
2376 }
Kenny Guy02c89902016-11-15 19:36:38 +00002377 }
2378 return userData;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002379 }
2380
Amith Yamasani920ace02012-09-20 22:15:37 -07002381 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
2382 String valueString = parser.getAttributeValue(null, attr);
2383 if (valueString == null) return defaultValue;
2384 try {
2385 return Integer.parseInt(valueString);
2386 } catch (NumberFormatException nfe) {
2387 return defaultValue;
2388 }
2389 }
2390
2391 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
2392 String valueString = parser.getAttributeValue(null, attr);
2393 if (valueString == null) return defaultValue;
2394 try {
2395 return Long.parseLong(valueString);
2396 } catch (NumberFormatException nfe) {
2397 return defaultValue;
2398 }
2399 }
2400
Amith Yamasanib82add22013-07-09 11:24:44 -07002401 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002402 * Removes the app restrictions file for a specific package and user id, if it exists.
2403 */
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07002404 private static void cleanAppRestrictionsForPackageLAr(String pkg, int userId) {
2405 File dir = Environment.getUserSystemDirectory(userId);
2406 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
2407 if (resFile.exists()) {
2408 resFile.delete();
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002409 }
2410 }
2411
Kenny Guya52dc3e2014-02-11 15:33:14 +00002412 @Override
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002413 public UserInfo createProfileForUser(String name, int flags, int userId,
2414 String[] disallowedPackages) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002415 checkManageOrCreateUsersPermission(flags);
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002416 return createUserInternal(name, flags, userId, disallowedPackages);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002417 }
2418
Amith Yamasani258848d2012-08-10 17:06:33 -07002419 @Override
Tony Mak6dc428f2016-10-10 15:48:27 +01002420 public UserInfo createProfileForUserEvenWhenDisallowed(String name, int flags, int userId,
2421 String[] disallowedPackages) {
2422 checkManageOrCreateUsersPermission(flags);
2423 return createUserInternalUnchecked(name, flags, userId, disallowedPackages);
2424 }
2425
2426 @Override
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00002427 public boolean removeUserEvenWhenDisallowed(@UserIdInt int userHandle) {
2428 checkManageOrCreateUsersPermission("Only the system can remove users");
2429 return removeUserUnchecked(userHandle);
2430 }
2431
2432 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07002433 public UserInfo createUser(String name, int flags) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002434 checkManageOrCreateUsersPermission(flags);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00002435 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002436 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07002437
Jessica Hummelbe81c802014-04-22 15:49:22 +01002438 private UserInfo createUserInternal(String name, int flags, int parentId) {
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002439 return createUserInternal(name, flags, parentId, null);
2440 }
2441
2442 private UserInfo createUserInternal(String name, int flags, int parentId,
2443 String[] disallowedPackages) {
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002444 String restriction = ((flags & UserInfo.FLAG_MANAGED_PROFILE) != 0)
2445 ? UserManager.DISALLOW_ADD_MANAGED_PROFILE
2446 : UserManager.DISALLOW_ADD_USER;
2447 if (hasUserRestriction(restriction, UserHandle.getCallingUserId())) {
2448 Log.w(LOG_TAG, "Cannot add user. " + restriction + " is enabled.");
Julia Reynolds75175022014-06-26 16:35:00 -04002449 return null;
2450 }
Tony Mak6dc428f2016-10-10 15:48:27 +01002451 return createUserInternalUnchecked(name, flags, parentId, disallowedPackages);
2452 }
2453
2454 private UserInfo createUserInternalUnchecked(String name, int flags, int parentId,
2455 String[] disallowedPackages) {
Suprabh Shuklac5e057c2016-08-08 16:22:44 -07002456 DeviceStorageMonitorInternal dsm = LocalServices
2457 .getService(DeviceStorageMonitorInternal.class);
2458 if (dsm.isMemoryLow()) {
2459 Log.w(LOG_TAG, "Cannot add user. Not enough space on disk.");
2460 return null;
2461 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07002462 if (ActivityManager.isLowRamDeviceStatic()) {
2463 return null;
2464 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07002465 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Nicolas Prevot12678a92015-05-13 12:15:03 -07002466 final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002467 final boolean isRestricted = (flags & UserInfo.FLAG_RESTRICTED) != 0;
Amith Yamasani52c21e32016-05-31 09:12:20 -07002468 final boolean isDemo = (flags & UserInfo.FLAG_DEMO) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002469 final long ident = Binder.clearCallingIdentity();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002470 UserInfo userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08002471 UserData userData;
Amith Yamasanibb054c92015-07-09 14:16:27 -07002472 final int userId;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002473 try {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002474 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002475 UserData parent = null;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002476 if (parentId != UserHandle.USER_NULL) {
2477 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002478 parent = getUserDataLU(parentId);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00002479 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002480 if (parent == null) return null;
2481 }
2482 if (isManagedProfile && !canAddMoreManagedProfiles(parentId, false)) {
2483 Log.e(LOG_TAG, "Cannot add more managed profiles for user " + parentId);
2484 return null;
2485 }
Amith Yamasani52c21e32016-05-31 09:12:20 -07002486 if (!isGuest && !isManagedProfile && !isDemo && isUserLimitReached()) {
2487 // If we're not adding a guest/demo user or a managed profile and the limit has
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002488 // been reached, cannot add a user.
2489 return null;
2490 }
2491 // If we're adding a guest and there already exists one, bail.
2492 if (isGuest && findCurrentGuestUser() != null) {
2493 return null;
2494 }
2495 // In legacy mode, restricted profile's parent can only be the owner user
2496 if (isRestricted && !UserManager.isSplitSystemUser()
2497 && (parentId != UserHandle.USER_SYSTEM)) {
2498 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
2499 return null;
2500 }
2501 if (isRestricted && UserManager.isSplitSystemUser()) {
2502 if (parent == null) {
2503 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be "
2504 + "specified");
Nicolas Prevot12678a92015-05-13 12:15:03 -07002505 return null;
2506 }
Amith Yamasani12747872015-12-07 14:19:49 -08002507 if (!parent.info.canHaveProfile()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002508 Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be "
2509 + "created for the specified parent user id " + parentId);
Amith Yamasani95ab7842014-08-11 17:09:26 -07002510 return null;
2511 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002512 }
2513 // In split system user mode, we assign the first human user the primary flag.
2514 // And if there is no device owner, we also assign the admin flag to primary user.
2515 if (UserManager.isSplitSystemUser()
2516 && !isGuest && !isManagedProfile && getPrimaryUser() == null) {
2517 flags |= UserInfo.FLAG_PRIMARY;
Makoto Onukie7927da2015-11-25 10:05:17 -08002518 synchronized (mUsersLock) {
2519 if (!mIsDeviceManaged) {
2520 flags |= UserInfo.FLAG_ADMIN;
2521 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07002522 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002523 }
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002524
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002525 userId = getNextAvailableId();
2526 Environment.getUserSystemDirectory(userId).mkdirs();
Lenka Trochtova02fee152015-12-22 14:26:18 +01002527 boolean ephemeralGuests = Resources.getSystem()
2528 .getBoolean(com.android.internal.R.bool.config_guestUserEphemeral);
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002529
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002530 synchronized (mUsersLock) {
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002531 // Add ephemeral flag to guests/users if required. Also inherit it from parent.
2532 if ((isGuest && ephemeralGuests) || mForceEphemeralUsers
2533 || (parent != null && parent.info.isEphemeral())) {
2534 flags |= UserInfo.FLAG_EPHEMERAL;
2535 }
2536
2537 userInfo = new UserInfo(userId, name, null, flags);
2538 userInfo.serialNumber = mNextSerialNumber++;
2539 long now = System.currentTimeMillis();
2540 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
2541 userInfo.partial = true;
Fyodor Kupolov83c24242016-03-31 13:30:42 -07002542 userInfo.lastLoggedInFingerprint = Build.FINGERPRINT;
Kenny Guy02c89902016-11-15 19:36:38 +00002543 if (isManagedProfile && parentId != UserHandle.USER_NULL) {
2544 userInfo.profileBadge = getFreeProfileBadgeLU(parentId);
2545 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002546 userData = new UserData();
2547 userData.info = userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08002548 mUsers.put(userId, userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002549 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06002550 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002551 writeUserListLP();
2552 if (parent != null) {
2553 if (isManagedProfile) {
Amith Yamasani12747872015-12-07 14:19:49 -08002554 if (parent.info.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
2555 parent.info.profileGroupId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002556 writeUserLP(parent);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002557 }
Amith Yamasani12747872015-12-07 14:19:49 -08002558 userInfo.profileGroupId = parent.info.profileGroupId;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002559 } else if (isRestricted) {
Amith Yamasani12747872015-12-07 14:19:49 -08002560 if (parent.info.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) {
2561 parent.info.restrictedProfileParentId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002562 writeUserLP(parent);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002563 }
Amith Yamasani12747872015-12-07 14:19:49 -08002564 userInfo.restrictedProfileParentId = parent.info.restrictedProfileParentId;
Makoto Onuki068c54a2015-10-13 14:34:03 -07002565 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002566 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07002567 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002568 final StorageManager storage = mContext.getSystemService(StorageManager.class);
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002569 storage.createUserKey(userId, userInfo.serialNumber, userInfo.isEphemeral());
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -08002570 mUserDataPreparer.prepareUserData(userId, userInfo.serialNumber,
Jeff Sharkey47f71082016-02-01 17:03:54 -07002571 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002572 mPm.createNewUser(userId, disallowedPackages);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002573 userInfo.partial = false;
2574 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002575 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002576 }
2577 updateUserIds();
2578 Bundle restrictions = new Bundle();
Fyodor Kupolove04462c2015-11-30 15:02:53 -08002579 if (isGuest) {
2580 synchronized (mGuestRestrictions) {
2581 restrictions.putAll(mGuestRestrictions);
2582 }
2583 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002584 synchronized (mRestrictionsLock) {
2585 mBaseUserRestrictions.append(userId, restrictions);
2586 }
Fyodor Kupolov5fd967d2016-07-12 14:46:19 -07002587 mPm.onNewUserCreated(userId);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002588 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
2589 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
2590 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
2591 android.Manifest.permission.MANAGE_USERS);
Christine Franks88220562017-05-24 11:11:21 -07002592 MetricsLogger.count(mContext, isGuest ? TRON_GUEST_CREATED
2593 : (isDemo ? TRON_DEMO_CREATED : TRON_USER_CREATED), 1);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002594 } finally {
2595 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07002596 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002597 return userInfo;
2598 }
2599
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002600 @VisibleForTesting
2601 UserData putUserInfo(UserInfo userInfo) {
2602 final UserData userData = new UserData();
2603 userData.info = userInfo;
2604 synchronized (mUsers) {
2605 mUsers.put(userInfo.id, userData);
2606 }
2607 return userData;
2608 }
2609
2610 @VisibleForTesting
2611 void removeUserInfo(int userId) {
2612 synchronized (mUsers) {
2613 mUsers.remove(userId);
2614 }
2615 }
2616
Amith Yamasani0b285492011-04-14 17:35:23 -07002617 /**
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002618 * @hide
2619 */
Amith Yamasani12747872015-12-07 14:19:49 -08002620 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002621 public UserInfo createRestrictedProfile(String name, int parentUserId) {
Sudheer Shanka53d41472016-06-16 09:11:08 -07002622 checkManageOrCreateUsersPermission("setupRestrictedProfile");
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002623 final UserInfo user = createProfileForUser(
2624 name, UserInfo.FLAG_RESTRICTED, parentUserId, null);
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002625 if (user == null) {
2626 return null;
2627 }
Fyodor Kupolov9e912ba2016-02-09 18:29:43 -08002628 long identity = Binder.clearCallingIdentity();
2629 try {
2630 setUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, true, user.id);
2631 // Change the setting before applying the DISALLOW_SHARE_LOCATION restriction, otherwise
2632 // the putIntForUser() will fail.
2633 android.provider.Settings.Secure.putIntForUser(mContext.getContentResolver(),
2634 android.provider.Settings.Secure.LOCATION_MODE,
2635 android.provider.Settings.Secure.LOCATION_MODE_OFF, user.id);
2636 setUserRestriction(UserManager.DISALLOW_SHARE_LOCATION, true, user.id);
2637 } finally {
2638 Binder.restoreCallingIdentity(identity);
2639 }
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002640 return user;
2641 }
2642
2643 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07002644 * Find the current guest user. If the Guest user is partial,
2645 * then do not include it in the results as it is about to die.
Adam Lesinskieddeb492014-09-08 17:50:03 -07002646 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002647 private UserInfo findCurrentGuestUser() {
2648 synchronized (mUsersLock) {
2649 final int size = mUsers.size();
2650 for (int i = 0; i < size; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002651 final UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002652 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
2653 return user;
2654 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002655 }
2656 }
2657 return null;
2658 }
2659
2660 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07002661 * Mark this guest user for deletion to allow us to create another guest
2662 * and switch to that user before actually removing this guest.
2663 * @param userHandle the userid of the current guest
2664 * @return whether the user could be marked for deletion
2665 */
Amith Yamasani12747872015-12-07 14:19:49 -08002666 @Override
Amith Yamasani1df14732014-08-29 21:37:27 -07002667 public boolean markGuestForDeletion(int userHandle) {
2668 checkManageUsersPermission("Only the system can remove users");
2669 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
2670 UserManager.DISALLOW_REMOVE_USER, false)) {
2671 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
2672 return false;
2673 }
2674
2675 long ident = Binder.clearCallingIdentity();
2676 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002677 final UserData userData;
Amith Yamasani1df14732014-08-29 21:37:27 -07002678 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002679 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002680 userData = mUsers.get(userHandle);
2681 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002682 return false;
2683 }
Amith Yamasani1df14732014-08-29 21:37:27 -07002684 }
Amith Yamasani12747872015-12-07 14:19:49 -08002685 if (!userData.info.isGuest()) {
Amith Yamasani1df14732014-08-29 21:37:27 -07002686 return false;
2687 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002688 // We set this to a guest user that is to be removed. This is a temporary state
2689 // where we are allowed to add new Guest users, even if this one is still not
2690 // removed. This user will still show up in getUserInfo() calls.
2691 // If we don't get around to removing this Guest user, it will be purged on next
2692 // startup.
Amith Yamasani12747872015-12-07 14:19:49 -08002693 userData.info.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07002694 // Mark it as disabled, so that it isn't returned any more when
2695 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002696 userData.info.flags |= UserInfo.FLAG_DISABLED;
2697 writeUserLP(userData);
Amith Yamasani1df14732014-08-29 21:37:27 -07002698 }
2699 } finally {
2700 Binder.restoreCallingIdentity(ident);
2701 }
2702 return true;
2703 }
2704
2705 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002706 * Removes a user and all data directories created for that user. This method should be called
2707 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07002708 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07002709 */
Amith Yamasani12747872015-12-07 14:19:49 -08002710 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -07002711 public boolean removeUser(int userHandle) {
Fyodor Kupolov4593e422016-10-27 11:00:29 -07002712 Slog.i(LOG_TAG, "removeUser u" + userHandle);
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002713 checkManageOrCreateUsersPermission("Only the system can remove users");
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002714
2715 final boolean isManagedProfile;
2716 synchronized (mUsersLock) {
2717 UserInfo userInfo = getUserInfoLU(userHandle);
2718 isManagedProfile = userInfo != null && userInfo.isManagedProfile();
2719 }
2720 String restriction = isManagedProfile
2721 ? UserManager.DISALLOW_REMOVE_MANAGED_PROFILE : UserManager.DISALLOW_REMOVE_USER;
2722 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(restriction, false)) {
2723 Log.w(LOG_TAG, "Cannot remove user. " + restriction + " is enabled.");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04002724 return false;
2725 }
Nicolas Prevotdf1b87d2016-10-25 13:57:08 +01002726 return removeUserUnchecked(userHandle);
2727 }
Julia Reynolds4ac5f852014-06-23 17:38:51 -04002728
Nicolas Prevotdf1b87d2016-10-25 13:57:08 +01002729 private boolean removeUserUnchecked(int userHandle) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002730 long ident = Binder.clearCallingIdentity();
2731 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002732 final UserData userData;
Fyodor Kupolov0df68cd2015-10-01 13:54:22 -07002733 int currentUser = ActivityManager.getCurrentUser();
2734 if (currentUser == userHandle) {
2735 Log.w(LOG_TAG, "Current user cannot be removed");
2736 return false;
2737 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002738 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002739 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002740 userData = mUsers.get(userHandle);
2741 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002742 return false;
2743 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002744
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002745 addRemovingUserIdLocked(userHandle);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002746 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002747
Kenny Guyee58b4f2014-05-23 15:19:53 +01002748 // Set this to a partially created user, so that the user will be purged
2749 // on next startup, in case the runtime stops now before stopping and
2750 // removing the user completely.
Amith Yamasani12747872015-12-07 14:19:49 -08002751 userData.info.partial = true;
Kenny Guyee58b4f2014-05-23 15:19:53 +01002752 // Mark it as disabled, so that it isn't returned any more when
2753 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002754 userData.info.flags |= UserInfo.FLAG_DISABLED;
2755 writeUserLP(userData);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002756 }
Fyodor Kupolov6c96f7f2017-06-28 18:22:59 -07002757 try {
2758 mAppOpsService.removeUser(userHandle);
2759 } catch (RemoteException e) {
2760 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
2761 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002762
Amith Yamasani12747872015-12-07 14:19:49 -08002763 if (userData.info.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
2764 && userData.info.isManagedProfile()) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002765 // Send broadcast to notify system that the user removed was a
2766 // managed user.
Amith Yamasani12747872015-12-07 14:19:49 -08002767 sendProfileRemovedBroadcast(userData.info.profileGroupId, userData.info.id);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002768 }
2769
2770 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
2771 int res;
2772 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08002773 res = ActivityManager.getService().stopUser(userHandle, /* force= */ true,
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07002774 new IStopUserCallback.Stub() {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002775 @Override
2776 public void userStopped(int userId) {
2777 finishRemoveUser(userId);
2778 }
2779 @Override
2780 public void userStopAborted(int userId) {
2781 }
2782 });
2783 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002784 return false;
2785 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002786 return res == ActivityManager.USER_OP_SUCCESS;
2787 } finally {
2788 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002789 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002790 }
2791
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002792 @VisibleForTesting
2793 void addRemovingUserIdLocked(int userId) {
2794 // We remember deleted user IDs to prevent them from being
2795 // reused during the current boot; they can still be reused
2796 // after a reboot or recycling of userIds.
2797 mRemovingUserIds.put(userId, true);
2798 mRecentlyRemovedIds.add(userId);
2799 // Keep LRU queue of recently removed IDs for recycling
2800 if (mRecentlyRemovedIds.size() > MAX_RECENTLY_REMOVED_IDS_SIZE) {
2801 mRecentlyRemovedIds.removeFirst();
2802 }
2803 }
2804
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002805 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07002806 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002807 // Let other services shutdown any activity and clean up their state before completely
2808 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002809 long ident = Binder.clearCallingIdentity();
2810 try {
2811 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
2812 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002813 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
2814 android.Manifest.permission.MANAGE_USERS,
2815
2816 new BroadcastReceiver() {
2817 @Override
2818 public void onReceive(Context context, Intent intent) {
2819 if (DBG) {
2820 Slog.i(LOG_TAG,
2821 "USER_REMOVED broadcast sent, cleaning up user data "
2822 + userHandle);
2823 }
2824 new Thread() {
Amith Yamasani12747872015-12-07 14:19:49 -08002825 @Override
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002826 public void run() {
Amith Yamasani515d4062015-09-28 11:30:06 -07002827 // Clean up any ActivityManager state
2828 LocalServices.getService(ActivityManagerInternal.class)
2829 .onUserRemoved(userHandle);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002830 removeUserState(userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002831 }
2832 }.start();
2833 }
2834 },
2835
2836 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002837 } finally {
2838 Binder.restoreCallingIdentity(ident);
2839 }
Amith Yamasani2a003292012-08-14 18:25:45 -07002840 }
2841
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002842 private void removeUserState(final int userHandle) {
Paul Crowley91293792016-03-25 15:23:07 -07002843 try {
2844 mContext.getSystemService(StorageManager.class).destroyUserKey(userHandle);
2845 } catch (IllegalStateException e) {
2846 // This may be simply because the user was partially created.
2847 Slog.i(LOG_TAG,
2848 "Destroying key for user " + userHandle + " failed, continuing anyway", e);
2849 }
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002850
Amith Yamasanid04aaa32016-06-13 12:09:36 -07002851 // Cleanup gatekeeper secure user id
2852 try {
2853 final IGateKeeperService gk = GateKeeper.getService();
2854 if (gk != null) {
2855 gk.clearSecureUserId(userHandle);
2856 }
2857 } catch (Exception ex) {
2858 Slog.w(LOG_TAG, "unable to clear GK secure user id");
2859 }
2860
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002861 // Cleanup package manager settings
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002862 mPm.cleanUpUser(this, userHandle);
Amith Yamasanid04aaa32016-06-13 12:09:36 -07002863
2864 // Clean up all data before removing metadata
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -08002865 mUserDataPreparer.destroyUserData(userHandle,
Amith Yamasanid04aaa32016-06-13 12:09:36 -07002866 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2867
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002868 // Remove this user from the list
Fyodor Kupolov82402752015-10-28 14:54:51 -07002869 synchronized (mUsersLock) {
2870 mUsers.remove(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08002871 mIsUserManaged.delete(userHandle);
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00002872 }
2873 synchronized (mUserStates) {
2874 mUserStates.delete(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08002875 }
2876 synchronized (mRestrictionsLock) {
2877 mBaseUserRestrictions.remove(userHandle);
2878 mAppliedUserRestrictions.remove(userHandle);
2879 mCachedEffectiveUserRestrictions.remove(userHandle);
2880 mDevicePolicyLocalUserRestrictions.remove(userHandle);
Pavel Grafov6a40f092016-10-25 15:46:51 +01002881 if (mDevicePolicyGlobalUserRestrictions.get(userHandle) != null) {
2882 mDevicePolicyGlobalUserRestrictions.remove(userHandle);
2883 applyUserRestrictionsForAllUsersLR();
2884 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002885 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002886 // Update the user list
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002887 synchronized (mPackagesLock) {
2888 writeUserListLP();
2889 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06002890 // Remove user file
2891 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
2892 userFile.delete();
Fyodor Kupolov82402752015-10-28 14:54:51 -07002893 updateUserIds();
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002894 if (RELEASE_DELETED_USER_ID) {
2895 synchronized (mUsers) {
2896 mRemovingUserIds.delete(userHandle);
2897 }
2898 }
Amith Yamasani61f57372012-08-31 12:12:28 -07002899 }
2900
Kenny Guyf8d3a232014-05-15 16:09:52 +01002901 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01002902 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01002903 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
2904 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002905 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
Jeff Sharkeyaf6ec292015-12-17 11:19:00 -07002906 managedProfileIntent.putExtra(Intent.EXTRA_USER_HANDLE, removedUserId);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002907 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01002908 }
2909
Amith Yamasani2a003292012-08-14 18:25:45 -07002910 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002911 public Bundle getApplicationRestrictions(String packageName) {
2912 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
2913 }
2914
2915 @Override
2916 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002917 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07002918 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07002919 checkSystemOrRoot("get application restrictions for other user/app " + packageName);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002920 }
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07002921 synchronized (mAppRestrictionsLock) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002922 // Read the restrictions from XML
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07002923 return readApplicationRestrictionsLAr(packageName, userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002924 }
2925 }
2926
2927 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002928 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002929 int userId) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00002930 checkSystemOrRoot("set application restrictions");
Fyodor Kupolov0d88d542016-04-19 11:37:22 -07002931 if (restrictions != null) {
2932 restrictions.setDefusable(true);
2933 }
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07002934 synchronized (mAppRestrictionsLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01002935 if (restrictions == null || restrictions.isEmpty()) {
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07002936 cleanAppRestrictionsForPackageLAr(packageName, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01002937 } else {
2938 // Write the restrictions to XML
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07002939 writeApplicationRestrictionsLAr(packageName, restrictions, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01002940 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002941 }
Robin Lee66e5d962014-04-09 16:44:21 +01002942
Fyodor Kupolovd2846122016-02-11 18:06:34 -08002943 // Notify package of changes via an intent - only sent to explicitly registered receivers.
2944 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
2945 changeIntent.setPackage(packageName);
2946 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
2947 mContext.sendBroadcastAsUser(changeIntent, UserHandle.of(userId));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002948 }
2949
2950 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07002951 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002952 try {
2953 return mContext.getPackageManager().getApplicationInfo(packageName,
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07002954 PackageManager.MATCH_ANY_USER).uid;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002955 } catch (NameNotFoundException nnfe) {
2956 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07002957 } finally {
2958 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002959 }
2960 }
2961
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07002962 @GuardedBy("mAppRestrictionsLock")
2963 private static Bundle readApplicationRestrictionsLAr(String packageName, int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002964 AtomicFile restrictionsFile =
2965 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
2966 packageToRestrictionsFileName(packageName)));
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07002967 return readApplicationRestrictionsLAr(restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002968 }
2969
2970 @VisibleForTesting
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07002971 @GuardedBy("mAppRestrictionsLock")
2972 static Bundle readApplicationRestrictionsLAr(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002973 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002974 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002975 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07002976 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002977 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002978
2979 FileInputStream fis = null;
2980 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002981 fis = restrictionsFile.openRead();
2982 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002983 parser.setInput(fis, StandardCharsets.UTF_8.name());
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002984 XmlUtils.nextElement(parser);
2985 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002986 Slog.e(LOG_TAG, "Unable to read restrictions file "
2987 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002988 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002989 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002990 while (parser.next() != XmlPullParser.END_DOCUMENT) {
2991 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002992 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002993 } catch (IOException|XmlPullParserException e) {
2994 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002995 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002996 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002997 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002998 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002999 }
3000
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003001 private static void readEntry(Bundle restrictions, ArrayList<String> values,
3002 XmlPullParser parser) throws XmlPullParserException, IOException {
3003 int type = parser.getEventType();
3004 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
3005 String key = parser.getAttributeValue(null, ATTR_KEY);
3006 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
3007 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
3008 if (multiple != null) {
3009 values.clear();
3010 int count = Integer.parseInt(multiple);
3011 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
3012 if (type == XmlPullParser.START_TAG
3013 && parser.getName().equals(TAG_VALUE)) {
3014 values.add(parser.nextText().trim());
3015 count--;
3016 }
3017 }
3018 String [] valueStrings = new String[values.size()];
3019 values.toArray(valueStrings);
3020 restrictions.putStringArray(key, valueStrings);
3021 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
3022 restrictions.putBundle(key, readBundleEntry(parser, values));
3023 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
3024 final int outerDepth = parser.getDepth();
3025 ArrayList<Bundle> bundleList = new ArrayList<>();
3026 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
3027 Bundle childBundle = readBundleEntry(parser, values);
3028 bundleList.add(childBundle);
3029 }
3030 restrictions.putParcelableArray(key,
3031 bundleList.toArray(new Bundle[bundleList.size()]));
3032 } else {
3033 String value = parser.nextText().trim();
3034 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
3035 restrictions.putBoolean(key, Boolean.parseBoolean(value));
3036 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
3037 restrictions.putInt(key, Integer.parseInt(value));
3038 } else {
3039 restrictions.putString(key, value);
3040 }
3041 }
3042 }
3043 }
3044
3045 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
3046 throws IOException, XmlPullParserException {
3047 Bundle childBundle = new Bundle();
3048 final int outerDepth = parser.getDepth();
3049 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
3050 readEntry(childBundle, values, parser);
3051 }
3052 return childBundle;
3053 }
3054
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003055 @GuardedBy("mAppRestrictionsLock")
3056 private static void writeApplicationRestrictionsLAr(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07003057 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003058 AtomicFile restrictionsFile = new AtomicFile(
3059 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07003060 packageToRestrictionsFileName(packageName)));
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003061 writeApplicationRestrictionsLAr(restrictions, restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003062 }
3063
3064 @VisibleForTesting
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003065 @GuardedBy("mAppRestrictionsLock")
3066 static void writeApplicationRestrictionsLAr(Bundle restrictions, AtomicFile restrictionsFile) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003067 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003068 try {
3069 fos = restrictionsFile.startWrite();
3070 final BufferedOutputStream bos = new BufferedOutputStream(fos);
3071
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003072 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01003073 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003074 serializer.startDocument(null, true);
3075 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
3076
3077 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003078 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003079 serializer.endTag(null, TAG_RESTRICTIONS);
3080
3081 serializer.endDocument();
3082 restrictionsFile.finishWrite(fos);
3083 } catch (Exception e) {
3084 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003085 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
3086 }
3087 }
3088
3089 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
3090 throws IOException {
3091 for (String key : restrictions.keySet()) {
3092 Object value = restrictions.get(key);
3093 serializer.startTag(null, TAG_ENTRY);
3094 serializer.attribute(null, ATTR_KEY, key);
3095
3096 if (value instanceof Boolean) {
3097 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
3098 serializer.text(value.toString());
3099 } else if (value instanceof Integer) {
3100 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
3101 serializer.text(value.toString());
3102 } else if (value == null || value instanceof String) {
3103 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
3104 serializer.text(value != null ? (String) value : "");
3105 } else if (value instanceof Bundle) {
3106 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
3107 writeBundle((Bundle) value, serializer);
3108 } else if (value instanceof Parcelable[]) {
3109 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
3110 Parcelable[] array = (Parcelable[]) value;
3111 for (Parcelable parcelable : array) {
3112 if (!(parcelable instanceof Bundle)) {
3113 throw new IllegalArgumentException("bundle-array can only hold Bundles");
3114 }
3115 serializer.startTag(null, TAG_ENTRY);
3116 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
3117 writeBundle((Bundle) parcelable, serializer);
3118 serializer.endTag(null, TAG_ENTRY);
3119 }
3120 } else {
3121 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
3122 String[] values = (String[]) value;
3123 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
3124 for (String choice : values) {
3125 serializer.startTag(null, TAG_VALUE);
3126 serializer.text(choice != null ? choice : "");
3127 serializer.endTag(null, TAG_VALUE);
3128 }
3129 }
3130 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003131 }
3132 }
3133
3134 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07003135 public int getUserSerialNumber(int userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003136 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07003137 if (!exists(userHandle)) return -1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003138 return getUserInfoLU(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07003139 }
3140 }
3141
3142 @Override
Fyodor Kupolov605b12a2017-05-10 15:58:09 -07003143 public boolean isUserNameSet(int userHandle) {
3144 synchronized (mUsersLock) {
3145 UserInfo userInfo = getUserInfoLU(userHandle);
3146 return userInfo != null && userInfo.name != null;
3147 }
3148 }
3149
3150 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07003151 public int getUserHandle(int userSerialNumber) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003152 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07003153 for (int userId : mUserIds) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003154 UserInfo info = getUserInfoLU(userId);
Kenny Guy945f8832015-02-10 15:17:26 +00003155 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07003156 }
3157 // Not found
3158 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07003159 }
3160 }
3161
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003162 @Override
3163 public long getUserCreationTime(int userHandle) {
3164 int callingUserId = UserHandle.getCallingUserId();
3165 UserInfo userInfo = null;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003166 synchronized (mUsersLock) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003167 if (callingUserId == userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003168 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003169 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003170 UserInfo parent = getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003171 if (parent != null && parent.id == callingUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003172 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003173 }
3174 }
3175 }
3176 if (userInfo == null) {
3177 throw new SecurityException("userHandle can only be the calling user or a managed "
3178 + "profile associated with this user");
3179 }
3180 return userInfo.creationTime;
3181 }
3182
Amith Yamasani0b285492011-04-14 17:35:23 -07003183 /**
3184 * Caches the list of user ids in an array, adjusting the array size when necessary.
3185 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07003186 private void updateUserIds() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003187 int num = 0;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003188 synchronized (mUsersLock) {
3189 final int userSize = mUsers.size();
3190 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003191 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003192 num++;
3193 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003194 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07003195 final int[] newUsers = new int[num];
3196 int n = 0;
3197 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003198 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003199 newUsers[n++] = mUsers.keyAt(i);
3200 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003201 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07003202 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07003203 }
3204 }
3205
3206 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003207 * Called right before a user is started. This gives us a chance to prepare
3208 * app storage and apply any user restrictions.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003209 */
3210 public void onBeforeStartUser(int userId) {
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003211 UserInfo userInfo = getUserInfo(userId);
3212 if (userInfo == null) {
3213 return;
3214 }
3215 final int userSerial = userInfo.serialNumber;
3216 // Migrate only if build fingerprints mismatch
3217 boolean migrateAppsData = !Build.FINGERPRINT.equals(userInfo.lastLoggedInFingerprint);
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -08003218 mUserDataPreparer.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_DE);
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003219 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_DE, migrateAppsData);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003220
3221 if (userId != UserHandle.USER_SYSTEM) {
3222 synchronized (mRestrictionsLock) {
3223 applyUserRestrictionsLR(userId);
3224 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003225 }
3226 }
3227
3228 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003229 * Called right before a user is unlocked. This gives us a chance to prepare
3230 * app storage.
3231 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003232 public void onBeforeUnlockUser(@UserIdInt int userId) {
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003233 UserInfo userInfo = getUserInfo(userId);
3234 if (userInfo == null) {
3235 return;
3236 }
3237 final int userSerial = userInfo.serialNumber;
3238 // Migrate only if build fingerprints mismatch
3239 boolean migrateAppsData = !Build.FINGERPRINT.equals(userInfo.lastLoggedInFingerprint);
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -08003240 mUserDataPreparer.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_CE);
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003241 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_CE, migrateAppsData);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003242 }
3243
3244 /**
Fyodor Kupolov50979d12017-01-27 17:36:32 -08003245 * Examine all users present on given mounted volume, and destroy data
3246 * belonging to users that are no longer valid, or whose user ID has been
3247 * recycled.
3248 */
3249 void reconcileUsers(String volumeUuid) {
3250 mUserDataPreparer.reconcileUsers(volumeUuid, getUsers(true /* excludeDying */));
3251 }
3252
3253 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07003254 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasanieb437d42016-04-29 09:31:25 -07003255 * This is called with ActivityManagerService lock held.
Amith Yamasani920ace02012-09-20 22:15:37 -07003256 * @param userId the user that was just foregrounded
3257 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003258 public void onUserLoggedIn(@UserIdInt int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -08003259 UserData userData = getUserDataNoChecks(userId);
3260 if (userData == null || userData.info.partial) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003261 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
3262 return;
3263 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003264
3265 final long now = System.currentTimeMillis();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003266 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani12747872015-12-07 14:19:49 -08003267 userData.info.lastLoggedInTime = now;
Amith Yamasani920ace02012-09-20 22:15:37 -07003268 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003269 userData.info.lastLoggedInFingerprint = Build.FINGERPRINT;
3270 scheduleWriteUser(userData);
Amith Yamasani920ace02012-09-20 22:15:37 -07003271 }
3272
3273 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07003274 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani0b285492011-04-14 17:35:23 -07003275 */
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003276 @VisibleForTesting
3277 int getNextAvailableId() {
3278 int nextId;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003279 synchronized (mUsersLock) {
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003280 nextId = scanNextAvailableIdLocked();
3281 if (nextId >= 0) {
3282 return nextId;
3283 }
3284 // All ids up to MAX_USER_ID were used. Remove all mRemovingUserIds,
3285 // except most recently removed
3286 if (mRemovingUserIds.size() > 0) {
3287 Slog.i(LOG_TAG, "All available IDs are used. Recycling LRU ids.");
3288 mRemovingUserIds.clear();
3289 for (Integer recentlyRemovedId : mRecentlyRemovedIds) {
3290 mRemovingUserIds.put(recentlyRemovedId, true);
Amith Yamasani195263742012-08-21 15:40:12 -07003291 }
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003292 nextId = scanNextAvailableIdLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003293 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003294 }
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003295 if (nextId < 0) {
3296 throw new IllegalStateException("No user id available!");
3297 }
3298 return nextId;
3299 }
3300
3301 private int scanNextAvailableIdLocked() {
3302 for (int i = MIN_USER_ID; i < MAX_USER_ID; i++) {
3303 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
3304 return i;
3305 }
3306 }
3307 return -1;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003308 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003309
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003310 private static String packageToRestrictionsFileName(String packageName) {
Amith Yamasanifc95e702013-09-26 13:20:17 -07003311 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
3312 }
3313
Amith Yamasani920ace02012-09-20 22:15:37 -07003314 @Override
Amith Yamasani12747872015-12-07 14:19:49 -08003315 public void setSeedAccountData(int userId, String accountName, String accountType,
3316 PersistableBundle accountOptions, boolean persist) {
3317 checkManageUsersPermission("Require MANAGE_USERS permission to set user seed data");
3318 synchronized (mPackagesLock) {
3319 final UserData userData;
3320 synchronized (mUsersLock) {
3321 userData = getUserDataLU(userId);
3322 if (userData == null) {
3323 Slog.e(LOG_TAG, "No such user for settings seed data u=" + userId);
3324 return;
3325 }
3326 userData.seedAccountName = accountName;
3327 userData.seedAccountType = accountType;
3328 userData.seedAccountOptions = accountOptions;
3329 userData.persistSeedData = persist;
3330 }
3331 if (persist) {
3332 writeUserLP(userData);
3333 }
3334 }
3335 }
3336
3337 @Override
3338 public String getSeedAccountName() throws RemoteException {
3339 checkManageUsersPermission("Cannot get seed account information");
3340 synchronized (mUsersLock) {
3341 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3342 return userData.seedAccountName;
3343 }
3344 }
3345
3346 @Override
3347 public String getSeedAccountType() throws RemoteException {
3348 checkManageUsersPermission("Cannot get seed account information");
3349 synchronized (mUsersLock) {
3350 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3351 return userData.seedAccountType;
3352 }
3353 }
3354
3355 @Override
3356 public PersistableBundle getSeedAccountOptions() throws RemoteException {
3357 checkManageUsersPermission("Cannot get seed account information");
3358 synchronized (mUsersLock) {
3359 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3360 return userData.seedAccountOptions;
3361 }
3362 }
3363
3364 @Override
3365 public void clearSeedAccountData() throws RemoteException {
3366 checkManageUsersPermission("Cannot clear seed account information");
3367 synchronized (mPackagesLock) {
3368 UserData userData;
3369 synchronized (mUsersLock) {
3370 userData = getUserDataLU(UserHandle.getCallingUserId());
3371 if (userData == null) return;
3372 userData.clearSeedAccountData();
3373 }
3374 writeUserLP(userData);
3375 }
3376 }
3377
3378 @Override
3379 public boolean someUserHasSeedAccount(String accountName, String accountType)
3380 throws RemoteException {
3381 checkManageUsersPermission("Cannot check seed account information");
3382 synchronized (mUsersLock) {
3383 final int userSize = mUsers.size();
3384 for (int i = 0; i < userSize; i++) {
3385 final UserData data = mUsers.valueAt(i);
3386 if (data.info.isInitialized()) continue;
3387 if (data.seedAccountName == null || !data.seedAccountName.equals(accountName)) {
3388 continue;
3389 }
3390 if (data.seedAccountType == null || !data.seedAccountType.equals(accountType)) {
3391 continue;
3392 }
3393 return true;
3394 }
3395 }
3396 return false;
3397 }
3398
3399 @Override
Todd Kennedy60459ab2015-10-30 11:32:16 -07003400 public void onShellCommand(FileDescriptor in, FileDescriptor out,
Dianne Hackborn354736e2016-08-22 17:00:05 -07003401 FileDescriptor err, String[] args, ShellCallback callback,
3402 ResultReceiver resultReceiver) {
3403 (new Shell()).exec(this, in, out, err, args, callback, resultReceiver);
Todd Kennedy60459ab2015-10-30 11:32:16 -07003404 }
3405
3406 int onShellCommand(Shell shell, String cmd) {
3407 if (cmd == null) {
3408 return shell.handleDefaultCommands(cmd);
3409 }
3410
3411 final PrintWriter pw = shell.getOutPrintWriter();
3412 try {
3413 switch(cmd) {
3414 case "list":
3415 return runList(pw);
3416 }
3417 } catch (RemoteException e) {
3418 pw.println("Remote exception: " + e);
3419 }
3420 return -1;
3421 }
3422
3423 private int runList(PrintWriter pw) throws RemoteException {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003424 final IActivityManager am = ActivityManager.getService();
Todd Kennedy60459ab2015-10-30 11:32:16 -07003425 final List<UserInfo> users = getUsers(false);
3426 if (users == null) {
3427 pw.println("Error: couldn't get users");
3428 return 1;
3429 } else {
3430 pw.println("Users:");
3431 for (int i = 0; i < users.size(); i++) {
Jeff Sharkeye17ac152015-11-06 22:40:29 -08003432 String running = am.isUserRunning(users.get(i).id, 0) ? " running" : "";
Todd Kennedy60459ab2015-10-30 11:32:16 -07003433 pw.println("\t" + users.get(i).toString() + running);
3434 }
3435 return 0;
3436 }
3437 }
3438
3439 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -07003440 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06003441 if (!DumpUtils.checkDumpPermission(mContext, LOG_TAG, pw)) return;
Amith Yamasani920ace02012-09-20 22:15:37 -07003442
3443 long now = System.currentTimeMillis();
3444 StringBuilder sb = new StringBuilder();
3445 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003446 synchronized (mUsersLock) {
3447 pw.println("Users:");
3448 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003449 UserData userData = mUsers.valueAt(i);
3450 if (userData == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003451 continue;
3452 }
Amith Yamasani12747872015-12-07 14:19:49 -08003453 UserInfo userInfo = userData.info;
3454 final int userId = userInfo.id;
3455 pw.print(" "); pw.print(userInfo);
3456 pw.print(" serialNo="); pw.print(userInfo.serialNumber);
Makoto Onukie7927da2015-11-25 10:05:17 -08003457 if (mRemovingUserIds.get(userId)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003458 pw.print(" <removing> ");
3459 }
Amith Yamasani12747872015-12-07 14:19:49 -08003460 if (userInfo.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003461 pw.print(" <partial>");
3462 }
3463 pw.println();
Makoto Onuki88aef752017-03-29 16:52:03 -07003464 pw.print(" State: ");
3465 final int state;
3466 synchronized (mUserStates) {
3467 state = mUserStates.get(userId, -1);
3468 }
3469 pw.println(UserState.stateToString(state));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003470 pw.print(" Created: ");
Amith Yamasani12747872015-12-07 14:19:49 -08003471 if (userInfo.creationTime == 0) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003472 pw.println("<unknown>");
3473 } else {
3474 sb.setLength(0);
Amith Yamasani12747872015-12-07 14:19:49 -08003475 TimeUtils.formatDuration(now - userInfo.creationTime, sb);
Fyodor Kupolov82402752015-10-28 14:54:51 -07003476 sb.append(" ago");
3477 pw.println(sb);
3478 }
3479 pw.print(" Last logged in: ");
Amith Yamasani12747872015-12-07 14:19:49 -08003480 if (userInfo.lastLoggedInTime == 0) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003481 pw.println("<unknown>");
3482 } else {
3483 sb.setLength(0);
Amith Yamasani12747872015-12-07 14:19:49 -08003484 TimeUtils.formatDuration(now - userInfo.lastLoggedInTime, sb);
Fyodor Kupolov82402752015-10-28 14:54:51 -07003485 sb.append(" ago");
3486 pw.println(sb);
3487 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003488 pw.print(" Last logged in fingerprint: ");
3489 pw.println(userInfo.lastLoggedInFingerprint);
Makoto Onukie7927da2015-11-25 10:05:17 -08003490 pw.print(" Has profile owner: ");
3491 pw.println(mIsUserManaged.get(userId));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003492 pw.println(" Restrictions:");
3493 synchronized (mRestrictionsLock) {
3494 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003495 pw, " ", mBaseUserRestrictions.get(userInfo.id));
Pavel Grafov6a40f092016-10-25 15:46:51 +01003496 pw.println(" Device policy global restrictions:");
3497 UserRestrictionsUtils.dumpRestrictions(
3498 pw, " ", mDevicePolicyGlobalUserRestrictions.get(userInfo.id));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003499 pw.println(" Device policy local restrictions:");
3500 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003501 pw, " ", mDevicePolicyLocalUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003502 pw.println(" Effective restrictions:");
3503 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003504 pw, " ", mCachedEffectiveUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003505 }
Amith Yamasani12747872015-12-07 14:19:49 -08003506
3507 if (userData.account != null) {
3508 pw.print(" Account name: " + userData.account);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08003509 pw.println();
3510 }
Amith Yamasani12747872015-12-07 14:19:49 -08003511
3512 if (userData.seedAccountName != null) {
3513 pw.print(" Seed account name: " + userData.seedAccountName);
3514 pw.println();
3515 if (userData.seedAccountType != null) {
3516 pw.print(" account type: " + userData.seedAccountType);
3517 pw.println();
3518 }
3519 if (userData.seedAccountOptions != null) {
3520 pw.print(" account options exist");
3521 pw.println();
3522 }
3523 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003524 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003525 }
Amith Yamasani12747872015-12-07 14:19:49 -08003526 pw.println();
Pavel Grafov6a40f092016-10-25 15:46:51 +01003527 pw.println(" Device owner id:" + mDeviceOwnerUserId);
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01003528 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003529 pw.println(" Guest restrictions:");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003530 synchronized (mGuestRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003531 UserRestrictionsUtils.dumpRestrictions(pw, " ", mGuestRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003532 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003533 synchronized (mUsersLock) {
3534 pw.println();
3535 pw.println(" Device managed: " + mIsDeviceManaged);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003536 if (mRemovingUserIds.size() > 0) {
3537 pw.println();
3538 pw.println(" Recently removed userIds: " + mRecentlyRemovedIds);
3539 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003540 }
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003541 synchronized (mUserStates) {
3542 pw.println(" Started users state: " + mUserStates);
3543 }
Amith Yamasani12747872015-12-07 14:19:49 -08003544 // Dump some capabilities
3545 pw.println();
3546 pw.println(" Max users: " + UserManager.getMaxSupportedUsers());
3547 pw.println(" Supports switchable users: " + UserManager.supportsMultipleUsers());
Lenka Trochtova02fee152015-12-22 14:26:18 +01003548 pw.println(" All guests ephemeral: " + Resources.getSystem().getBoolean(
3549 com.android.internal.R.bool.config_guestUserEphemeral));
Amith Yamasani920ace02012-09-20 22:15:37 -07003550 }
3551 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08003552
3553 final class MainHandler extends Handler {
3554
3555 @Override
3556 public void handleMessage(Message msg) {
3557 switch (msg.what) {
3558 case WRITE_USER_MSG:
3559 removeMessages(WRITE_USER_MSG, msg.obj);
3560 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08003561 int userId = ((UserData) msg.obj).info.id;
3562 UserData userData = getUserDataNoChecks(userId);
3563 if (userData != null) {
3564 writeUserLP(userData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08003565 }
3566 }
3567 }
3568 }
3569 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07003570
3571 /**
3572 * @param userId
3573 * @return whether the user has been initialized yet
3574 */
Todd Kennedy0eb97382017-10-03 16:57:22 -07003575 boolean isUserInitialized(int userId) {
3576 return mLocalService.isUserInitialized(userId);
Amith Yamasanibb054c92015-07-09 14:16:27 -07003577 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003578
3579 private class LocalService extends UserManagerInternal {
Makoto Onuki068c54a2015-10-13 14:34:03 -07003580 @Override
Pavel Grafov6a40f092016-10-25 15:46:51 +01003581 public void setDevicePolicyUserRestrictions(int userId, @Nullable Bundle restrictions,
3582 boolean isDeviceOwner, int cameraRestrictionScope) {
3583 UserManagerService.this.setDevicePolicyUserRestrictionsInner(userId, restrictions,
3584 isDeviceOwner, cameraRestrictionScope);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003585 }
3586
3587 @Override
3588 public Bundle getBaseUserRestrictions(int userId) {
3589 synchronized (mRestrictionsLock) {
3590 return mBaseUserRestrictions.get(userId);
3591 }
3592 }
3593
3594 @Override
3595 public void setBaseUserRestrictionsByDpmsForMigration(
3596 int userId, Bundle baseRestrictions) {
3597 synchronized (mRestrictionsLock) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01003598 if (updateRestrictionsIfNeededLR(
3599 userId, new Bundle(baseRestrictions), mBaseUserRestrictions)) {
3600 invalidateEffectiveUserRestrictionsLR(userId);
3601 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003602 }
3603
Amith Yamasani12747872015-12-07 14:19:49 -08003604 final UserData userData = getUserDataNoChecks(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003605 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08003606 if (userData != null) {
3607 writeUserLP(userData);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003608 } else {
3609 Slog.w(LOG_TAG, "UserInfo not found for " + userId);
3610 }
3611 }
3612 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08003613
3614 @Override
3615 public boolean getUserRestriction(int userId, String key) {
3616 return getUserRestrictions(userId).getBoolean(key);
3617 }
3618
3619 @Override
3620 public void addUserRestrictionsListener(UserRestrictionsListener listener) {
3621 synchronized (mUserRestrictionsListeners) {
3622 mUserRestrictionsListeners.add(listener);
3623 }
3624 }
3625
3626 @Override
3627 public void removeUserRestrictionsListener(UserRestrictionsListener listener) {
3628 synchronized (mUserRestrictionsListeners) {
3629 mUserRestrictionsListeners.remove(listener);
3630 }
3631 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003632
3633 @Override
3634 public void setDeviceManaged(boolean isManaged) {
3635 synchronized (mUsersLock) {
3636 mIsDeviceManaged = isManaged;
3637 }
3638 }
3639
3640 @Override
3641 public void setUserManaged(int userId, boolean isManaged) {
3642 synchronized (mUsersLock) {
3643 mIsUserManaged.put(userId, isManaged);
3644 }
3645 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01003646
3647 @Override
3648 public void setUserIcon(int userId, Bitmap bitmap) {
3649 long ident = Binder.clearCallingIdentity();
3650 try {
3651 synchronized (mPackagesLock) {
3652 UserData userData = getUserDataNoChecks(userId);
3653 if (userData == null || userData.info.partial) {
3654 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
3655 return;
3656 }
3657 writeBitmapLP(userData.info, bitmap);
3658 writeUserLP(userData);
3659 }
3660 sendUserInfoChangedBroadcast(userId);
3661 } finally {
3662 Binder.restoreCallingIdentity(ident);
3663 }
3664 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01003665
3666 @Override
3667 public void setForceEphemeralUsers(boolean forceEphemeralUsers) {
3668 synchronized (mUsersLock) {
3669 mForceEphemeralUsers = forceEphemeralUsers;
3670 }
3671 }
3672
3673 @Override
3674 public void removeAllUsers() {
3675 if (UserHandle.USER_SYSTEM == ActivityManager.getCurrentUser()) {
3676 // Remove the non-system users straight away.
3677 removeNonSystemUsers();
3678 } else {
3679 // Switch to the system user first and then remove the other users.
3680 BroadcastReceiver userSwitchedReceiver = new BroadcastReceiver() {
3681 @Override
3682 public void onReceive(Context context, Intent intent) {
3683 int userId =
3684 intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3685 if (userId != UserHandle.USER_SYSTEM) {
3686 return;
3687 }
3688 mContext.unregisterReceiver(this);
3689 removeNonSystemUsers();
3690 }
3691 };
3692 IntentFilter userSwitchedFilter = new IntentFilter();
3693 userSwitchedFilter.addAction(Intent.ACTION_USER_SWITCHED);
3694 mContext.registerReceiver(
3695 userSwitchedReceiver, userSwitchedFilter, null, mHandler);
3696
3697 // Switch to the system user.
3698 ActivityManager am =
3699 (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
3700 am.switchUser(UserHandle.USER_SYSTEM);
3701 }
3702 }
phweisse9c44062016-02-10 12:57:38 +01003703
3704 @Override
Lenka Trochtova1ddda472016-02-12 10:42:12 +01003705 public void onEphemeralUserStop(int userId) {
3706 synchronized (mUsersLock) {
3707 UserInfo userInfo = getUserInfoLU(userId);
3708 if (userInfo != null && userInfo.isEphemeral()) {
3709 // Do not allow switching back to the ephemeral user again as the user is going
3710 // to be deleted.
3711 userInfo.flags |= UserInfo.FLAG_DISABLED;
3712 if (userInfo.isGuest()) {
3713 // Indicate that the guest will be deleted after it stops.
3714 userInfo.guestToRemove = true;
3715 }
3716 }
3717 }
3718 }
3719
3720 @Override
Alex Chaub6a9f942017-11-07 11:28:56 +08003721 public UserInfo createUserEvenWhenDisallowed(String name, int flags,
3722 String[] disallowedPackages) {
3723 UserInfo user = createUserInternalUnchecked(name, flags, UserHandle.USER_NULL,
3724 disallowedPackages);
phweisse9c44062016-02-10 12:57:38 +01003725 // Keep this in sync with UserManager.createUser
Christine Franks97a54802017-08-09 10:06:43 -07003726 if (user != null && !user.isAdmin() && !user.isDemo()) {
phweisse9c44062016-02-10 12:57:38 +01003727 setUserRestriction(UserManager.DISALLOW_SMS, true, user.id);
3728 setUserRestriction(UserManager.DISALLOW_OUTGOING_CALLS, true, user.id);
3729 }
3730 return user;
3731 }
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003732
3733 @Override
Nicolas Prevotdf1b87d2016-10-25 13:57:08 +01003734 public boolean removeUserEvenWhenDisallowed(int userId) {
3735 return removeUserUnchecked(userId);
3736 }
3737
3738 @Override
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003739 public boolean isUserRunning(int userId) {
3740 synchronized (mUserStates) {
3741 return mUserStates.get(userId, -1) >= 0;
3742 }
3743 }
3744
3745 @Override
3746 public void setUserState(int userId, int userState) {
3747 synchronized (mUserStates) {
3748 mUserStates.put(userId, userState);
3749 }
3750 }
3751
3752 @Override
3753 public void removeUserState(int userId) {
3754 synchronized (mUserStates) {
3755 mUserStates.delete(userId);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003756 }
3757 }
3758
3759 @Override
Michael Wachenschwanz3f2b6552017-05-15 13:53:09 -07003760 public int[] getUserIds() {
3761 return UserManagerService.this.getUserIds();
3762 }
3763
3764 @Override
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003765 public boolean isUserUnlockingOrUnlocked(int userId) {
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07003766 int state;
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003767 synchronized (mUserStates) {
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07003768 state = mUserStates.get(userId, -1);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003769 }
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07003770 // Special case, in the stopping/shutdown state user key can still be unlocked
3771 if (state == UserState.STATE_STOPPING || state == UserState.STATE_SHUTDOWN) {
3772 return StorageManager.isUserKeyUnlocked(userId);
3773 }
3774 return (state == UserState.STATE_RUNNING_UNLOCKING)
3775 || (state == UserState.STATE_RUNNING_UNLOCKED);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003776 }
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08003777
3778 @Override
3779 public boolean isUserUnlocked(int userId) {
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07003780 int state;
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08003781 synchronized (mUserStates) {
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07003782 state = mUserStates.get(userId, -1);
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08003783 }
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07003784 // Special case, in the stopping/shutdown state user key can still be unlocked
3785 if (state == UserState.STATE_STOPPING || state == UserState.STATE_SHUTDOWN) {
3786 return StorageManager.isUserKeyUnlocked(userId);
3787 }
3788 return state == UserState.STATE_RUNNING_UNLOCKED;
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08003789 }
Todd Kennedy0eb97382017-10-03 16:57:22 -07003790
3791 @Override
3792 public boolean isUserInitialized(int userId) {
3793 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
3794 }
3795
3796 @Override
3797 public boolean exists(int userId) {
3798 return getUserInfoNoChecks(userId) != null;
3799 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01003800 }
3801
3802 /* Remove all the users except of the system one. */
3803 private void removeNonSystemUsers() {
3804 ArrayList<UserInfo> usersToRemove = new ArrayList<>();
3805 synchronized (mUsersLock) {
3806 final int userSize = mUsers.size();
3807 for (int i = 0; i < userSize; i++) {
3808 UserInfo ui = mUsers.valueAt(i).info;
3809 if (ui.id != UserHandle.USER_SYSTEM) {
3810 usersToRemove.add(ui);
3811 }
3812 }
3813 }
3814 for (UserInfo ui: usersToRemove) {
3815 removeUser(ui.id);
3816 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003817 }
Todd Kennedy60459ab2015-10-30 11:32:16 -07003818
3819 private class Shell extends ShellCommand {
3820 @Override
3821 public int onCommand(String cmd) {
3822 return onShellCommand(this, cmd);
3823 }
3824
3825 @Override
3826 public void onHelp() {
3827 final PrintWriter pw = getOutPrintWriter();
3828 pw.println("User manager (user) commands:");
3829 pw.println(" help");
3830 pw.println(" Print this help text.");
3831 pw.println("");
3832 pw.println(" list");
3833 pw.println(" Prints all users on the system.");
3834 }
3835 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003836
3837 private static void debug(String message) {
3838 Log.d(LOG_TAG, message +
3839 (DBG_WITH_STACKTRACE ? " called at\n" + Debug.getCallers(10, " ") : ""));
3840 }
Kenny Guy02c89902016-11-15 19:36:38 +00003841
3842 @VisibleForTesting
3843 static int getMaxManagedProfiles() {
3844 // Allow overriding max managed profiles on debuggable builds for testing
3845 // of multiple profiles.
3846 if (!Build.IS_DEBUGGABLE) {
3847 return MAX_MANAGED_PROFILES;
3848 } else {
3849 return SystemProperties.getInt("persist.sys.max_profiles",
3850 MAX_MANAGED_PROFILES);
3851 }
3852 }
3853
3854 @VisibleForTesting
3855 int getFreeProfileBadgeLU(int parentUserId) {
3856 int maxManagedProfiles = getMaxManagedProfiles();
3857 boolean[] usedBadges = new boolean[maxManagedProfiles];
3858 final int userSize = mUsers.size();
3859 for (int i = 0; i < userSize; i++) {
3860 UserInfo ui = mUsers.valueAt(i).info;
3861 // Check which badge indexes are already used by this profile group.
3862 if (ui.isManagedProfile()
3863 && ui.profileGroupId == parentUserId
3864 && !mRemovingUserIds.get(ui.id)
3865 && ui.profileBadge < maxManagedProfiles) {
3866 usedBadges[ui.profileBadge] = true;
3867 }
3868 }
3869 for (int i = 0; i < maxManagedProfiles; i++) {
3870 if (!usedBadges[i]) {
3871 return i;
3872 }
3873 }
3874 return 0;
3875 }
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07003876
3877 /**
3878 * Checks if the given user has a managed profile associated with it.
3879 * @param userId The parent user
3880 * @return
3881 */
3882 boolean hasManagedProfile(int userId) {
3883 synchronized (mUsersLock) {
3884 UserInfo userInfo = getUserInfoLU(userId);
3885 final int userSize = mUsers.size();
3886 for (int i = 0; i < userSize; i++) {
3887 UserInfo profile = mUsers.valueAt(i).info;
3888 if (userId != profile.id && isProfileOf(userInfo, profile)) {
3889 return true;
3890 }
3891 }
3892 return false;
3893 }
3894 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003895}