blob: dbf413f0415d9e5143d8f3545de997c513626ad1 [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;
Sudheer Shanka38c67d32016-08-02 22:13:17 +000030import android.app.AppGlobals;
Todd Kennedy60459ab2015-10-30 11:32:16 -070031import android.app.IActivityManager;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070032import android.app.IStopUserCallback;
Benjamin Franzf02420c2016-04-04 18:52:21 +010033import android.app.KeyguardManager;
Ricky Waib1dd80b2016-06-07 18:00:55 +010034import android.app.PendingIntent;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070035import android.content.BroadcastReceiver;
Amith Yamasani258848d2012-08-10 17:06:33 -070036import android.content.Context;
37import android.content.Intent;
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +010038import android.content.IntentFilter;
Benjamin Franzf02420c2016-04-04 18:52:21 +010039import android.content.IntentSender;
Amith Yamasani0b285492011-04-14 17:35:23 -070040import android.content.pm.PackageManager;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -080041import android.content.pm.PackageManager.NameNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070042import android.content.pm.UserInfo;
Lenka Trochtova02fee152015-12-22 14:26:18 +010043import android.content.res.Resources;
Amith Yamasanie928d7d2012-09-17 21:46:51 -070044import android.graphics.Bitmap;
Amith Yamasani258848d2012-08-10 17:06:33 -070045import android.os.Binder;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -060046import android.os.Build;
Amith Yamasanie4cf7342012-12-17 11:12:09 -080047import android.os.Bundle;
Makoto Onuki1a2cd742015-11-16 13:51:27 -080048import android.os.Debug;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070049import android.os.Environment;
50import android.os.FileUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080051import android.os.Handler;
Svet Ganov9cea80cd2016-02-16 11:47:00 -080052import android.os.IBinder;
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;
Jeff Sharkey6dce4962015-07-03 18:08:41 -070074import android.system.ErrnoException;
75import android.system.Os;
76import android.system.OsConstants;
Amith Yamasanieb437d42016-04-29 09:31:25 -070077import android.text.TextUtils;
Amith Yamasani2a003292012-08-14 18:25:45 -070078import android.util.AtomicFile;
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -070079import android.util.IntArray;
Amith Yamasani655d0e22013-06-12 14:19:10 -070080import android.util.Log;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070081import android.util.Slog;
82import android.util.SparseArray;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080083import android.util.SparseBooleanArray;
Amith Yamasaniea1b9d72016-05-27 15:57:38 +000084import android.util.SparseIntArray;
Amith Yamasani920ace02012-09-20 22:15:37 -070085import android.util.TimeUtils;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070086import android.util.Xml;
87
Makoto Onuki068c54a2015-10-13 14:34:03 -070088import com.android.internal.annotations.GuardedBy;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070089import com.android.internal.annotations.VisibleForTesting;
Jason Monk62062992014-05-06 09:55:28 -040090import com.android.internal.app.IAppOpsService;
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -080091import com.android.internal.logging.MetricsLogger;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -060092import com.android.internal.util.DumpUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080093import com.android.internal.util.FastXmlSerializer;
Makoto Onuki068c54a2015-10-13 14:34:03 -070094import com.android.internal.util.Preconditions;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070095import com.android.internal.util.XmlUtils;
Clara Bayarri10ad84a2015-12-01 17:38:05 +000096import com.android.internal.widget.LockPatternUtils;
Amith Yamasani515d4062015-09-28 11:30:06 -070097import com.android.server.LocalServices;
Jeff Sharkey5f3e9342017-03-13 14:53:11 -060098import com.android.server.LockGuard;
Amith Yamasanid04aaa32016-06-13 12:09:36 -070099import com.android.server.SystemService;
Amith Yamasaniea1b9d72016-05-27 15:57:38 +0000100import com.android.server.am.UserState;
Suprabh Shuklac5e057c2016-08-08 16:22:44 -0700101import com.android.server.storage.DeviceStorageMonitorInternal;
Tony Mak6dc428f2016-10-10 15:48:27 +0100102
Jeff Sharkey47f71082016-02-01 17:03:54 -0700103import libcore.io.IoUtils;
104import libcore.util.Objects;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800105
106import org.xmlpull.v1.XmlPullParser;
107import org.xmlpull.v1.XmlPullParserException;
108import org.xmlpull.v1.XmlSerializer;
109
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700110import java.io.BufferedOutputStream;
111import java.io.File;
Amith Yamasani920ace02012-09-20 22:15:37 -0700112import java.io.FileDescriptor;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700113import java.io.FileInputStream;
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700114import java.io.FileNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700115import java.io.FileOutputStream;
Kenny Guy02c89902016-11-15 19:36:38 +0000116import java.io.InputStream;
117import java.io.OutputStream;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700118import java.io.IOException;
Amith Yamasani920ace02012-09-20 22:15:37 -0700119import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100120import java.nio.charset.StandardCharsets;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700121import java.util.ArrayList;
Pavel Grafov6a40f092016-10-25 15:46:51 +0100122import java.util.Collections;
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700123import java.util.LinkedList;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700124import java.util.List;
125
Makoto Onuki068c54a2015-10-13 14:34:03 -0700126/**
127 * Service for {@link UserManager}.
128 *
129 * Method naming convention:
Fyodor Kupolov82402752015-10-28 14:54:51 -0700130 * <ul>
Fyodor Kupolovd31cee92017-09-05 16:31:08 -0700131 * <li> Methods suffixed with "LAr" should be called within the {@link #mAppRestrictionsLock} lock.
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800132 * <li> Methods suffixed with "LP" should be called within the {@link #mPackagesLock} lock.
Fyodor Kupolov82402752015-10-28 14:54:51 -0700133 * <li> Methods suffixed with "LR" should be called within the {@link #mRestrictionsLock} lock.
134 * <li> Methods suffixed with "LU" should be called within the {@link #mUsersLock} lock.
135 * </ul>
Makoto Onuki068c54a2015-10-13 14:34:03 -0700136 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700137public class UserManagerService extends IUserManager.Stub {
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700138
Amith Yamasani2a003292012-08-14 18:25:45 -0700139 private static final String LOG_TAG = "UserManagerService";
Makoto Onuki81c61ea2016-01-22 11:22:26 -0800140 static final boolean DBG = false; // DO NOT SUBMIT WITH TRUE
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800141 private static final boolean DBG_WITH_STACKTRACE = false; // DO NOT SUBMIT WITH TRUE
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700142 // Can be used for manual testing of id recycling
143 private static final boolean RELEASE_DELETED_USER_ID = false; // DO NOT SUBMIT WITH TRUE
Amith Yamasani16389312012-10-17 21:20:14 -0700144
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700145 private static final String TAG_NAME = "name";
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800146 private static final String TAG_ACCOUNT = "account";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700147 private static final String ATTR_FLAGS = "flags";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700148 private static final String ATTR_ICON_PATH = "icon";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700149 private static final String ATTR_ID = "id";
Amith Yamasani920ace02012-09-20 22:15:37 -0700150 private static final String ATTR_CREATION_TIME = "created";
151 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -0600152 private static final String ATTR_LAST_LOGGED_IN_FINGERPRINT = "lastLoggedInFingerprint";
Amith Yamasani2a003292012-08-14 18:25:45 -0700153 private static final String ATTR_SERIAL_NO = "serialNumber";
154 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700155 private static final String ATTR_PARTIAL = "partial";
Adam Lesinskieddeb492014-09-08 17:50:03 -0700156 private static final String ATTR_GUEST_TO_REMOVE = "guestToRemove";
Amith Yamasani6f34b412012-10-22 18:19:27 -0700157 private static final String ATTR_USER_VERSION = "version";
Kenny Guy2a764942014-04-02 13:29:20 +0100158 private static final String ATTR_PROFILE_GROUP_ID = "profileGroupId";
Kenny Guy02c89902016-11-15 19:36:38 +0000159 private static final String ATTR_PROFILE_BADGE = "profileBadge";
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700160 private static final String ATTR_RESTRICTED_PROFILE_PARENT_ID = "restrictedProfileParentId";
Amith Yamasani12747872015-12-07 14:19:49 -0800161 private static final String ATTR_SEED_ACCOUNT_NAME = "seedAccountName";
162 private static final String ATTR_SEED_ACCOUNT_TYPE = "seedAccountType";
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530163 private static final String TAG_GUEST_RESTRICTIONS = "guestRestrictions";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700164 private static final String TAG_USERS = "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700165 private static final String TAG_USER = "user";
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800166 private static final String TAG_RESTRICTIONS = "restrictions";
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800167 private static final String TAG_DEVICE_POLICY_RESTRICTIONS = "device_policy_restrictions";
Pavel Grafov6a40f092016-10-25 15:46:51 +0100168 private static final String TAG_DEVICE_POLICY_GLOBAL_RESTRICTIONS =
169 "device_policy_global_restrictions";
170 /** Legacy name for device owner id tag. */
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +0100171 private static final String TAG_GLOBAL_RESTRICTION_OWNER_ID = "globalRestrictionOwnerUserId";
Pavel Grafov6a40f092016-10-25 15:46:51 +0100172 private static final String TAG_DEVICE_OWNER_USER_ID = "deviceOwnerUserId";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800173 private static final String TAG_ENTRY = "entry";
174 private static final String TAG_VALUE = "value";
Amith Yamasani12747872015-12-07 14:19:49 -0800175 private static final String TAG_SEED_ACCOUNT_OPTIONS = "seedAccountOptions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800176 private static final String ATTR_KEY = "key";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700177 private static final String ATTR_VALUE_TYPE = "type";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800178 private static final String ATTR_MULTIPLE = "m";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700179
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700180 private static final String ATTR_TYPE_STRING_ARRAY = "sa";
181 private static final String ATTR_TYPE_STRING = "s";
182 private static final String ATTR_TYPE_BOOLEAN = "b";
Amith Yamasani5b5aa402014-06-01 20:10:14 -0700183 private static final String ATTR_TYPE_INTEGER = "i";
Fyodor Kupolov262f9952015-03-23 18:55:11 -0700184 private static final String ATTR_TYPE_BUNDLE = "B";
185 private static final String ATTR_TYPE_BUNDLE_ARRAY = "BA";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700186
Amith Yamasani0b285492011-04-14 17:35:23 -0700187 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700188 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700189 private static final String USER_PHOTO_FILENAME = "photo.png";
Adrian Roos1bdff912015-02-17 15:51:35 +0100190 private static final String USER_PHOTO_FILENAME_TMP = USER_PHOTO_FILENAME + ".tmp";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700191
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800192 private static final String RESTRICTIONS_FILE_PREFIX = "res_";
Amith Yamasanifc95e702013-09-26 13:20:17 -0700193 private static final String XML_SUFFIX = ".xml";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800194
Sudheer Shankaf5cea032016-06-08 17:13:24 -0700195 private static final int ALLOWED_FLAGS_FOR_CREATE_USERS_PERMISSION =
196 UserInfo.FLAG_MANAGED_PROFILE
197 | UserInfo.FLAG_EPHEMERAL
198 | UserInfo.FLAG_RESTRICTED
Sudheer Shanka234d1af2016-08-26 15:42:53 -0700199 | UserInfo.FLAG_GUEST
200 | UserInfo.FLAG_DEMO;
Sudheer Shankaf5cea032016-06-08 17:13:24 -0700201
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700202 @VisibleForTesting
203 static final int MIN_USER_ID = 10;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700204 // We need to keep process uid within Integer.MAX_VALUE.
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700205 @VisibleForTesting
206 static final int MAX_USER_ID = Integer.MAX_VALUE / UserHandle.PER_USER_RANGE;
207
208 // Max size of the queue of recently removed users
209 @VisibleForTesting
210 static final int MAX_RECENTLY_REMOVED_IDS_SIZE = 100;
Amith Yamasani634cf312012-10-04 17:34:21 -0700211
Pavel Grafov6a40f092016-10-25 15:46:51 +0100212 private static final int USER_VERSION = 7;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700213
Amith Yamasani920ace02012-09-20 22:15:37 -0700214 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
215
Nicolas Prevotb8186812015-08-06 15:00:03 +0100216 // Maximum number of managed profiles permitted per user is 1. This cannot be increased
Amith Yamasani95ab7842014-08-11 17:09:26 -0700217 // without first making sure that the rest of the framework is prepared for it.
Kenny Guy02c89902016-11-15 19:36:38 +0000218 @VisibleForTesting
219 static final int MAX_MANAGED_PROFILES = 1;
Amith Yamasani95ab7842014-08-11 17:09:26 -0700220
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800221 static final int WRITE_USER_MSG = 1;
222 static final int WRITE_USER_DELAY = 2*1000; // 2 seconds
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530223
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -0800224 // Tron counters
225 private static final String TRON_GUEST_CREATED = "users_guest_created";
226 private static final String TRON_USER_CREATED = "users_user_created";
Christine Franks88220562017-05-24 11:11:21 -0700227 private static final String TRON_DEMO_CREATED = "users_demo_created";
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -0800228
Dianne Hackborn4428e172012-08-24 17:43:05 -0700229 private final Context mContext;
230 private final PackageManagerService mPm;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700231 private final Object mPackagesLock;
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800232 private final UserDataPreparer mUserDataPreparer;
Fyodor Kupolov82402752015-10-28 14:54:51 -0700233 // Short-term lock for internal state, when interaction/sync with PM is not required
Jeff Sharkey5f3e9342017-03-13 14:53:11 -0600234 private final Object mUsersLock = LockGuard.installNewLock(LockGuard.INDEX_USER);
Fyodor Kupolov82402752015-10-28 14:54:51 -0700235 private final Object mRestrictionsLock = new Object();
Fyodor Kupolovd31cee92017-09-05 16:31:08 -0700236 // Used for serializing access to app restriction files
237 private final Object mAppRestrictionsLock = new Object();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700238
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800239 private final Handler mHandler;
240
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700241 private final File mUsersDir;
242 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700243
Svet Ganov9cea80cd2016-02-16 11:47:00 -0800244 private static final IBinder mUserRestriconToken = new Binder();
245
Makoto Onuki068c54a2015-10-13 14:34:03 -0700246 /**
Amith Yamasani12747872015-12-07 14:19:49 -0800247 * User-related information that is used for persisting to flash. Only UserInfo is
248 * directly exposed to other system apps.
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800249 */
Kenny Guy02c89902016-11-15 19:36:38 +0000250 @VisibleForTesting
251 static class UserData {
Amith Yamasani12747872015-12-07 14:19:49 -0800252 // Basic user information and properties
253 UserInfo info;
254 // Account name used when there is a strong association between a user and an account
255 String account;
256 // Account information for seeding into a newly created user. This could also be
257 // used for login validation for an existing user, for updating their credentials.
258 // In the latter case, data may not need to be persisted as it is only valid for the
259 // current login session.
260 String seedAccountName;
261 String seedAccountType;
262 PersistableBundle seedAccountOptions;
263 // Whether to perist the seed account information to be available after a boot
264 boolean persistSeedData;
265
266 void clearSeedAccountData() {
267 seedAccountName = null;
268 seedAccountType = null;
269 seedAccountOptions = null;
270 persistSeedData = false;
271 }
272 }
273
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800274 @GuardedBy("mUsersLock")
Amith Yamasani12747872015-12-07 14:19:49 -0800275 private final SparseArray<UserData> mUsers = new SparseArray<>();
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800276
277 /**
Makoto Onuki068c54a2015-10-13 14:34:03 -0700278 * User restrictions set via UserManager. This doesn't include restrictions set by
Pavel Grafov6a40f092016-10-25 15:46:51 +0100279 * device owner / profile owners. Only non-empty restriction bundles are stored.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700280 *
281 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
282 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
283 * maybe shared between {@link #mBaseUserRestrictions} and
284 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
285 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700286 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700287 */
288 @GuardedBy("mRestrictionsLock")
289 private final SparseArray<Bundle> mBaseUserRestrictions = new SparseArray<>();
290
291 /**
292 * Cached user restrictions that are in effect -- i.e. {@link #mBaseUserRestrictions} combined
293 * with device / profile owner restrictions. We'll initialize it lazily; use
294 * {@link #getEffectiveUserRestrictions} to access it.
295 *
296 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
297 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
298 * maybe shared between {@link #mBaseUserRestrictions} and
299 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
300 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700301 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700302 */
303 @GuardedBy("mRestrictionsLock")
304 private final SparseArray<Bundle> mCachedEffectiveUserRestrictions = new SparseArray<>();
305
Makoto Onuki4f160732015-10-27 17:15:38 -0700306 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800307 * User restrictions that have already been applied in
308 * {@link #updateUserRestrictionsInternalLR(Bundle, int)}. We use it to detect restrictions
309 * that have changed since the last
310 * {@link #updateUserRestrictionsInternalLR(Bundle, int)} call.
Makoto Onuki4f160732015-10-27 17:15:38 -0700311 */
312 @GuardedBy("mRestrictionsLock")
313 private final SparseArray<Bundle> mAppliedUserRestrictions = new SparseArray<>();
314
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800315 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800316 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
Pavel Grafov6a40f092016-10-25 15:46:51 +0100317 * that should be applied to all users, including guests. Only non-empty restriction bundles are
318 * stored.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800319 */
320 @GuardedBy("mRestrictionsLock")
Pavel Grafov6a40f092016-10-25 15:46:51 +0100321 private final SparseArray<Bundle> mDevicePolicyGlobalUserRestrictions = new SparseArray<>();
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800322
323 /**
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +0100324 * Id of the user that set global restrictions.
325 */
326 @GuardedBy("mRestrictionsLock")
Pavel Grafov6a40f092016-10-25 15:46:51 +0100327 private int mDeviceOwnerUserId = UserHandle.USER_NULL;
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +0100328
329 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800330 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
Pavel Grafov6a40f092016-10-25 15:46:51 +0100331 * for each user. Only non-empty restriction bundles are stored.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800332 */
333 @GuardedBy("mRestrictionsLock")
334 private final SparseArray<Bundle> mDevicePolicyLocalUserRestrictions = new SparseArray<>();
335
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800336 @GuardedBy("mGuestRestrictions")
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530337 private final Bundle mGuestRestrictions = new Bundle();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800338
339 /**
340 * Set of user IDs being actively removed. Removed IDs linger in this set
341 * for several seconds to work around a VFS caching issue.
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700342 * Use {@link #addRemovingUserIdLocked(int)} to add elements to this array
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800343 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700344 @GuardedBy("mUsersLock")
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800345 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700346
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700347 /**
348 * Queue of recently removed userIds. Used for recycling of userIds
349 */
350 @GuardedBy("mUsersLock")
351 private final LinkedList<Integer> mRecentlyRemovedIds = new LinkedList<>();
352
Fyodor Kupolov82402752015-10-28 14:54:51 -0700353 @GuardedBy("mUsersLock")
Amith Yamasani0b285492011-04-14 17:35:23 -0700354 private int[] mUserIds;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800355 @GuardedBy("mPackagesLock")
Amith Yamasani2a003292012-08-14 18:25:45 -0700356 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700357 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700358
Jason Monk62062992014-05-06 09:55:28 -0400359 private IAppOpsService mAppOpsService;
360
Makoto Onuki068c54a2015-10-13 14:34:03 -0700361 private final LocalService mLocalService;
362
Makoto Onukie7927da2015-11-25 10:05:17 -0800363 @GuardedBy("mUsersLock")
364 private boolean mIsDeviceManaged;
365
366 @GuardedBy("mUsersLock")
367 private final SparseBooleanArray mIsUserManaged = new SparseBooleanArray();
368
Makoto Onukid45a4a22015-11-02 17:17:38 -0800369 @GuardedBy("mUserRestrictionsListeners")
370 private final ArrayList<UserRestrictionsListener> mUserRestrictionsListeners =
371 new ArrayList<>();
372
Clara Bayarria1771112015-12-18 16:29:18 +0000373 private final LockPatternUtils mLockPatternUtils;
374
Ricky Waib1dd80b2016-06-07 18:00:55 +0100375 private final String ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK =
376 "com.android.server.pm.DISABLE_QUIET_MODE_AFTER_UNLOCK";
377
378 private final BroadcastReceiver mDisableQuietModeCallback = new BroadcastReceiver() {
379 @Override
380 public void onReceive(Context context, Intent intent) {
381 if (ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK.equals(intent.getAction())) {
382 final IntentSender target = intent.getParcelableExtra(Intent.EXTRA_INTENT);
383 final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_ID, 0);
384 setQuietModeEnabled(userHandle, false);
385 if (target != null) {
386 try {
387 mContext.startIntentSender(target, null, 0, 0, 0);
388 } catch (IntentSender.SendIntentException e) {
389 /* ignore */
390 }
391 }
392 }
393 }
394 };
395
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +0100396 /**
397 * Whether all users should be created ephemeral.
398 */
399 @GuardedBy("mUsersLock")
400 private boolean mForceEphemeralUsers;
401
Amith Yamasaniea1b9d72016-05-27 15:57:38 +0000402 @GuardedBy("mUserStates")
403 private final SparseIntArray mUserStates = new SparseIntArray();
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -0700404
Amith Yamasani258848d2012-08-10 17:06:33 -0700405 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700406
Dianne Hackborn4428e172012-08-24 17:43:05 -0700407 public static UserManagerService getInstance() {
408 synchronized (UserManagerService.class) {
409 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700410 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700411 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700412
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700413 public static class LifeCycle extends SystemService {
414
415 private UserManagerService mUms;
416
417 /**
418 * @param context
419 */
420 public LifeCycle(Context context) {
421 super(context);
422 }
423
424 @Override
425 public void onStart() {
426 mUms = UserManagerService.getInstance();
427 publishBinderService(Context.USER_SERVICE, mUms);
428 }
429
430 @Override
431 public void onBootPhase(int phase) {
432 if (phase == SystemService.PHASE_ACTIVITY_MANAGER_READY) {
433 mUms.cleanupPartialUsers();
434 }
435 }
436 }
437
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700438 // TODO b/28848102 Add support for test dependencies injection
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800439 @VisibleForTesting
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700440 UserManagerService(Context context) {
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800441 this(context, null, null, new Object(), context.getCacheDir());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700442 }
443
Dianne Hackborn4428e172012-08-24 17:43:05 -0700444 /**
445 * Called by package manager to create the service. This is closely
446 * associated with the package manager, and the given lock is the
447 * package manager's own lock.
448 */
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800449 UserManagerService(Context context, PackageManagerService pm, UserDataPreparer userDataPreparer,
450 Object packagesLock) {
451 this(context, pm, userDataPreparer, packagesLock, Environment.getDataDirectory());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700452 }
453
Dianne Hackborn4428e172012-08-24 17:43:05 -0700454 private UserManagerService(Context context, PackageManagerService pm,
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800455 UserDataPreparer userDataPreparer, Object packagesLock, File dataDir) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700456 mContext = context;
457 mPm = pm;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700458 mPackagesLock = packagesLock;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800459 mHandler = new MainHandler();
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800460 mUserDataPreparer = userDataPreparer;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800461 synchronized (mPackagesLock) {
462 mUsersDir = new File(dataDir, USER_INFO_DIR);
463 mUsersDir.mkdirs();
464 // Make zeroth user directory, for services to migrate their files to that location
465 File userZeroDir = new File(mUsersDir, String.valueOf(UserHandle.USER_SYSTEM));
466 userZeroDir.mkdirs();
467 FileUtils.setPermissions(mUsersDir.toString(),
468 FileUtils.S_IRWXU | FileUtils.S_IRWXG | FileUtils.S_IROTH | FileUtils.S_IXOTH,
469 -1, -1);
470 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
471 initDefaultGuestRestrictions();
472 readUserListLP();
473 sInstance = this;
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700474 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700475 mLocalService = new LocalService();
476 LocalServices.addService(UserManagerInternal.class, mLocalService);
Clara Bayarria1771112015-12-18 16:29:18 +0000477 mLockPatternUtils = new LockPatternUtils(mContext);
Amith Yamasaniea1b9d72016-05-27 15:57:38 +0000478 mUserStates.put(UserHandle.USER_SYSTEM, UserState.STATE_BOOTING);
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700479 }
480
481 void systemReady() {
Jason Monk62062992014-05-06 09:55:28 -0400482 mAppOpsService = IAppOpsService.Stub.asInterface(
483 ServiceManager.getService(Context.APP_OPS_SERVICE));
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800484
485 synchronized (mRestrictionsLock) {
486 applyUserRestrictionsLR(UserHandle.USER_SYSTEM);
Jason Monk62062992014-05-06 09:55:28 -0400487 }
Samuel Tand9453b82016-03-14 15:57:02 -0700488
489 UserInfo currentGuestUser = findCurrentGuestUser();
490 if (currentGuestUser != null && !hasUserRestriction(
491 UserManager.DISALLOW_CONFIG_WIFI, currentGuestUser.id)) {
492 // If a guest user currently exists, apply the DISALLOW_CONFIG_WIFI option
493 // to it, in case this guest was created in a previous version where this
494 // user restriction was not a default guest restriction.
495 setUserRestriction(UserManager.DISALLOW_CONFIG_WIFI, true, currentGuestUser.id);
496 }
Amith Yamasanieb437d42016-04-29 09:31:25 -0700497
Ricky Waib1dd80b2016-06-07 18:00:55 +0100498 mContext.registerReceiver(mDisableQuietModeCallback,
499 new IntentFilter(ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK),
500 null, mHandler);
Amith Yamasani258848d2012-08-10 17:06:33 -0700501 }
502
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700503 void cleanupPartialUsers() {
504 // Prune out any partially created, partially removed and ephemeral users.
505 ArrayList<UserInfo> partials = new ArrayList<>();
506 synchronized (mUsersLock) {
507 final int userSize = mUsers.size();
508 for (int i = 0; i < userSize; i++) {
509 UserInfo ui = mUsers.valueAt(i).info;
510 if ((ui.partial || ui.guestToRemove || ui.isEphemeral()) && i != 0) {
511 partials.add(ui);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700512 addRemovingUserIdLocked(ui.id);
Amith Yamasaniae261892016-06-27 10:40:09 -0700513 ui.partial = true;
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700514 }
515 }
516 }
517 final int partialsSize = partials.size();
518 for (int i = 0; i < partialsSize; i++) {
519 UserInfo ui = partials.get(i);
520 Slog.w(LOG_TAG, "Removing partially created user " + ui.id
521 + " (name=" + ui.name + ")");
522 removeUserState(ui.id);
523 }
524 }
525
Amith Yamasani258848d2012-08-10 17:06:33 -0700526 @Override
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800527 public String getUserAccount(int userId) {
528 checkManageUserAndAcrossUsersFullPermission("get user account");
529 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800530 return mUsers.get(userId).account;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800531 }
532 }
533
534 @Override
535 public void setUserAccount(int userId, String accountName) {
536 checkManageUserAndAcrossUsersFullPermission("set user account");
Amith Yamasani12747872015-12-07 14:19:49 -0800537 UserData userToUpdate = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800538 synchronized (mPackagesLock) {
539 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800540 final UserData userData = mUsers.get(userId);
541 if (userData == null) {
542 Slog.e(LOG_TAG, "User not found for setting user account: u" + userId);
543 return;
544 }
545 String currentAccount = userData.account;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800546 if (!Objects.equal(currentAccount, accountName)) {
Amith Yamasani12747872015-12-07 14:19:49 -0800547 userData.account = accountName;
548 userToUpdate = userData;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800549 }
550 }
551
552 if (userToUpdate != null) {
553 writeUserLP(userToUpdate);
554 }
555 }
556 }
557
558 @Override
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700559 public UserInfo getPrimaryUser() {
560 checkManageUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700561 synchronized (mUsersLock) {
Amith Yamasani515d4062015-09-28 11:30:06 -0700562 final int userSize = mUsers.size();
563 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800564 UserInfo ui = mUsers.valueAt(i).info;
Xiaohui Chend3e9e182015-11-18 13:37:32 -0800565 if (ui.isPrimary() && !mRemovingUserIds.get(ui.id)) {
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700566 return ui;
567 }
568 }
569 }
570 return null;
571 }
572
573 @Override
Xiaohui Chen594f2082015-08-18 11:04:20 -0700574 public @NonNull List<UserInfo> getUsers(boolean excludeDying) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -0700575 checkManageOrCreateUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700576 synchronized (mUsersLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700577 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasani515d4062015-09-28 11:30:06 -0700578 final int userSize = mUsers.size();
579 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800580 UserInfo ui = mUsers.valueAt(i).info;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700581 if (ui.partial) {
582 continue;
583 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800584 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Amith Yamasani6f48d6e2016-03-23 14:28:25 -0700585 users.add(userWithName(ui));
Amith Yamasani920ace02012-09-20 22:15:37 -0700586 }
Amith Yamasani13593602012-03-22 16:16:17 -0700587 }
588 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700589 }
Amith Yamasani13593602012-03-22 16:16:17 -0700590 }
591
Amith Yamasani258848d2012-08-10 17:06:33 -0700592 @Override
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100593 public List<UserInfo> getProfiles(int userId, boolean enabledOnly) {
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700594 boolean returnFullInfo = true;
Amith Yamasani4f582632014-02-19 14:31:52 -0800595 if (userId != UserHandle.getCallingUserId()) {
Sudheer Shanka74680912016-07-29 11:03:37 -0700596 checkManageOrCreateUsersPermission("getting profiles related to user " + userId);
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700597 } else {
598 returnFullInfo = hasManageUsersPermission();
Amith Yamasani4f582632014-02-19 14:31:52 -0800599 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700600 final long ident = Binder.clearCallingIdentity();
601 try {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700602 synchronized (mUsersLock) {
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700603 return getProfilesLU(userId, enabledOnly, returnFullInfo);
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100604 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700605 } finally {
606 Binder.restoreCallingIdentity(ident);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000607 }
608 }
609
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700610 @Override
611 public int[] getProfileIds(int userId, boolean enabledOnly) {
612 if (userId != UserHandle.getCallingUserId()) {
bohu12d23a12016-09-26 16:20:07 -0700613 checkManageOrCreateUsersPermission("getting profiles related to user " + userId);
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700614 }
615 final long ident = Binder.clearCallingIdentity();
616 try {
617 synchronized (mUsersLock) {
618 return getProfileIdsLU(userId, enabledOnly).toArray();
619 }
620 } finally {
621 Binder.restoreCallingIdentity(ident);
622 }
623 }
624
Amith Yamasanibe465322014-04-24 13:45:17 -0700625 /** Assume permissions already checked and caller's identity cleared */
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700626 private List<UserInfo> getProfilesLU(int userId, boolean enabledOnly, boolean fullInfo) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700627 IntArray profileIds = getProfileIdsLU(userId, enabledOnly);
628 ArrayList<UserInfo> users = new ArrayList<>(profileIds.size());
629 for (int i = 0; i < profileIds.size(); i++) {
630 int profileId = profileIds.get(i);
631 UserInfo userInfo = mUsers.get(profileId).info;
632 // If full info is not required - clear PII data to prevent 3P apps from reading it
633 if (!fullInfo) {
634 userInfo = new UserInfo(userInfo);
635 userInfo.name = null;
636 userInfo.iconPath = null;
637 } else {
638 userInfo = userWithName(userInfo);
639 }
640 users.add(userInfo);
641 }
642 return users;
643 }
644
645 /**
646 * Assume permissions already checked and caller's identity cleared
647 */
648 private IntArray getProfileIdsLU(int userId, boolean enabledOnly) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700649 UserInfo user = getUserInfoLU(userId);
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700650 IntArray result = new IntArray(mUsers.size());
Amith Yamasanidda003f2014-08-28 18:06:51 -0700651 if (user == null) {
652 // Probably a dying user
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700653 return result;
Amith Yamasanidda003f2014-08-28 18:06:51 -0700654 }
Amith Yamasani515d4062015-09-28 11:30:06 -0700655 final int userSize = mUsers.size();
656 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800657 UserInfo profile = mUsers.valueAt(i).info;
Amith Yamasanibe465322014-04-24 13:45:17 -0700658 if (!isProfileOf(user, profile)) {
659 continue;
660 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100661 if (enabledOnly && !profile.isEnabled()) {
662 continue;
Amith Yamasanibe465322014-04-24 13:45:17 -0700663 }
Amith Yamasani70fcf0c2014-07-11 08:40:19 -0700664 if (mRemovingUserIds.get(profile.id)) {
665 continue;
666 }
Tony Mak80189cd2016-04-05 17:21:42 +0100667 if (profile.partial) {
668 continue;
669 }
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700670 result.add(profile.id);
Amith Yamasanibe465322014-04-24 13:45:17 -0700671 }
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700672 return result;
Amith Yamasanibe465322014-04-24 13:45:17 -0700673 }
674
Jessica Hummelbe81c802014-04-22 15:49:22 +0100675 @Override
Andres Moralesc5548c02015-08-05 10:23:12 -0700676 public int getCredentialOwnerProfile(int userHandle) {
677 checkManageUsersPermission("get the credential owner");
Clara Bayarria1771112015-12-18 16:29:18 +0000678 if (!mLockPatternUtils.isSeparateProfileChallengeEnabled(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700679 synchronized (mUsersLock) {
680 UserInfo profileParent = getProfileParentLU(userHandle);
Andres Moralesc5548c02015-08-05 10:23:12 -0700681 if (profileParent != null) {
682 return profileParent.id;
683 }
684 }
685 }
686
687 return userHandle;
688 }
689
690 @Override
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700691 public boolean isSameProfileGroup(int userId, int otherUserId) {
692 if (userId == otherUserId) return true;
693 checkManageUsersPermission("check if in the same profile group");
Fyodor Kupolov0fb772e2016-10-13 16:27:34 -0700694 return isSameProfileGroupNoChecks(userId, otherUserId);
695 }
696
697 private boolean isSameProfileGroupNoChecks(int userId, int otherUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700698 synchronized (mUsersLock) {
699 UserInfo userInfo = getUserInfoLU(userId);
700 if (userInfo == null || userInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
701 return false;
702 }
703 UserInfo otherUserInfo = getUserInfoLU(otherUserId);
704 if (otherUserInfo == null
705 || otherUserInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
706 return false;
707 }
708 return userInfo.profileGroupId == otherUserInfo.profileGroupId;
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700709 }
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700710 }
711
712 @Override
Jessica Hummelbe81c802014-04-22 15:49:22 +0100713 public UserInfo getProfileParent(int userHandle) {
714 checkManageUsersPermission("get the profile parent");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700715 synchronized (mUsersLock) {
716 return getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700717 }
718 }
719
Jakub Pawlowski0f1f5b72017-11-15 14:50:43 -0800720 @Override
721 public int getProfileParentId(int userHandle) {
722 checkManageUsersPermission("get the profile parent");
723 synchronized (mUsersLock) {
724 UserInfo profileParent = getProfileParentLU(userHandle);
725 if (profileParent == null) {
726 return userHandle;
727 }
728
729 return profileParent.id;
730 }
731 }
732
Fyodor Kupolov82402752015-10-28 14:54:51 -0700733 private UserInfo getProfileParentLU(int userHandle) {
734 UserInfo profile = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700735 if (profile == null) {
736 return null;
737 }
738 int parentUserId = profile.profileGroupId;
Amith Yamasani801e3422017-01-25 11:35:44 -0800739 if (parentUserId == userHandle || parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700740 return null;
741 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700742 return getUserInfoLU(parentUserId);
Jessica Hummelbe81c802014-04-22 15:49:22 +0100743 }
744 }
745
Fyodor Kupolov82402752015-10-28 14:54:51 -0700746 private static boolean isProfileOf(UserInfo user, UserInfo profile) {
Kenny Guy2a764942014-04-02 13:29:20 +0100747 return user.id == profile.id ||
748 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
749 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000750 }
751
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000752 private void broadcastProfileAvailabilityChanges(UserHandle profileHandle,
Rubin Xuf13c9802016-01-21 18:06:00 +0000753 UserHandle parentHandle, boolean inQuietMode) {
Rubin Xue95057a2016-04-01 16:49:25 +0100754 Intent intent = new Intent();
755 if (inQuietMode) {
756 intent.setAction(Intent.ACTION_MANAGED_PROFILE_UNAVAILABLE);
757 } else {
758 intent.setAction(Intent.ACTION_MANAGED_PROFILE_AVAILABLE);
759 }
Rubin Xuf13c9802016-01-21 18:06:00 +0000760 intent.putExtra(Intent.EXTRA_QUIET_MODE, inQuietMode);
761 intent.putExtra(Intent.EXTRA_USER, profileHandle);
762 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileHandle.getIdentifier());
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000763 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Rubin Xuf13c9802016-01-21 18:06:00 +0000764 mContext.sendBroadcastAsUser(intent, parentHandle);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000765 }
766
767 @Override
768 public void setQuietModeEnabled(int userHandle, boolean enableQuietMode) {
769 checkManageUsersPermission("silence profile");
770 boolean changed = false;
771 UserInfo profile, parent;
772 synchronized (mPackagesLock) {
773 synchronized (mUsersLock) {
774 profile = getUserInfoLU(userHandle);
775 parent = getProfileParentLU(userHandle);
776
777 }
778 if (profile == null || !profile.isManagedProfile()) {
779 throw new IllegalArgumentException("User " + userHandle + " is not a profile");
780 }
781 if (profile.isQuietModeEnabled() != enableQuietMode) {
782 profile.flags ^= UserInfo.FLAG_QUIET_MODE;
Amith Yamasani12747872015-12-07 14:19:49 -0800783 writeUserLP(getUserDataLU(profile.id));
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000784 changed = true;
785 }
786 }
787 if (changed) {
Rubin Xuf13c9802016-01-21 18:06:00 +0000788 long identity = Binder.clearCallingIdentity();
789 try {
790 if (enableQuietMode) {
Sudheer Shankadc589ac2016-11-10 15:30:17 -0800791 ActivityManager.getService().stopUser(userHandle, /* force */true, null);
Rubin Xuf8451b92016-04-01 15:50:58 +0100792 LocalServices.getService(ActivityManagerInternal.class)
793 .killForegroundAppsForUser(userHandle);
Rubin Xuf13c9802016-01-21 18:06:00 +0000794 } else {
Sudheer Shankadc589ac2016-11-10 15:30:17 -0800795 ActivityManager.getService().startUserInBackground(userHandle);
Rubin Xuf13c9802016-01-21 18:06:00 +0000796 }
797 } catch (RemoteException e) {
798 Slog.e(LOG_TAG, "fail to start/stop user for quiet mode", e);
799 } finally {
800 Binder.restoreCallingIdentity(identity);
801 }
802
803 broadcastProfileAvailabilityChanges(profile.getUserHandle(), parent.getUserHandle(),
804 enableQuietMode);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000805 }
806 }
807
808 @Override
809 public boolean isQuietModeEnabled(int userHandle) {
810 synchronized (mPackagesLock) {
811 UserInfo info;
812 synchronized (mUsersLock) {
813 info = getUserInfoLU(userHandle);
814 }
815 if (info == null || !info.isManagedProfile()) {
Rubin Xuf13c9802016-01-21 18:06:00 +0000816 return false;
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000817 }
818 return info.isQuietModeEnabled();
819 }
820 }
821
Kenny Guya52dc3e2014-02-11 15:33:14 +0000822 @Override
Benjamin Franzf02420c2016-04-04 18:52:21 +0100823 public boolean trySetQuietModeDisabled(int userHandle, IntentSender target) {
Ricky Waib1dd80b2016-06-07 18:00:55 +0100824 checkManageUsersPermission("silence profile");
Jeff Sharkeyce18c812016-04-27 16:00:41 -0600825 if (StorageManager.isUserKeyUnlocked(userHandle)
Ricky Wai9cc7ad62016-05-11 18:00:20 +0100826 || !mLockPatternUtils.isSecure(userHandle)) {
Benjamin Franzf02420c2016-04-04 18:52:21 +0100827 // if the user is already unlocked, no need to show a profile challenge
828 setQuietModeEnabled(userHandle, false);
829 return true;
830 }
831
832 long identity = Binder.clearCallingIdentity();
833 try {
834 // otherwise, we show a profile challenge to trigger decryption of the user
835 final KeyguardManager km = (KeyguardManager) mContext.getSystemService(
836 Context.KEYGUARD_SERVICE);
Ricky Wai7881cf82016-04-15 17:20:12 +0100837 // We should use userHandle not credentialOwnerUserId here, as even if it is unified
838 // lock, confirm screenlock page will know and show personal challenge, and unlock
839 // work profile when personal challenge is correct
Benjamin Franzf02420c2016-04-04 18:52:21 +0100840 final Intent unlockIntent = km.createConfirmDeviceCredentialIntent(null, null,
841 userHandle);
842 if (unlockIntent == null) {
843 return false;
844 }
Ricky Waib1dd80b2016-06-07 18:00:55 +0100845 final Intent callBackIntent = new Intent(
846 ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK);
Benjamin Franzf02420c2016-04-04 18:52:21 +0100847 if (target != null) {
Ricky Waib1dd80b2016-06-07 18:00:55 +0100848 callBackIntent.putExtra(Intent.EXTRA_INTENT, target);
Benjamin Franzf02420c2016-04-04 18:52:21 +0100849 }
Ricky Waib1dd80b2016-06-07 18:00:55 +0100850 callBackIntent.putExtra(Intent.EXTRA_USER_ID, userHandle);
851 callBackIntent.setPackage(mContext.getPackageName());
852 callBackIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
853 final PendingIntent pendingIntent = PendingIntent.getBroadcast(
854 mContext,
855 0,
856 callBackIntent,
857 PendingIntent.FLAG_CANCEL_CURRENT |
858 PendingIntent.FLAG_ONE_SHOT |
859 PendingIntent.FLAG_IMMUTABLE);
860 // After unlocking the challenge, it will disable quiet mode and run the original
861 // intentSender
862 unlockIntent.putExtra(Intent.EXTRA_INTENT, pendingIntent.getIntentSender());
Benjamin Franzf02420c2016-04-04 18:52:21 +0100863 unlockIntent.setFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
864 mContext.startActivity(unlockIntent);
865 } finally {
866 Binder.restoreCallingIdentity(identity);
867 }
868 return false;
869 }
870
871 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100872 public void setUserEnabled(int userId) {
873 checkManageUsersPermission("enable user");
874 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700875 UserInfo info;
876 synchronized (mUsersLock) {
877 info = getUserInfoLU(userId);
878 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100879 if (info != null && !info.isEnabled()) {
880 info.flags ^= UserInfo.FLAG_DISABLED;
Amith Yamasani12747872015-12-07 14:19:49 -0800881 writeUserLP(getUserDataLU(info.id));
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100882 }
883 }
884 }
885
Andrew Scull85a63bc2016-10-24 13:47:47 +0100886 /**
887 * Evicts a user's CE key by stopping and restarting the user.
888 *
889 * The key is evicted automatically by the user controller when the user has stopped.
890 */
891 @Override
892 public void evictCredentialEncryptionKey(@UserIdInt int userId) {
893 checkManageUsersPermission("evict CE key");
894 final IActivityManager am = ActivityManagerNative.getDefault();
895 final long identity = Binder.clearCallingIdentity();
896 try {
897 am.restartUserInBackground(userId);
898 } catch (RemoteException re) {
899 throw re.rethrowAsRuntimeException();
900 } finally {
901 Binder.restoreCallingIdentity(identity);
902 }
903 }
904
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100905 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700906 public UserInfo getUserInfo(int userId) {
Sudheer Shankaaccaa082016-06-14 16:22:57 -0700907 checkManageOrCreateUsersPermission("query user");
Tony Mak8673b282016-03-21 21:10:59 +0000908 synchronized (mUsersLock) {
Amith Yamasani6f48d6e2016-03-23 14:28:25 -0700909 return userWithName(getUserInfoLU(userId));
910 }
911 }
912
913 /**
914 * Returns a UserInfo object with the name filled in, for Owner, or the original
915 * if the name is already set.
916 */
917 private UserInfo userWithName(UserInfo orig) {
918 if (orig != null && orig.name == null && orig.id == UserHandle.USER_SYSTEM) {
919 UserInfo withName = new UserInfo(orig);
920 withName.name = getOwnerName();
921 return withName;
922 } else {
923 return orig;
Tony Mak8673b282016-03-21 21:10:59 +0000924 }
925 }
926
927 @Override
Kenny Guy02c89902016-11-15 19:36:38 +0000928 public int getManagedProfileBadge(@UserIdInt int userId) {
929 int callingUserId = UserHandle.getCallingUserId();
930 if (callingUserId != userId && !hasManageUsersPermission()) {
931 if (!isSameProfileGroupNoChecks(callingUserId, userId)) {
932 throw new SecurityException(
933 "You need MANAGE_USERS permission to: check if specified user a " +
934 "managed profile outside your profile group");
935 }
936 }
937 synchronized (mUsersLock) {
938 UserInfo userInfo = getUserInfoLU(userId);
939 return userInfo != null ? userInfo.profileBadge : 0;
940 }
941 }
942
943 @Override
Tony Mak8673b282016-03-21 21:10:59 +0000944 public boolean isManagedProfile(int userId) {
Tony Makb531d082016-03-16 14:49:52 +0000945 int callingUserId = UserHandle.getCallingUserId();
946 if (callingUserId != userId && !hasManageUsersPermission()) {
Fyodor Kupolov0fb772e2016-10-13 16:27:34 -0700947 if (!isSameProfileGroupNoChecks(callingUserId, userId)) {
Fyodor Kupolovc413f702016-10-06 17:11:14 -0700948 throw new SecurityException(
949 "You need MANAGE_USERS permission to: check if specified user a " +
950 "managed profile outside your profile group");
Tony Makb531d082016-03-16 14:49:52 +0000951 }
Tony Mak4dc008c2016-03-16 10:46:49 +0000952 }
Fyodor Kupolov82402752015-10-28 14:54:51 -0700953 synchronized (mUsersLock) {
Amith Yamasani1c41dc82016-06-28 16:13:15 -0700954 UserInfo userInfo = getUserInfoLU(userId);
Tony Mak8673b282016-03-21 21:10:59 +0000955 return userInfo != null && userInfo.isManagedProfile();
Amith Yamasani13593602012-03-22 16:16:17 -0700956 }
957 }
958
Amith Yamasani71e6c692013-03-24 17:39:28 -0700959 @Override
Fyodor Kupolovc413f702016-10-06 17:11:14 -0700960 public boolean isUserUnlockingOrUnlocked(int userId) {
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -0800961 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isUserUnlockingOrUnlocked");
Fyodor Kupolovc413f702016-10-06 17:11:14 -0700962 return mLocalService.isUserUnlockingOrUnlocked(userId);
963 }
964
965 @Override
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -0800966 public boolean isUserUnlocked(int userId) {
967 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isUserUnlocked");
Fyodor Kupolov0468ee92017-05-25 17:06:17 -0700968 return mLocalService.isUserUnlocked(userId);
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -0800969 }
970
971 @Override
972 public boolean isUserRunning(int userId) {
973 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isUserRunning");
974 return mLocalService.isUserRunning(userId);
975 }
976
977 private void checkManageOrInteractPermIfCallerInOtherProfileGroup(int userId, String name) {
978 int callingUserId = UserHandle.getCallingUserId();
979 if (callingUserId == userId || isSameProfileGroupNoChecks(callingUserId, userId) ||
980 hasManageUsersPermission()) {
981 return;
982 }
983 if (ActivityManager.checkComponentPermission(Manifest.permission.INTERACT_ACROSS_USERS,
984 Binder.getCallingUid(), -1, true) != PackageManager.PERMISSION_GRANTED) {
985 throw new SecurityException("You need INTERACT_ACROSS_USERS or MANAGE_USERS permission "
986 + "to: check " + name);
987 }
988 }
989
990 @Override
Amith Yamasani1c41dc82016-06-28 16:13:15 -0700991 public boolean isDemoUser(int userId) {
992 int callingUserId = UserHandle.getCallingUserId();
993 if (callingUserId != userId && !hasManageUsersPermission()) {
994 throw new SecurityException("You need MANAGE_USERS permission to query if u=" + userId
995 + " is a demo user");
996 }
997 synchronized (mUsersLock) {
998 UserInfo userInfo = getUserInfoLU(userId);
999 return userInfo != null && userInfo.isDemo();
1000 }
1001 }
1002
1003 @Override
Amith Yamasani71e6c692013-03-24 17:39:28 -07001004 public boolean isRestricted() {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001005 synchronized (mUsersLock) {
1006 return getUserInfoLU(UserHandle.getCallingUserId()).isRestricted();
Amith Yamasani71e6c692013-03-24 17:39:28 -07001007 }
1008 }
1009
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001010 @Override
1011 public boolean canHaveRestrictedProfile(int userId) {
1012 checkManageUsersPermission("canHaveRestrictedProfile");
Fyodor Kupolov82402752015-10-28 14:54:51 -07001013 synchronized (mUsersLock) {
1014 final UserInfo userInfo = getUserInfoLU(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001015 if (userInfo == null || !userInfo.canHaveProfile()) {
1016 return false;
1017 }
1018 if (!userInfo.isAdmin()) {
1019 return false;
1020 }
Makoto Onukie7927da2015-11-25 10:05:17 -08001021 // restricted profile can be created if there is no DO set and the admin user has no PO;
1022 return !mIsDeviceManaged && !mIsUserManaged.get(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001023 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001024 }
1025
Fyodor Kupolovca177562017-11-09 17:43:01 -08001026 @Override
1027 public boolean hasRestrictedProfiles() {
1028 checkManageUsersPermission("hasRestrictedProfiles");
1029 final int callingUserId = UserHandle.getCallingUserId();
1030 synchronized (mUsersLock) {
1031 final int userSize = mUsers.size();
1032 for (int i = 0; i < userSize; i++) {
1033 UserInfo profile = mUsers.valueAt(i).info;
1034 if (callingUserId != profile.id
1035 && profile.restrictedProfileParentId == callingUserId) {
1036 return true;
1037 }
1038 }
1039 return false;
1040 }
1041 }
1042
Amith Yamasani195263742012-08-21 15:40:12 -07001043 /*
1044 * Should be locked on mUsers before calling this.
1045 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001046 private UserInfo getUserInfoLU(int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -08001047 final UserData userData = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -07001048 // If it is partial and not in the process of being removed, return as unknown user.
Amith Yamasani12747872015-12-07 14:19:49 -08001049 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001050 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
1051 return null;
1052 }
Amith Yamasani12747872015-12-07 14:19:49 -08001053 return userData != null ? userData.info : null;
1054 }
1055
1056 private UserData getUserDataLU(int userId) {
1057 final UserData userData = mUsers.get(userId);
1058 // If it is partial and not in the process of being removed, return as unknown user.
1059 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
1060 return null;
1061 }
1062 return userData;
Amith Yamasani195263742012-08-21 15:40:12 -07001063 }
1064
Fyodor Kupolov82402752015-10-28 14:54:51 -07001065 /**
1066 * Obtains {@link #mUsersLock} and return UserInfo from mUsers.
1067 * <p>No permissions checking or any addition checks are made</p>
1068 */
1069 private UserInfo getUserInfoNoChecks(int userId) {
1070 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001071 final UserData userData = mUsers.get(userId);
1072 return userData != null ? userData.info : null;
1073 }
1074 }
1075
1076 /**
1077 * Obtains {@link #mUsersLock} and return UserData from mUsers.
1078 * <p>No permissions checking or any addition checks are made</p>
1079 */
1080 private UserData getUserDataNoChecks(int userId) {
1081 synchronized (mUsersLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001082 return mUsers.get(userId);
1083 }
1084 }
1085
Amith Yamasani236b2b52015-08-18 14:32:14 -07001086 /** Called by PackageManagerService */
Amith Yamasani13593602012-03-22 16:16:17 -07001087 public boolean exists(int userId) {
Todd Kennedy0eb97382017-10-03 16:57:22 -07001088 return mLocalService.exists(userId);
Amith Yamasani13593602012-03-22 16:16:17 -07001089 }
1090
Amith Yamasani258848d2012-08-10 17:06:33 -07001091 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001092 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001093 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001094 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -07001095 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001096 UserData userData = getUserDataNoChecks(userId);
1097 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001098 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
1099 return;
1100 }
Amith Yamasani12747872015-12-07 14:19:49 -08001101 if (name != null && !name.equals(userData.info.name)) {
1102 userData.info.name = name;
1103 writeUserLP(userData);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001104 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -07001105 }
1106 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001107 if (changed) {
1108 sendUserInfoChangedBroadcast(userId);
1109 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001110 }
1111
Amith Yamasani258848d2012-08-10 17:06:33 -07001112 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001113 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001114 checkManageUsersPermission("update users");
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01001115 if (hasUserRestriction(UserManager.DISALLOW_SET_USER_ICON, userId)) {
1116 Log.w(LOG_TAG, "Cannot set user icon. DISALLOW_SET_USER_ICON is enabled.");
1117 return;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001118 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01001119 mLocalService.setUserIcon(userId, bitmap);
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001120 }
1121
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01001122
1123
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001124 private void sendUserInfoChangedBroadcast(int userId) {
1125 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
1126 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
1127 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -07001128 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001129 }
1130
Amith Yamasani258848d2012-08-10 17:06:33 -07001131 @Override
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001132 public ParcelFileDescriptor getUserIcon(int targetUserId) {
Adrian Roos1bdff912015-02-17 15:51:35 +01001133 String iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001134 synchronized (mPackagesLock) {
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001135 UserInfo targetUserInfo = getUserInfoNoChecks(targetUserId);
1136 if (targetUserInfo == null || targetUserInfo.partial) {
1137 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + targetUserId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001138 return null;
1139 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001140
1141 final int callingUserId = UserHandle.getCallingUserId();
1142 final int callingGroupId = getUserInfoNoChecks(callingUserId).profileGroupId;
1143 final int targetGroupId = targetUserInfo.profileGroupId;
1144 final boolean sameGroup = (callingGroupId != UserInfo.NO_PROFILE_GROUP_ID
1145 && callingGroupId == targetGroupId);
1146 if ((callingUserId != targetUserId) && !sameGroup) {
Nicolas Prevot88cc3462014-05-14 14:51:48 +01001147 checkManageUsersPermission("get the icon of a user who is not related");
1148 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001149
1150 if (targetUserInfo.iconPath == null) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001151 return null;
1152 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001153 iconPath = targetUserInfo.iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001154 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001155
1156 try {
1157 return ParcelFileDescriptor.open(
1158 new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
1159 } catch (FileNotFoundException e) {
1160 Log.e(LOG_TAG, "Couldn't find icon file", e);
1161 }
1162 return null;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001163 }
1164
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001165 public void makeInitialized(int userId) {
1166 checkManageUsersPermission("makeInitialized");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001167 boolean scheduleWriteUser = false;
Amith Yamasani12747872015-12-07 14:19:49 -08001168 UserData userData;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001169 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001170 userData = mUsers.get(userId);
1171 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001172 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001173 return;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001174 }
Amith Yamasani12747872015-12-07 14:19:49 -08001175 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1176 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001177 scheduleWriteUser = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001178 }
1179 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001180 if (scheduleWriteUser) {
Amith Yamasani12747872015-12-07 14:19:49 -08001181 scheduleWriteUser(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001182 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001183 }
1184
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001185 /**
1186 * If default guest restrictions haven't been initialized yet, add the basic
1187 * restrictions.
1188 */
1189 private void initDefaultGuestRestrictions() {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001190 synchronized (mGuestRestrictions) {
1191 if (mGuestRestrictions.isEmpty()) {
Samuel Tand9453b82016-03-14 15:57:02 -07001192 mGuestRestrictions.putBoolean(UserManager.DISALLOW_CONFIG_WIFI, true);
Fyodor Kupolove04462c2015-11-30 15:02:53 -08001193 mGuestRestrictions.putBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, true);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001194 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
1195 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
1196 }
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001197 }
1198 }
1199
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001200 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301201 public Bundle getDefaultGuestRestrictions() {
1202 checkManageUsersPermission("getDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001203 synchronized (mGuestRestrictions) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301204 return new Bundle(mGuestRestrictions);
1205 }
1206 }
1207
1208 @Override
1209 public void setDefaultGuestRestrictions(Bundle restrictions) {
1210 checkManageUsersPermission("setDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001211 synchronized (mGuestRestrictions) {
1212 mGuestRestrictions.clear();
1213 mGuestRestrictions.putAll(restrictions);
1214 }
1215 synchronized (mPackagesLock) {
1216 writeUserListLP();
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301217 }
1218 }
1219
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001220 /**
Pavel Grafov6a40f092016-10-25 15:46:51 +01001221 * See {@link UserManagerInternal#setDevicePolicyUserRestrictions}
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001222 */
Pavel Grafov6a40f092016-10-25 15:46:51 +01001223 private void setDevicePolicyUserRestrictionsInner(int userId, @Nullable Bundle restrictions,
1224 boolean isDeviceOwner, int cameraRestrictionScope) {
1225 final Bundle global = new Bundle();
1226 final Bundle local = new Bundle();
1227
1228 // Sort restrictions into local and global ensuring they don't overlap.
1229 UserRestrictionsUtils.sortToGlobalAndLocal(restrictions, isDeviceOwner,
1230 cameraRestrictionScope, global, local);
1231
1232 boolean globalChanged, localChanged;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001233 synchronized (mRestrictionsLock) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001234 // Update global and local restrictions if they were changed.
1235 globalChanged = updateRestrictionsIfNeededLR(
1236 userId, global, mDevicePolicyGlobalUserRestrictions);
1237 localChanged = updateRestrictionsIfNeededLR(
1238 userId, local, mDevicePolicyLocalUserRestrictions);
1239
1240 if (isDeviceOwner) {
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001241 // Remember the global restriction owner userId to be able to make a distinction
1242 // in getUserRestrictionSource on who set local policies.
Pavel Grafov6a40f092016-10-25 15:46:51 +01001243 mDeviceOwnerUserId = userId;
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001244 } else {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001245 if (mDeviceOwnerUserId == userId) {
Zoltan Szatmary-Ban8a5536d2016-05-27 17:56:44 +01001246 // When profile owner sets restrictions it passes null global bundle and we
1247 // reset global restriction owner userId.
1248 // This means this user used to have DO, but now the DO is gone and the user
1249 // instead has PO.
Pavel Grafov6a40f092016-10-25 15:46:51 +01001250 mDeviceOwnerUserId = UserHandle.USER_NULL;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001251 }
1252 }
1253 }
1254 if (DBG) {
1255 Log.d(LOG_TAG, "setDevicePolicyUserRestrictions: userId=" + userId
1256 + " global=" + global + (globalChanged ? " (changed)" : "")
1257 + " local=" + local + (localChanged ? " (changed)" : "")
1258 );
1259 }
1260 // Don't call them within the mRestrictionsLock.
1261 synchronized (mPackagesLock) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001262 if (localChanged || globalChanged) {
Amith Yamasani12747872015-12-07 14:19:49 -08001263 writeUserLP(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001264 }
1265 }
1266
1267 synchronized (mRestrictionsLock) {
1268 if (globalChanged) {
1269 applyUserRestrictionsForAllUsersLR();
1270 } else if (localChanged) {
1271 applyUserRestrictionsLR(userId);
1272 }
1273 }
1274 }
1275
Pavel Grafov6a40f092016-10-25 15:46:51 +01001276 /**
1277 * Updates restriction bundle for a given user in a given restriction array. If new bundle is
1278 * empty, record is removed from the array.
1279 * @return whether restrictions bundle is different from the old one.
1280 */
1281 private boolean updateRestrictionsIfNeededLR(int userId, @Nullable Bundle restrictions,
1282 SparseArray<Bundle> restrictionsArray) {
1283 final boolean changed =
1284 !UserRestrictionsUtils.areEqual(restrictionsArray.get(userId), restrictions);
1285 if (changed) {
1286 if (!UserRestrictionsUtils.isEmpty(restrictions)) {
1287 restrictionsArray.put(userId, restrictions);
1288 } else {
1289 restrictionsArray.delete(userId);
1290 }
1291 }
1292 return changed;
1293 }
1294
Makoto Onuki068c54a2015-10-13 14:34:03 -07001295 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001296 private Bundle computeEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001297 final Bundle baseRestrictions =
1298 UserRestrictionsUtils.nonNull(mBaseUserRestrictions.get(userId));
Pavel Grafov6a40f092016-10-25 15:46:51 +01001299 final Bundle global = UserRestrictionsUtils.mergeAll(mDevicePolicyGlobalUserRestrictions);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001300 final Bundle local = mDevicePolicyLocalUserRestrictions.get(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001301
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001302 if (UserRestrictionsUtils.isEmpty(global) && UserRestrictionsUtils.isEmpty(local)) {
1303 // Common case first.
1304 return baseRestrictions;
Makoto Onuki068c54a2015-10-13 14:34:03 -07001305 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001306 final Bundle effective = UserRestrictionsUtils.clone(baseRestrictions);
1307 UserRestrictionsUtils.merge(effective, global);
1308 UserRestrictionsUtils.merge(effective, local);
1309
Makoto Onuki068c54a2015-10-13 14:34:03 -07001310 return effective;
1311 }
1312
1313 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001314 private void invalidateEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki068c54a2015-10-13 14:34:03 -07001315 if (DBG) {
1316 Log.d(LOG_TAG, "invalidateEffectiveUserRestrictions userId=" + userId);
1317 }
1318 mCachedEffectiveUserRestrictions.remove(userId);
1319 }
1320
1321 private Bundle getEffectiveUserRestrictions(int userId) {
1322 synchronized (mRestrictionsLock) {
1323 Bundle restrictions = mCachedEffectiveUserRestrictions.get(userId);
1324 if (restrictions == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001325 restrictions = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001326 mCachedEffectiveUserRestrictions.put(userId, restrictions);
1327 }
1328 return restrictions;
Amith Yamasani8cd28b52014-06-08 17:54:27 -07001329 }
1330 }
1331
Makoto Onuki068c54a2015-10-13 14:34:03 -07001332 /** @return a specific user restriction that's in effect currently. */
1333 @Override
1334 public boolean hasUserRestriction(String restrictionKey, int userId) {
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001335 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1336 return false;
1337 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001338 Bundle restrictions = getEffectiveUserRestrictions(userId);
1339 return restrictions != null && restrictions.getBoolean(restrictionKey);
1340 }
1341
1342 /**
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001343 * @hide
1344 *
1345 * Returns who set a user restriction on a user.
1346 * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
1347 * @param restrictionKey the string key representing the restriction
1348 * @param userId the id of the user for whom to retrieve the restrictions.
1349 * @return The source of user restriction. Any combination of
1350 * {@link UserManager#RESTRICTION_NOT_SET},
1351 * {@link UserManager#RESTRICTION_SOURCE_SYSTEM},
1352 * {@link UserManager#RESTRICTION_SOURCE_DEVICE_OWNER}
1353 * and {@link UserManager#RESTRICTION_SOURCE_PROFILE_OWNER}
1354 */
1355 @Override
1356 public int getUserRestrictionSource(String restrictionKey, int userId) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001357 List<EnforcingUser> enforcingUsers = getUserRestrictionSources(restrictionKey, userId);
1358 // Get "bitwise or" of restriction sources for all enforcing users.
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001359 int result = UserManager.RESTRICTION_NOT_SET;
Pavel Grafov6a40f092016-10-25 15:46:51 +01001360 for (int i = enforcingUsers.size() - 1; i >= 0; i--) {
1361 result |= enforcingUsers.get(i).getUserRestrictionSource();
1362 }
1363 return result;
1364 }
1365
1366 @Override
1367 public List<EnforcingUser> getUserRestrictionSources(
1368 String restrictionKey, @UserIdInt int userId) {
1369 checkManageUsersPermission("getUserRestrictionSource");
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001370
1371 // Shortcut for the most common case
1372 if (!hasUserRestriction(restrictionKey, userId)) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001373 return Collections.emptyList();
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001374 }
1375
Pavel Grafov6a40f092016-10-25 15:46:51 +01001376 final List<EnforcingUser> result = new ArrayList<>();
1377
1378 // Check if it is base restriction.
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001379 if (hasBaseUserRestriction(restrictionKey, userId)) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001380 result.add(new EnforcingUser(
1381 UserHandle.USER_NULL, UserManager.RESTRICTION_SOURCE_SYSTEM));
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001382 }
1383
Pavel Grafov6a40f092016-10-25 15:46:51 +01001384 synchronized (mRestrictionsLock) {
1385 // Check if it is set by profile owner.
1386 Bundle profileOwnerRestrictions = mDevicePolicyLocalUserRestrictions.get(userId);
1387 if (UserRestrictionsUtils.contains(profileOwnerRestrictions, restrictionKey)) {
1388 result.add(getEnforcingUserLocked(userId));
1389 }
1390
1391 // Iterate over all users who enforce global restrictions.
1392 for (int i = mDevicePolicyGlobalUserRestrictions.size() - 1; i >= 0; i--) {
1393 Bundle globalRestrictions = mDevicePolicyGlobalUserRestrictions.valueAt(i);
1394 int profileUserId = mDevicePolicyGlobalUserRestrictions.keyAt(i);
1395 if (UserRestrictionsUtils.contains(globalRestrictions, restrictionKey)) {
1396 result.add(getEnforcingUserLocked(profileUserId));
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001397 }
1398 }
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001399 }
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001400 return result;
1401 }
1402
Pavel Grafov6a40f092016-10-25 15:46:51 +01001403 private EnforcingUser getEnforcingUserLocked(@UserIdInt int userId) {
1404 int source = mDeviceOwnerUserId == userId ? UserManager.RESTRICTION_SOURCE_DEVICE_OWNER
1405 : UserManager.RESTRICTION_SOURCE_PROFILE_OWNER;
1406 return new EnforcingUser(userId, source);
1407 }
1408
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001409 /**
Makoto Onuki068c54a2015-10-13 14:34:03 -07001410 * @return UserRestrictions that are in effect currently. This always returns a new
1411 * {@link Bundle}.
1412 */
Amith Yamasani8cd28b52014-06-08 17:54:27 -07001413 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001414 public Bundle getUserRestrictions(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001415 return UserRestrictionsUtils.clone(getEffectiveUserRestrictions(userId));
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001416 }
1417
1418 @Override
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +00001419 public boolean hasBaseUserRestriction(String restrictionKey, int userId) {
1420 checkManageUsersPermission("hasBaseUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001421 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1422 return false;
1423 }
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +00001424 synchronized (mRestrictionsLock) {
1425 Bundle bundle = mBaseUserRestrictions.get(userId);
1426 return (bundle != null && bundle.getBoolean(restrictionKey, false));
1427 }
1428 }
1429
1430 @Override
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001431 public void setUserRestriction(String key, boolean value, int userId) {
Fyodor Kupolovd4b26042015-07-27 14:30:59 -07001432 checkManageUsersPermission("setUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001433 if (!UserRestrictionsUtils.isValidRestriction(key)) {
1434 return;
1435 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001436 synchronized (mRestrictionsLock) {
1437 // Note we can't modify Bundles stored in mBaseUserRestrictions directly, so create
1438 // a copy.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001439 final Bundle newRestrictions = UserRestrictionsUtils.clone(
1440 mBaseUserRestrictions.get(userId));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001441 newRestrictions.putBoolean(key, value);
1442
Fyodor Kupolov82402752015-10-28 14:54:51 -07001443 updateUserRestrictionsInternalLR(newRestrictions, userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001444 }
1445 }
1446
Makoto Onuki068c54a2015-10-13 14:34:03 -07001447 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001448 * Optionally updating user restrictions, calculate the effective user restrictions and also
1449 * propagate to other services and system settings.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001450 *
Pavel Grafov6a40f092016-10-25 15:46:51 +01001451 * @param newBaseRestrictions User restrictions to set.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001452 * If null, will not update user restrictions and only does the propagation.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001453 * @param userId target user ID.
1454 */
1455 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001456 private void updateUserRestrictionsInternalLR(
Pavel Grafov6a40f092016-10-25 15:46:51 +01001457 @Nullable Bundle newBaseRestrictions, int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001458 final Bundle prevAppliedRestrictions = UserRestrictionsUtils.nonNull(
1459 mAppliedUserRestrictions.get(userId));
1460
1461 // Update base restrictions.
Pavel Grafov6a40f092016-10-25 15:46:51 +01001462 if (newBaseRestrictions != null) {
1463 // If newBaseRestrictions == the current one, it's probably a bug.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001464 final Bundle prevBaseRestrictions = mBaseUserRestrictions.get(userId);
1465
Pavel Grafov6a40f092016-10-25 15:46:51 +01001466 Preconditions.checkState(prevBaseRestrictions != newBaseRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001467 Preconditions.checkState(mCachedEffectiveUserRestrictions.get(userId)
Pavel Grafov6a40f092016-10-25 15:46:51 +01001468 != newBaseRestrictions);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001469
Pavel Grafov6a40f092016-10-25 15:46:51 +01001470 if (updateRestrictionsIfNeededLR(userId, newBaseRestrictions, mBaseUserRestrictions)) {
Amith Yamasani12747872015-12-07 14:19:49 -08001471 scheduleWriteUser(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001472 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001473 }
1474
Fyodor Kupolov82402752015-10-28 14:54:51 -07001475 final Bundle effective = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001476
Makoto Onuki759a7632015-10-28 16:43:10 -07001477 mCachedEffectiveUserRestrictions.put(userId, effective);
1478
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001479 // Apply the new restrictions.
Makoto Onuki4f160732015-10-27 17:15:38 -07001480 if (DBG) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001481 debug("Applying user restrictions: userId=" + userId
1482 + " new=" + effective + " prev=" + prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001483 }
1484
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001485 if (mAppOpsService != null) { // We skip it until system-ready.
Fyodor Kupolovec30ca32016-06-16 15:09:29 -07001486 mHandler.post(new Runnable() {
1487 @Override
1488 public void run() {
1489 try {
1490 mAppOpsService.setUserRestrictions(effective, mUserRestriconToken, userId);
1491 } catch (RemoteException e) {
1492 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
1493 }
1494 }
1495 });
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001496 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001497
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001498 propagateUserRestrictionsLR(userId, effective, prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001499
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001500 mAppliedUserRestrictions.put(userId, new Bundle(effective));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001501 }
1502
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001503 private void propagateUserRestrictionsLR(final int userId,
Makoto Onukid45a4a22015-11-02 17:17:38 -08001504 Bundle newRestrictions, Bundle prevRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001505 // Note this method doesn't touch any state, meaning it doesn't require mRestrictionsLock
1506 // actually, but we still need some kind of synchronization otherwise we might end up
1507 // calling listeners out-of-order, thus "LR".
1508
1509 if (UserRestrictionsUtils.areEqual(newRestrictions, prevRestrictions)) {
1510 return;
1511 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08001512
1513 final Bundle newRestrictionsFinal = new Bundle(newRestrictions);
1514 final Bundle prevRestrictionsFinal = new Bundle(prevRestrictions);
1515
1516 mHandler.post(new Runnable() {
1517 @Override
1518 public void run() {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07001519 UserRestrictionsUtils.applyUserRestrictions(
1520 mContext, userId, newRestrictionsFinal, prevRestrictionsFinal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001521
Makoto Onukid45a4a22015-11-02 17:17:38 -08001522 final UserRestrictionsListener[] listeners;
1523 synchronized (mUserRestrictionsListeners) {
1524 listeners = new UserRestrictionsListener[mUserRestrictionsListeners.size()];
1525 mUserRestrictionsListeners.toArray(listeners);
1526 }
1527 for (int i = 0; i < listeners.length; i++) {
1528 listeners[i].onUserRestrictionsChanged(userId,
1529 newRestrictionsFinal, prevRestrictionsFinal);
1530 }
Makoto Onukie72f81b2017-03-16 14:08:19 -07001531
1532 final Intent broadcast = new Intent(UserManager.ACTION_USER_RESTRICTIONS_CHANGED)
1533 .setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
1534 mContext.sendBroadcastAsUser(broadcast, UserHandle.of(userId));
Makoto Onukid45a4a22015-11-02 17:17:38 -08001535 }
1536 });
1537 }
1538
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001539 // Package private for the inner class.
1540 void applyUserRestrictionsLR(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001541 updateUserRestrictionsInternalLR(null, userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001542 }
1543
1544 @GuardedBy("mRestrictionsLock")
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001545 // Package private for the inner class.
1546 void applyUserRestrictionsForAllUsersLR() {
1547 if (DBG) {
1548 debug("applyUserRestrictionsForAllUsersLR");
1549 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001550 // First, invalidate all cached values.
Makoto Onuki4f160732015-10-27 17:15:38 -07001551 mCachedEffectiveUserRestrictions.clear();
1552
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001553 // We don't want to call into ActivityManagerService while taking a lock, so we'll call
Makoto Onuki068c54a2015-10-13 14:34:03 -07001554 // it on a handler.
1555 final Runnable r = new Runnable() {
1556 @Override
1557 public void run() {
1558 // Then get the list of running users.
1559 final int[] runningUsers;
1560 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001561 runningUsers = ActivityManager.getService().getRunningUserIds();
Makoto Onuki068c54a2015-10-13 14:34:03 -07001562 } catch (RemoteException e) {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001563 Log.w(LOG_TAG, "Unable to access ActivityManagerService");
Makoto Onuki068c54a2015-10-13 14:34:03 -07001564 return;
1565 }
1566 // Then re-calculate the effective restrictions and apply, only for running users.
1567 // It's okay if a new user has started after the getRunningUserIds() call,
1568 // because we'll do the same thing (re-calculate the restrictions and apply)
1569 // when we start a user.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001570 synchronized (mRestrictionsLock) {
1571 for (int i = 0; i < runningUsers.length; i++) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001572 applyUserRestrictionsLR(runningUsers[i]);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001573 }
1574 }
1575 }
1576 };
1577 mHandler.post(r);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001578 }
1579
Amith Yamasani258848d2012-08-10 17:06:33 -07001580 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001581 * Check if we've hit the limit of how many users can be created.
1582 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001583 private boolean isUserLimitReached() {
1584 int count;
1585 synchronized (mUsersLock) {
1586 count = getAliveUsersExcludingGuestsCountLU();
1587 }
1588 return count >= UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001589 }
1590
1591 @Override
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001592 public boolean canAddMoreManagedProfiles(int userId, boolean allowedToRemoveOne) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001593 checkManageUsersPermission("check if more managed profiles can be added.");
1594 if (ActivityManager.isLowRamDeviceStatic()) {
1595 return false;
1596 }
Fyodor Kupolovb6157992015-06-05 15:32:28 -07001597 if (!mContext.getPackageManager().hasSystemFeature(
1598 PackageManager.FEATURE_MANAGED_USERS)) {
1599 return false;
1600 }
Nicolas Prevotb8186812015-08-06 15:00:03 +01001601 // Limit number of managed profiles that can be created
Benjamin Franzc8776152017-01-06 14:16:41 +00001602 final int managedProfilesCount = getProfiles(userId, false).size() - 1;
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001603 final int profilesRemovedCount = managedProfilesCount > 0 && allowedToRemoveOne ? 1 : 0;
Kenny Guy02c89902016-11-15 19:36:38 +00001604 if (managedProfilesCount - profilesRemovedCount >= getMaxManagedProfiles()) {
Nicolas Prevotb8186812015-08-06 15:00:03 +01001605 return false;
1606 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001607 synchronized(mUsersLock) {
1608 UserInfo userInfo = getUserInfoLU(userId);
yuanhao47f9f7c2017-01-18 09:54:45 +08001609 if (userInfo == null || !userInfo.canHaveProfile()) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001610 return false;
1611 }
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001612 int usersCountAfterRemoving = getAliveUsersExcludingGuestsCountLU()
1613 - profilesRemovedCount;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001614 // We allow creating a managed profile in the special case where there is only one user.
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001615 return usersCountAfterRemoving == 1
1616 || usersCountAfterRemoving < UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001617 }
1618 }
1619
Fyodor Kupolov82402752015-10-28 14:54:51 -07001620 private int getAliveUsersExcludingGuestsCountLU() {
Amith Yamasanif584f012014-05-19 17:57:25 -07001621 int aliveUserCount = 0;
1622 final int totalUserCount = mUsers.size();
1623 // Skip over users being removed
1624 for (int i = 0; i < totalUserCount; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001625 UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov6e99d3f2016-11-01 17:18:41 -07001626 if (!mRemovingUserIds.get(user.id) && !user.isGuest()) {
Amith Yamasanif584f012014-05-19 17:57:25 -07001627 aliveUserCount++;
1628 }
1629 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001630 return aliveUserCount;
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001631 }
1632
1633 /**
Amith Yamasani195263742012-08-21 15:40:12 -07001634 * Enforces that only the system UID or root's UID or apps that have the
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001635 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} and
1636 * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL INTERACT_ACROSS_USERS_FULL}
1637 * permissions can make certain calls to the UserManager.
1638 *
1639 * @param message used as message if SecurityException is thrown
1640 * @throws SecurityException if the caller does not have enough privilege.
1641 */
1642 private static final void checkManageUserAndAcrossUsersFullPermission(String message) {
1643 final int uid = Binder.getCallingUid();
1644 if (uid != Process.SYSTEM_UID && uid != 0
1645 && ActivityManager.checkComponentPermission(
1646 Manifest.permission.MANAGE_USERS,
1647 uid, -1, true) != PackageManager.PERMISSION_GRANTED
1648 && ActivityManager.checkComponentPermission(
1649 Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1650 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
1651 throw new SecurityException(
1652 "You need MANAGE_USERS and INTERACT_ACROSS_USERS_FULL permission to: "
1653 + message);
1654 }
1655 }
1656
1657 /**
1658 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001659 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -07001660 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -07001661 *
1662 * @param message used as message if SecurityException is thrown
1663 * @throws SecurityException if the caller is not system or root
Tony Mak4dc008c2016-03-16 10:46:49 +00001664 * @see #hasManageUsersPermission()
Amith Yamasani258848d2012-08-10 17:06:33 -07001665 */
Amith Yamasanibe465322014-04-24 13:45:17 -07001666 private static final void checkManageUsersPermission(String message) {
Tony Mak4dc008c2016-03-16 10:46:49 +00001667 if (!hasManageUsersPermission()) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001668 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
1669 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -04001670 }
1671
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001672 /**
Sudheer Shankaf5cea032016-06-08 17:13:24 -07001673 * Enforces that only the system UID or root's UID or apps that have the
1674 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or
1675 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS}
1676 * can make certain calls to the UserManager.
1677 *
1678 * @param message used as message if SecurityException is thrown
1679 * @throws SecurityException if the caller is not system or root
1680 * @see #hasManageOrCreateUsersPermission()
1681 */
1682 private static final void checkManageOrCreateUsersPermission(String message) {
1683 if (!hasManageOrCreateUsersPermission()) {
1684 throw new SecurityException(
1685 "You either need MANAGE_USERS or CREATE_USERS permission to: " + message);
1686 }
1687 }
1688
1689 /**
1690 * Similar to {@link #checkManageOrCreateUsersPermission(String)} but when the caller is tries
1691 * to create user/profiles other than what is allowed for
1692 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS} permission, then it will only
1693 * allow callers with {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} permission.
1694 */
1695 private static final void checkManageOrCreateUsersPermission(int creationFlags) {
1696 if ((creationFlags & ~ALLOWED_FLAGS_FOR_CREATE_USERS_PERMISSION) == 0) {
1697 if (!hasManageOrCreateUsersPermission()) {
1698 throw new SecurityException("You either need MANAGE_USERS or CREATE_USERS "
1699 + "permission to create an user with flags: " + creationFlags);
1700 }
1701 } else if (!hasManageUsersPermission()) {
1702 throw new SecurityException("You need MANAGE_USERS permission to create an user "
1703 + " with flags: " + creationFlags);
1704 }
1705 }
1706
1707 /**
Tony Mak4dc008c2016-03-16 10:46:49 +00001708 * @return whether the calling UID is system UID or root's UID or the calling app has the
1709 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}.
1710 */
1711 private static final boolean hasManageUsersPermission() {
1712 final int callingUid = Binder.getCallingUid();
1713 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
1714 || callingUid == Process.ROOT_UID
1715 || ActivityManager.checkComponentPermission(
1716 android.Manifest.permission.MANAGE_USERS,
1717 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED;
1718 }
1719
1720 /**
Sudheer Shankaf5cea032016-06-08 17:13:24 -07001721 * @return whether the calling UID is system UID or root's UID or the calling app has the
1722 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or
1723 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS}.
1724 */
1725 private static final boolean hasManageOrCreateUsersPermission() {
1726 final int callingUid = Binder.getCallingUid();
1727 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
1728 || callingUid == Process.ROOT_UID
1729 || ActivityManager.checkComponentPermission(
1730 android.Manifest.permission.MANAGE_USERS,
1731 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED
1732 || ActivityManager.checkComponentPermission(
1733 android.Manifest.permission.CREATE_USERS,
1734 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED;
1735 }
1736
1737 /**
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001738 * Enforces that only the system UID or root's UID (on any user) can make certain calls to the
1739 * UserManager.
1740 *
1741 * @param message used as message if SecurityException is thrown
1742 * @throws SecurityException if the caller is not system or root
1743 */
1744 private static void checkSystemOrRoot(String message) {
1745 final int uid = Binder.getCallingUid();
1746 if (!UserHandle.isSameApp(uid, Process.SYSTEM_UID) && uid != Process.ROOT_UID) {
1747 throw new SecurityException("Only system may: " + message);
1748 }
1749 }
1750
Fyodor Kupolov82402752015-10-28 14:54:51 -07001751 private void writeBitmapLP(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001752 try {
1753 File dir = new File(mUsersDir, Integer.toString(info.id));
1754 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +01001755 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001756 if (!dir.exists()) {
1757 dir.mkdir();
1758 FileUtils.setPermissions(
1759 dir.getPath(),
1760 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
1761 -1, -1);
1762 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001763 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +01001764 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001765 && tmp.renameTo(file) && SELinux.restorecon(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -07001766 info.iconPath = file.getAbsolutePath();
1767 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001768 try {
1769 os.close();
1770 } catch (IOException ioe) {
1771 // What the ... !
1772 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001773 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001774 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001775 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001776 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001777 }
1778
Amith Yamasani0b285492011-04-14 17:35:23 -07001779 /**
1780 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
1781 * cache it elsewhere.
1782 * @return the array of user ids.
1783 */
Dianne Hackborn1676c852012-09-10 14:52:30 -07001784 public int[] getUserIds() {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001785 synchronized (mUsersLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001786 return mUserIds;
1787 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001788 }
1789
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001790 private void readUserListLP() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001791 if (!mUserListFile.exists()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001792 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001793 return;
1794 }
1795 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001796 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001797 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001798 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001799 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001800 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001801 int type;
1802 while ((type = parser.next()) != XmlPullParser.START_TAG
1803 && type != XmlPullParser.END_DOCUMENT) {
Amith Yamasani12747872015-12-07 14:19:49 -08001804 // Skip
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001805 }
1806
1807 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001808 Slog.e(LOG_TAG, "Unable to read user list");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001809 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001810 return;
1811 }
1812
Amith Yamasani2a003292012-08-14 18:25:45 -07001813 mNextSerialNumber = -1;
1814 if (parser.getName().equals(TAG_USERS)) {
1815 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
1816 if (lastSerialNumber != null) {
1817 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
1818 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001819 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
1820 if (versionNumber != null) {
1821 mUserVersion = Integer.parseInt(versionNumber);
1822 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001823 }
1824
Pavel Grafov6a40f092016-10-25 15:46:51 +01001825 // Pre-O global user restriction were stored as a single bundle (as opposed to per-user
1826 // currently), take care of it in case of upgrade.
1827 Bundle oldDevicePolicyGlobalUserRestrictions = null;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001828
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001829 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301830 if (type == XmlPullParser.START_TAG) {
1831 final String name = parser.getName();
1832 if (name.equals(TAG_USER)) {
1833 String id = parser.getAttributeValue(null, ATTR_ID);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001834
Amith Yamasani12747872015-12-07 14:19:49 -08001835 UserData userData = readUserLP(Integer.parseInt(id));
1836
1837 if (userData != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001838 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001839 mUsers.put(userData.info.id, userData);
1840 if (mNextSerialNumber < 0
1841 || mNextSerialNumber <= userData.info.id) {
1842 mNextSerialNumber = userData.info.id + 1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001843 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301844 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001845 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301846 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -08001847 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1848 && type != XmlPullParser.END_TAG) {
1849 if (type == XmlPullParser.START_TAG) {
1850 if (parser.getName().equals(TAG_RESTRICTIONS)) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001851 synchronized (mGuestRestrictions) {
Fyodor Kupoloveafee022017-03-15 17:09:04 -07001852 UserRestrictionsUtils
1853 .readRestrictions(parser, mGuestRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001854 }
Amith Yamasanida0b1682014-11-21 12:58:17 -08001855 }
1856 break;
1857 }
1858 }
Pavel Grafov6a40f092016-10-25 15:46:51 +01001859 } else if (name.equals(TAG_DEVICE_OWNER_USER_ID)
1860 // Legacy name, should only be encountered when upgrading from pre-O.
1861 || name.equals(TAG_GLOBAL_RESTRICTION_OWNER_ID)) {
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001862 String ownerUserId = parser.getAttributeValue(null, ATTR_ID);
1863 if (ownerUserId != null) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001864 mDeviceOwnerUserId = Integer.parseInt(ownerUserId);
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001865 }
Pavel Grafov6a40f092016-10-25 15:46:51 +01001866 } else if (name.equals(TAG_DEVICE_POLICY_RESTRICTIONS)) {
1867 // Should only happen when upgrading from pre-O (version < 7).
1868 oldDevicePolicyGlobalUserRestrictions =
1869 UserRestrictionsUtils.readRestrictions(parser);
Amith Yamasani258848d2012-08-10 17:06:33 -07001870 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001871 }
1872 }
Pavel Grafov6a40f092016-10-25 15:46:51 +01001873
Fyodor Kupolov82402752015-10-28 14:54:51 -07001874 updateUserIds();
Pavel Grafov6a40f092016-10-25 15:46:51 +01001875 upgradeIfNecessaryLP(oldDevicePolicyGlobalUserRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001876 } catch (IOException | XmlPullParserException e) {
1877 fallbackToSingleUserLP();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001878 } finally {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001879 IoUtils.closeQuietly(fis);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001880 }
1881 }
1882
Amith Yamasani6f34b412012-10-22 18:19:27 -07001883 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -08001884 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Pavel Grafov6a40f092016-10-25 15:46:51 +01001885 * @param oldGlobalUserRestrictions Pre-O global device policy restrictions.
Amith Yamasani6f34b412012-10-22 18:19:27 -07001886 */
Pavel Grafov6a40f092016-10-25 15:46:51 +01001887 private void upgradeIfNecessaryLP(Bundle oldGlobalUserRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001888 final int originalVersion = mUserVersion;
Amith Yamasani6f34b412012-10-22 18:19:27 -07001889 int userVersion = mUserVersion;
1890 if (userVersion < 1) {
1891 // Assign a proper name for the owner, if not initialized correctly before
Amith Yamasani12747872015-12-07 14:19:49 -08001892 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
1893 if ("Primary".equals(userData.info.name)) {
1894 userData.info.name =
1895 mContext.getResources().getString(com.android.internal.R.string.owner_name);
1896 scheduleWriteUser(userData);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001897 }
1898 userVersion = 1;
1899 }
1900
Amith Yamasanibc9625052012-11-15 14:39:18 -08001901 if (userVersion < 2) {
1902 // Owner should be marked as initialized
Amith Yamasani12747872015-12-07 14:19:49 -08001903 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
1904 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1905 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
1906 scheduleWriteUser(userData);
Amith Yamasanibc9625052012-11-15 14:39:18 -08001907 }
1908 userVersion = 2;
1909 }
1910
Amith Yamasani350962c2013-08-06 11:18:53 -07001911
Amith Yamasani5e486f52013-08-07 11:06:44 -07001912 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -07001913 userVersion = 4;
1914 }
1915
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001916 if (userVersion < 5) {
1917 initDefaultGuestRestrictions();
1918 userVersion = 5;
1919 }
1920
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001921 if (userVersion < 6) {
1922 final boolean splitSystemUser = UserManager.isSplitSystemUser();
Fyodor Kupolov82402752015-10-28 14:54:51 -07001923 synchronized (mUsersLock) {
1924 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001925 UserData userData = mUsers.valueAt(i);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001926 // In non-split mode, only user 0 can have restricted profiles
Amith Yamasani12747872015-12-07 14:19:49 -08001927 if (!splitSystemUser && userData.info.isRestricted()
1928 && (userData.info.restrictedProfileParentId
1929 == UserInfo.NO_PROFILE_GROUP_ID)) {
1930 userData.info.restrictedProfileParentId = UserHandle.USER_SYSTEM;
1931 scheduleWriteUser(userData);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001932 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001933 }
1934 }
1935 userVersion = 6;
1936 }
1937
Pavel Grafov6a40f092016-10-25 15:46:51 +01001938 if (userVersion < 7) {
1939 // Previously only one user could enforce global restrictions, now it is per-user.
1940 synchronized (mRestrictionsLock) {
1941 if (!UserRestrictionsUtils.isEmpty(oldGlobalUserRestrictions)
1942 && mDeviceOwnerUserId != UserHandle.USER_NULL) {
1943 mDevicePolicyGlobalUserRestrictions.put(
1944 mDeviceOwnerUserId, oldGlobalUserRestrictions);
1945 }
1946 // ENSURE_VERIFY_APPS is now enforced globally even if put by profile owner, so move
1947 // it from local to global bundle for all users who set it.
1948 UserRestrictionsUtils.moveRestriction(UserManager.ENSURE_VERIFY_APPS,
1949 mDevicePolicyLocalUserRestrictions, mDevicePolicyGlobalUserRestrictions
1950 );
1951 }
1952 userVersion = 7;
1953 }
1954
Amith Yamasani6f34b412012-10-22 18:19:27 -07001955 if (userVersion < USER_VERSION) {
1956 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
1957 + USER_VERSION);
1958 } else {
1959 mUserVersion = userVersion;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001960
1961 if (originalVersion < mUserVersion) {
1962 writeUserListLP();
1963 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001964 }
1965 }
1966
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001967 private void fallbackToSingleUserLP() {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001968 int flags = UserInfo.FLAG_INITIALIZED;
1969 // In split system user mode, the admin and primary flags are assigned to the first human
1970 // user.
1971 if (!UserManager.isSplitSystemUser()) {
1972 flags |= UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY;
1973 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001974 // Create the system user
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001975 UserInfo system = new UserInfo(UserHandle.USER_SYSTEM, null, null, flags);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07001976 UserData userData = putUserInfo(system);
Amith Yamasani634cf312012-10-04 17:34:21 -07001977 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -04001978 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -08001979
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001980 Bundle restrictions = new Bundle();
Mahaver Chopra3d9805d2016-07-07 16:25:05 +01001981 try {
1982 final String[] defaultFirstUserRestrictions = mContext.getResources().getStringArray(
1983 com.android.internal.R.array.config_defaultFirstUserRestrictions);
1984 for (String userRestriction : defaultFirstUserRestrictions) {
1985 if (UserRestrictionsUtils.isValidRestriction(userRestriction)) {
1986 restrictions.putBoolean(userRestriction, true);
1987 }
1988 }
1989 } catch (Resources.NotFoundException e) {
1990 Log.e(LOG_TAG, "Couldn't find resource: config_defaultFirstUserRestrictions", e);
1991 }
1992
Pavel Grafov6a40f092016-10-25 15:46:51 +01001993 if (!restrictions.isEmpty()) {
1994 synchronized (mRestrictionsLock) {
1995 mBaseUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions);
1996 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001997 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001998
Fyodor Kupolov82402752015-10-28 14:54:51 -07001999 updateUserIds();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07002000 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002001
Amith Yamasani12747872015-12-07 14:19:49 -08002002 writeUserLP(userData);
Jeff Sharkeycd575992016-03-29 14:12:49 -06002003 writeUserListLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002004 }
2005
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07002006 private String getOwnerName() {
2007 return mContext.getResources().getString(com.android.internal.R.string.owner_name);
2008 }
2009
Amith Yamasani12747872015-12-07 14:19:49 -08002010 private void scheduleWriteUser(UserData UserData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002011 if (DBG) {
2012 debug("scheduleWriteUser");
2013 }
Makoto Onuki9e935a32015-11-06 14:24:24 -08002014 // No need to wrap it within a lock -- worst case, we'll just post the same message
2015 // twice.
Amith Yamasani12747872015-12-07 14:19:49 -08002016 if (!mHandler.hasMessages(WRITE_USER_MSG, UserData)) {
2017 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, UserData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002018 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
2019 }
2020 }
2021
Amith Yamasani12747872015-12-07 14:19:49 -08002022 private void writeUserLP(UserData userData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002023 if (DBG) {
Amith Yamasani12747872015-12-07 14:19:49 -08002024 debug("writeUserLP " + userData);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002025 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002026 FileOutputStream fos = null;
Amith Yamasani12747872015-12-07 14:19:49 -08002027 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userData.info.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002028 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07002029 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002030 final BufferedOutputStream bos = new BufferedOutputStream(fos);
Kenny Guy02c89902016-11-15 19:36:38 +00002031 writeUserLP(userData, bos);
Amith Yamasani2a003292012-08-14 18:25:45 -07002032 userFile.finishWrite(fos);
2033 } catch (Exception ioe) {
Jeff Sharkeycd575992016-03-29 14:12:49 -06002034 Slog.e(LOG_TAG, "Error writing user info " + userData.info.id, ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -07002035 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002036 }
2037 }
2038
2039 /*
Kenny Guy02c89902016-11-15 19:36:38 +00002040 * Writes the user file in this format:
2041 *
2042 * <user flags="20039023" id="0">
2043 * <name>Primary</name>
2044 * </user>
2045 */
2046 @VisibleForTesting
2047 void writeUserLP(UserData userData, OutputStream os)
2048 throws IOException, XmlPullParserException {
2049 // XmlSerializer serializer = XmlUtils.serializerInstance();
2050 final XmlSerializer serializer = new FastXmlSerializer();
2051 serializer.setOutput(os, StandardCharsets.UTF_8.name());
2052 serializer.startDocument(null, true);
2053 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2054
2055 final UserInfo userInfo = userData.info;
2056 serializer.startTag(null, TAG_USER);
2057 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
2058 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
2059 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
2060 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
2061 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
2062 Long.toString(userInfo.lastLoggedInTime));
2063 if (userInfo.lastLoggedInFingerprint != null) {
2064 serializer.attribute(null, ATTR_LAST_LOGGED_IN_FINGERPRINT,
2065 userInfo.lastLoggedInFingerprint);
2066 }
2067 if (userInfo.iconPath != null) {
2068 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
2069 }
2070 if (userInfo.partial) {
2071 serializer.attribute(null, ATTR_PARTIAL, "true");
2072 }
2073 if (userInfo.guestToRemove) {
2074 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
2075 }
2076 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
2077 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
2078 Integer.toString(userInfo.profileGroupId));
2079 }
2080 serializer.attribute(null, ATTR_PROFILE_BADGE,
2081 Integer.toString(userInfo.profileBadge));
2082 if (userInfo.restrictedProfileParentId != UserInfo.NO_PROFILE_GROUP_ID) {
2083 serializer.attribute(null, ATTR_RESTRICTED_PROFILE_PARENT_ID,
2084 Integer.toString(userInfo.restrictedProfileParentId));
2085 }
2086 // Write seed data
2087 if (userData.persistSeedData) {
2088 if (userData.seedAccountName != null) {
2089 serializer.attribute(null, ATTR_SEED_ACCOUNT_NAME, userData.seedAccountName);
2090 }
2091 if (userData.seedAccountType != null) {
2092 serializer.attribute(null, ATTR_SEED_ACCOUNT_TYPE, userData.seedAccountType);
2093 }
2094 }
2095 if (userInfo.name != null) {
2096 serializer.startTag(null, TAG_NAME);
2097 serializer.text(userInfo.name);
2098 serializer.endTag(null, TAG_NAME);
2099 }
2100 synchronized (mRestrictionsLock) {
2101 UserRestrictionsUtils.writeRestrictions(serializer,
2102 mBaseUserRestrictions.get(userInfo.id), TAG_RESTRICTIONS);
2103 UserRestrictionsUtils.writeRestrictions(serializer,
2104 mDevicePolicyLocalUserRestrictions.get(userInfo.id),
2105 TAG_DEVICE_POLICY_RESTRICTIONS);
Pavel Grafov6a40f092016-10-25 15:46:51 +01002106 UserRestrictionsUtils.writeRestrictions(serializer,
2107 mDevicePolicyGlobalUserRestrictions.get(userInfo.id),
2108 TAG_DEVICE_POLICY_GLOBAL_RESTRICTIONS);
Kenny Guy02c89902016-11-15 19:36:38 +00002109 }
2110
2111 if (userData.account != null) {
2112 serializer.startTag(null, TAG_ACCOUNT);
2113 serializer.text(userData.account);
2114 serializer.endTag(null, TAG_ACCOUNT);
2115 }
2116
2117 if (userData.persistSeedData && userData.seedAccountOptions != null) {
2118 serializer.startTag(null, TAG_SEED_ACCOUNT_OPTIONS);
2119 userData.seedAccountOptions.saveToXml(serializer);
2120 serializer.endTag(null, TAG_SEED_ACCOUNT_OPTIONS);
2121 }
2122
2123 serializer.endTag(null, TAG_USER);
2124
2125 serializer.endDocument();
2126 }
2127
2128 /*
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002129 * Writes the user list file in this format:
2130 *
Amith Yamasani2a003292012-08-14 18:25:45 -07002131 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002132 * <user id="0"></user>
2133 * <user id="2"></user>
2134 * </users>
2135 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002136 private void writeUserListLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002137 if (DBG) {
2138 debug("writeUserList");
2139 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002140 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07002141 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002142 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07002143 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002144 final BufferedOutputStream bos = new BufferedOutputStream(fos);
2145
2146 // XmlSerializer serializer = XmlUtils.serializerInstance();
2147 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002148 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002149 serializer.startDocument(null, true);
2150 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2151
2152 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -07002153 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -07002154 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002155
Adam Lesinskieddeb492014-09-08 17:50:03 -07002156 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002157 synchronized (mGuestRestrictions) {
2158 UserRestrictionsUtils
2159 .writeRestrictions(serializer, mGuestRestrictions, TAG_RESTRICTIONS);
2160 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05302161 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Pavel Grafov6a40f092016-10-25 15:46:51 +01002162 serializer.startTag(null, TAG_DEVICE_OWNER_USER_ID);
2163 serializer.attribute(null, ATTR_ID, Integer.toString(mDeviceOwnerUserId));
2164 serializer.endTag(null, TAG_DEVICE_OWNER_USER_ID);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002165 int[] userIdsToWrite;
2166 synchronized (mUsersLock) {
2167 userIdsToWrite = new int[mUsers.size()];
2168 for (int i = 0; i < userIdsToWrite.length; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002169 UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002170 userIdsToWrite[i] = user.id;
2171 }
2172 }
2173 for (int id : userIdsToWrite) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002174 serializer.startTag(null, TAG_USER);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002175 serializer.attribute(null, ATTR_ID, Integer.toString(id));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002176 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002177 }
2178
2179 serializer.endTag(null, TAG_USERS);
2180
2181 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07002182 userListFile.finishWrite(fos);
2183 } catch (Exception e) {
2184 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -07002185 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002186 }
2187 }
2188
Amith Yamasani12747872015-12-07 14:19:49 -08002189 private UserData readUserLP(int id) {
Kenny Guy02c89902016-11-15 19:36:38 +00002190 FileInputStream fis = null;
2191 try {
2192 AtomicFile userFile =
2193 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
2194 fis = userFile.openRead();
2195 return readUserLP(id, fis);
2196 } catch (IOException ioe) {
2197 Slog.e(LOG_TAG, "Error reading user list");
2198 } catch (XmlPullParserException pe) {
2199 Slog.e(LOG_TAG, "Error reading user list");
2200 } finally {
2201 IoUtils.closeQuietly(fis);
2202 }
2203 return null;
2204 }
2205
2206 @VisibleForTesting
2207 UserData readUserLP(int id, InputStream is) throws IOException,
2208 XmlPullParserException {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002209 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -07002210 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002211 String name = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -08002212 String account = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002213 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -07002214 long creationTime = 0L;
2215 long lastLoggedInTime = 0L;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002216 String lastLoggedInFingerprint = null;
Kenny Guy2a764942014-04-02 13:29:20 +01002217 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Kenny Guy02c89902016-11-15 19:36:38 +00002218 int profileBadge = 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002219 int restrictedProfileParentId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002220 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -07002221 boolean guestToRemove = false;
Amith Yamasani12747872015-12-07 14:19:49 -08002222 boolean persistSeedData = false;
2223 String seedAccountName = null;
2224 String seedAccountType = null;
2225 PersistableBundle seedAccountOptions = null;
Pavel Grafov6a40f092016-10-25 15:46:51 +01002226 Bundle baseRestrictions = null;
2227 Bundle localRestrictions = null;
2228 Bundle globalRestrictions = null;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002229
Kenny Guy02c89902016-11-15 19:36:38 +00002230 XmlPullParser parser = Xml.newPullParser();
2231 parser.setInput(is, StandardCharsets.UTF_8.name());
2232 int type;
2233 while ((type = parser.next()) != XmlPullParser.START_TAG
2234 && type != XmlPullParser.END_DOCUMENT) {
2235 // Skip
2236 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002237
Kenny Guy02c89902016-11-15 19:36:38 +00002238 if (type != XmlPullParser.START_TAG) {
2239 Slog.e(LOG_TAG, "Unable to read user " + id);
2240 return null;
2241 }
2242
2243 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
2244 int storedId = readIntAttribute(parser, ATTR_ID, -1);
2245 if (storedId != id) {
2246 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002247 return null;
2248 }
Kenny Guy02c89902016-11-15 19:36:38 +00002249 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
2250 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
2251 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
2252 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
2253 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
2254 lastLoggedInFingerprint = parser.getAttributeValue(null,
2255 ATTR_LAST_LOGGED_IN_FINGERPRINT);
2256 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
2257 UserInfo.NO_PROFILE_GROUP_ID);
2258 profileBadge = readIntAttribute(parser, ATTR_PROFILE_BADGE, 0);
2259 restrictedProfileParentId = readIntAttribute(parser,
2260 ATTR_RESTRICTED_PROFILE_PARENT_ID, UserInfo.NO_PROFILE_GROUP_ID);
2261 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
2262 if ("true".equals(valueString)) {
2263 partial = true;
2264 }
2265 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
2266 if ("true".equals(valueString)) {
2267 guestToRemove = true;
2268 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002269
Kenny Guy02c89902016-11-15 19:36:38 +00002270 seedAccountName = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_NAME);
2271 seedAccountType = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_TYPE);
2272 if (seedAccountName != null || seedAccountType != null) {
2273 persistSeedData = true;
2274 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002275
Kenny Guy02c89902016-11-15 19:36:38 +00002276 int outerDepth = parser.getDepth();
2277 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2278 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2279 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2280 continue;
2281 }
2282 String tag = parser.getName();
2283 if (TAG_NAME.equals(tag)) {
2284 type = parser.next();
2285 if (type == XmlPullParser.TEXT) {
2286 name = parser.getText();
2287 }
2288 } else if (TAG_RESTRICTIONS.equals(tag)) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01002289 baseRestrictions = UserRestrictionsUtils.readRestrictions(parser);
Kenny Guy02c89902016-11-15 19:36:38 +00002290 } else if (TAG_DEVICE_POLICY_RESTRICTIONS.equals(tag)) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01002291 localRestrictions = UserRestrictionsUtils.readRestrictions(parser);
2292 } else if (TAG_DEVICE_POLICY_GLOBAL_RESTRICTIONS.equals(tag)) {
2293 globalRestrictions = UserRestrictionsUtils.readRestrictions(parser);
Kenny Guy02c89902016-11-15 19:36:38 +00002294 } else if (TAG_ACCOUNT.equals(tag)) {
2295 type = parser.next();
2296 if (type == XmlPullParser.TEXT) {
2297 account = parser.getText();
2298 }
2299 } else if (TAG_SEED_ACCOUNT_OPTIONS.equals(tag)) {
2300 seedAccountOptions = PersistableBundle.restoreFromXml(parser);
Amith Yamasani12747872015-12-07 14:19:49 -08002301 persistSeedData = true;
2302 }
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08002303 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002304 }
Kenny Guy02c89902016-11-15 19:36:38 +00002305
2306 // Create the UserInfo object that gets passed around
2307 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
2308 userInfo.serialNumber = serialNumber;
2309 userInfo.creationTime = creationTime;
2310 userInfo.lastLoggedInTime = lastLoggedInTime;
2311 userInfo.lastLoggedInFingerprint = lastLoggedInFingerprint;
2312 userInfo.partial = partial;
2313 userInfo.guestToRemove = guestToRemove;
2314 userInfo.profileGroupId = profileGroupId;
2315 userInfo.profileBadge = profileBadge;
2316 userInfo.restrictedProfileParentId = restrictedProfileParentId;
2317
2318 // Create the UserData object that's internal to this class
2319 UserData userData = new UserData();
2320 userData.info = userInfo;
2321 userData.account = account;
2322 userData.seedAccountName = seedAccountName;
2323 userData.seedAccountType = seedAccountType;
2324 userData.persistSeedData = persistSeedData;
2325 userData.seedAccountOptions = seedAccountOptions;
2326
2327 synchronized (mRestrictionsLock) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01002328 if (baseRestrictions != null) {
2329 mBaseUserRestrictions.put(id, baseRestrictions);
2330 }
2331 if (localRestrictions != null) {
2332 mDevicePolicyLocalUserRestrictions.put(id, localRestrictions);
2333 }
2334 if (globalRestrictions != null) {
2335 mDevicePolicyGlobalUserRestrictions.put(id, globalRestrictions);
2336 }
Kenny Guy02c89902016-11-15 19:36:38 +00002337 }
2338 return userData;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002339 }
2340
Amith Yamasani920ace02012-09-20 22:15:37 -07002341 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
2342 String valueString = parser.getAttributeValue(null, attr);
2343 if (valueString == null) return defaultValue;
2344 try {
2345 return Integer.parseInt(valueString);
2346 } catch (NumberFormatException nfe) {
2347 return defaultValue;
2348 }
2349 }
2350
2351 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
2352 String valueString = parser.getAttributeValue(null, attr);
2353 if (valueString == null) return defaultValue;
2354 try {
2355 return Long.parseLong(valueString);
2356 } catch (NumberFormatException nfe) {
2357 return defaultValue;
2358 }
2359 }
2360
Amith Yamasanib82add22013-07-09 11:24:44 -07002361 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002362 * Removes the app restrictions file for a specific package and user id, if it exists.
2363 */
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07002364 private static void cleanAppRestrictionsForPackageLAr(String pkg, int userId) {
2365 File dir = Environment.getUserSystemDirectory(userId);
2366 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
2367 if (resFile.exists()) {
2368 resFile.delete();
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002369 }
2370 }
2371
Kenny Guya52dc3e2014-02-11 15:33:14 +00002372 @Override
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002373 public UserInfo createProfileForUser(String name, int flags, int userId,
2374 String[] disallowedPackages) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002375 checkManageOrCreateUsersPermission(flags);
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002376 return createUserInternal(name, flags, userId, disallowedPackages);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002377 }
2378
Amith Yamasani258848d2012-08-10 17:06:33 -07002379 @Override
Tony Mak6dc428f2016-10-10 15:48:27 +01002380 public UserInfo createProfileForUserEvenWhenDisallowed(String name, int flags, int userId,
2381 String[] disallowedPackages) {
2382 checkManageOrCreateUsersPermission(flags);
2383 return createUserInternalUnchecked(name, flags, userId, disallowedPackages);
2384 }
2385
2386 @Override
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00002387 public boolean removeUserEvenWhenDisallowed(@UserIdInt int userHandle) {
2388 checkManageOrCreateUsersPermission("Only the system can remove users");
2389 return removeUserUnchecked(userHandle);
2390 }
2391
2392 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07002393 public UserInfo createUser(String name, int flags) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002394 checkManageOrCreateUsersPermission(flags);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00002395 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002396 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07002397
Jessica Hummelbe81c802014-04-22 15:49:22 +01002398 private UserInfo createUserInternal(String name, int flags, int parentId) {
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002399 return createUserInternal(name, flags, parentId, null);
2400 }
2401
2402 private UserInfo createUserInternal(String name, int flags, int parentId,
2403 String[] disallowedPackages) {
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002404 String restriction = ((flags & UserInfo.FLAG_MANAGED_PROFILE) != 0)
2405 ? UserManager.DISALLOW_ADD_MANAGED_PROFILE
2406 : UserManager.DISALLOW_ADD_USER;
2407 if (hasUserRestriction(restriction, UserHandle.getCallingUserId())) {
2408 Log.w(LOG_TAG, "Cannot add user. " + restriction + " is enabled.");
Julia Reynolds75175022014-06-26 16:35:00 -04002409 return null;
2410 }
Tony Mak6dc428f2016-10-10 15:48:27 +01002411 return createUserInternalUnchecked(name, flags, parentId, disallowedPackages);
2412 }
2413
2414 private UserInfo createUserInternalUnchecked(String name, int flags, int parentId,
2415 String[] disallowedPackages) {
Suprabh Shuklac5e057c2016-08-08 16:22:44 -07002416 DeviceStorageMonitorInternal dsm = LocalServices
2417 .getService(DeviceStorageMonitorInternal.class);
2418 if (dsm.isMemoryLow()) {
2419 Log.w(LOG_TAG, "Cannot add user. Not enough space on disk.");
2420 return null;
2421 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07002422 if (ActivityManager.isLowRamDeviceStatic()) {
2423 return null;
2424 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07002425 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Nicolas Prevot12678a92015-05-13 12:15:03 -07002426 final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002427 final boolean isRestricted = (flags & UserInfo.FLAG_RESTRICTED) != 0;
Amith Yamasani52c21e32016-05-31 09:12:20 -07002428 final boolean isDemo = (flags & UserInfo.FLAG_DEMO) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002429 final long ident = Binder.clearCallingIdentity();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002430 UserInfo userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08002431 UserData userData;
Amith Yamasanibb054c92015-07-09 14:16:27 -07002432 final int userId;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002433 try {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002434 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002435 UserData parent = null;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002436 if (parentId != UserHandle.USER_NULL) {
2437 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002438 parent = getUserDataLU(parentId);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00002439 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002440 if (parent == null) return null;
2441 }
2442 if (isManagedProfile && !canAddMoreManagedProfiles(parentId, false)) {
2443 Log.e(LOG_TAG, "Cannot add more managed profiles for user " + parentId);
2444 return null;
2445 }
Amith Yamasani52c21e32016-05-31 09:12:20 -07002446 if (!isGuest && !isManagedProfile && !isDemo && isUserLimitReached()) {
2447 // If we're not adding a guest/demo user or a managed profile and the limit has
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002448 // been reached, cannot add a user.
2449 return null;
2450 }
2451 // If we're adding a guest and there already exists one, bail.
2452 if (isGuest && findCurrentGuestUser() != null) {
2453 return null;
2454 }
2455 // In legacy mode, restricted profile's parent can only be the owner user
2456 if (isRestricted && !UserManager.isSplitSystemUser()
2457 && (parentId != UserHandle.USER_SYSTEM)) {
2458 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
2459 return null;
2460 }
2461 if (isRestricted && UserManager.isSplitSystemUser()) {
2462 if (parent == null) {
2463 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be "
2464 + "specified");
Nicolas Prevot12678a92015-05-13 12:15:03 -07002465 return null;
2466 }
Amith Yamasani12747872015-12-07 14:19:49 -08002467 if (!parent.info.canHaveProfile()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002468 Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be "
2469 + "created for the specified parent user id " + parentId);
Amith Yamasani95ab7842014-08-11 17:09:26 -07002470 return null;
2471 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002472 }
2473 // In split system user mode, we assign the first human user the primary flag.
2474 // And if there is no device owner, we also assign the admin flag to primary user.
2475 if (UserManager.isSplitSystemUser()
2476 && !isGuest && !isManagedProfile && getPrimaryUser() == null) {
2477 flags |= UserInfo.FLAG_PRIMARY;
Makoto Onukie7927da2015-11-25 10:05:17 -08002478 synchronized (mUsersLock) {
2479 if (!mIsDeviceManaged) {
2480 flags |= UserInfo.FLAG_ADMIN;
2481 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07002482 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002483 }
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002484
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002485 userId = getNextAvailableId();
2486 Environment.getUserSystemDirectory(userId).mkdirs();
Lenka Trochtova02fee152015-12-22 14:26:18 +01002487 boolean ephemeralGuests = Resources.getSystem()
2488 .getBoolean(com.android.internal.R.bool.config_guestUserEphemeral);
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002489
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002490 synchronized (mUsersLock) {
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002491 // Add ephemeral flag to guests/users if required. Also inherit it from parent.
2492 if ((isGuest && ephemeralGuests) || mForceEphemeralUsers
2493 || (parent != null && parent.info.isEphemeral())) {
2494 flags |= UserInfo.FLAG_EPHEMERAL;
2495 }
2496
2497 userInfo = new UserInfo(userId, name, null, flags);
2498 userInfo.serialNumber = mNextSerialNumber++;
2499 long now = System.currentTimeMillis();
2500 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
2501 userInfo.partial = true;
Fyodor Kupolov83c24242016-03-31 13:30:42 -07002502 userInfo.lastLoggedInFingerprint = Build.FINGERPRINT;
Kenny Guy02c89902016-11-15 19:36:38 +00002503 if (isManagedProfile && parentId != UserHandle.USER_NULL) {
2504 userInfo.profileBadge = getFreeProfileBadgeLU(parentId);
2505 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002506 userData = new UserData();
2507 userData.info = userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08002508 mUsers.put(userId, userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002509 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06002510 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002511 writeUserListLP();
2512 if (parent != null) {
2513 if (isManagedProfile) {
Amith Yamasani12747872015-12-07 14:19:49 -08002514 if (parent.info.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
2515 parent.info.profileGroupId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002516 writeUserLP(parent);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002517 }
Amith Yamasani12747872015-12-07 14:19:49 -08002518 userInfo.profileGroupId = parent.info.profileGroupId;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002519 } else if (isRestricted) {
Amith Yamasani12747872015-12-07 14:19:49 -08002520 if (parent.info.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) {
2521 parent.info.restrictedProfileParentId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002522 writeUserLP(parent);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002523 }
Amith Yamasani12747872015-12-07 14:19:49 -08002524 userInfo.restrictedProfileParentId = parent.info.restrictedProfileParentId;
Makoto Onuki068c54a2015-10-13 14:34:03 -07002525 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002526 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07002527 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002528 final StorageManager storage = mContext.getSystemService(StorageManager.class);
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002529 storage.createUserKey(userId, userInfo.serialNumber, userInfo.isEphemeral());
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -08002530 mUserDataPreparer.prepareUserData(userId, userInfo.serialNumber,
Jeff Sharkey47f71082016-02-01 17:03:54 -07002531 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002532 mPm.createNewUser(userId, disallowedPackages);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002533 userInfo.partial = false;
2534 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002535 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002536 }
2537 updateUserIds();
2538 Bundle restrictions = new Bundle();
Fyodor Kupolove04462c2015-11-30 15:02:53 -08002539 if (isGuest) {
2540 synchronized (mGuestRestrictions) {
2541 restrictions.putAll(mGuestRestrictions);
2542 }
2543 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002544 synchronized (mRestrictionsLock) {
2545 mBaseUserRestrictions.append(userId, restrictions);
2546 }
Fyodor Kupolov5fd967d2016-07-12 14:46:19 -07002547 mPm.onNewUserCreated(userId);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002548 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
2549 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
2550 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
2551 android.Manifest.permission.MANAGE_USERS);
Christine Franks88220562017-05-24 11:11:21 -07002552 MetricsLogger.count(mContext, isGuest ? TRON_GUEST_CREATED
2553 : (isDemo ? TRON_DEMO_CREATED : TRON_USER_CREATED), 1);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002554 } finally {
2555 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07002556 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002557 return userInfo;
2558 }
2559
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002560 @VisibleForTesting
2561 UserData putUserInfo(UserInfo userInfo) {
2562 final UserData userData = new UserData();
2563 userData.info = userInfo;
2564 synchronized (mUsers) {
2565 mUsers.put(userInfo.id, userData);
2566 }
2567 return userData;
2568 }
2569
2570 @VisibleForTesting
2571 void removeUserInfo(int userId) {
2572 synchronized (mUsers) {
2573 mUsers.remove(userId);
2574 }
2575 }
2576
Amith Yamasani0b285492011-04-14 17:35:23 -07002577 /**
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002578 * @hide
2579 */
Amith Yamasani12747872015-12-07 14:19:49 -08002580 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002581 public UserInfo createRestrictedProfile(String name, int parentUserId) {
Sudheer Shanka53d41472016-06-16 09:11:08 -07002582 checkManageOrCreateUsersPermission("setupRestrictedProfile");
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002583 final UserInfo user = createProfileForUser(
2584 name, UserInfo.FLAG_RESTRICTED, parentUserId, null);
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002585 if (user == null) {
2586 return null;
2587 }
Fyodor Kupolov9e912ba2016-02-09 18:29:43 -08002588 long identity = Binder.clearCallingIdentity();
2589 try {
2590 setUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, true, user.id);
2591 // Change the setting before applying the DISALLOW_SHARE_LOCATION restriction, otherwise
2592 // the putIntForUser() will fail.
2593 android.provider.Settings.Secure.putIntForUser(mContext.getContentResolver(),
2594 android.provider.Settings.Secure.LOCATION_MODE,
2595 android.provider.Settings.Secure.LOCATION_MODE_OFF, user.id);
2596 setUserRestriction(UserManager.DISALLOW_SHARE_LOCATION, true, user.id);
2597 } finally {
2598 Binder.restoreCallingIdentity(identity);
2599 }
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002600 return user;
2601 }
2602
2603 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07002604 * Find the current guest user. If the Guest user is partial,
2605 * then do not include it in the results as it is about to die.
Adam Lesinskieddeb492014-09-08 17:50:03 -07002606 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002607 private UserInfo findCurrentGuestUser() {
2608 synchronized (mUsersLock) {
2609 final int size = mUsers.size();
2610 for (int i = 0; i < size; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002611 final UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002612 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
2613 return user;
2614 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002615 }
2616 }
2617 return null;
2618 }
2619
2620 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07002621 * Mark this guest user for deletion to allow us to create another guest
2622 * and switch to that user before actually removing this guest.
2623 * @param userHandle the userid of the current guest
2624 * @return whether the user could be marked for deletion
2625 */
Amith Yamasani12747872015-12-07 14:19:49 -08002626 @Override
Amith Yamasani1df14732014-08-29 21:37:27 -07002627 public boolean markGuestForDeletion(int userHandle) {
2628 checkManageUsersPermission("Only the system can remove users");
2629 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
2630 UserManager.DISALLOW_REMOVE_USER, false)) {
2631 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
2632 return false;
2633 }
2634
2635 long ident = Binder.clearCallingIdentity();
2636 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002637 final UserData userData;
Amith Yamasani1df14732014-08-29 21:37:27 -07002638 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002639 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002640 userData = mUsers.get(userHandle);
2641 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002642 return false;
2643 }
Amith Yamasani1df14732014-08-29 21:37:27 -07002644 }
Amith Yamasani12747872015-12-07 14:19:49 -08002645 if (!userData.info.isGuest()) {
Amith Yamasani1df14732014-08-29 21:37:27 -07002646 return false;
2647 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002648 // We set this to a guest user that is to be removed. This is a temporary state
2649 // where we are allowed to add new Guest users, even if this one is still not
2650 // removed. This user will still show up in getUserInfo() calls.
2651 // If we don't get around to removing this Guest user, it will be purged on next
2652 // startup.
Amith Yamasani12747872015-12-07 14:19:49 -08002653 userData.info.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07002654 // Mark it as disabled, so that it isn't returned any more when
2655 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002656 userData.info.flags |= UserInfo.FLAG_DISABLED;
2657 writeUserLP(userData);
Amith Yamasani1df14732014-08-29 21:37:27 -07002658 }
2659 } finally {
2660 Binder.restoreCallingIdentity(ident);
2661 }
2662 return true;
2663 }
2664
2665 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002666 * Removes a user and all data directories created for that user. This method should be called
2667 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07002668 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07002669 */
Amith Yamasani12747872015-12-07 14:19:49 -08002670 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -07002671 public boolean removeUser(int userHandle) {
Fyodor Kupolov4593e422016-10-27 11:00:29 -07002672 Slog.i(LOG_TAG, "removeUser u" + userHandle);
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002673 checkManageOrCreateUsersPermission("Only the system can remove users");
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002674
2675 final boolean isManagedProfile;
2676 synchronized (mUsersLock) {
2677 UserInfo userInfo = getUserInfoLU(userHandle);
2678 isManagedProfile = userInfo != null && userInfo.isManagedProfile();
2679 }
2680 String restriction = isManagedProfile
2681 ? UserManager.DISALLOW_REMOVE_MANAGED_PROFILE : UserManager.DISALLOW_REMOVE_USER;
2682 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(restriction, false)) {
2683 Log.w(LOG_TAG, "Cannot remove user. " + restriction + " is enabled.");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04002684 return false;
2685 }
Nicolas Prevotdf1b87d2016-10-25 13:57:08 +01002686 return removeUserUnchecked(userHandle);
2687 }
Julia Reynolds4ac5f852014-06-23 17:38:51 -04002688
Nicolas Prevotdf1b87d2016-10-25 13:57:08 +01002689 private boolean removeUserUnchecked(int userHandle) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002690 long ident = Binder.clearCallingIdentity();
2691 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002692 final UserData userData;
Fyodor Kupolov0df68cd2015-10-01 13:54:22 -07002693 int currentUser = ActivityManager.getCurrentUser();
2694 if (currentUser == userHandle) {
2695 Log.w(LOG_TAG, "Current user cannot be removed");
2696 return false;
2697 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002698 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002699 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002700 userData = mUsers.get(userHandle);
2701 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002702 return false;
2703 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002704
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002705 addRemovingUserIdLocked(userHandle);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002706 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002707
Kenny Guyee58b4f2014-05-23 15:19:53 +01002708 // Set this to a partially created user, so that the user will be purged
2709 // on next startup, in case the runtime stops now before stopping and
2710 // removing the user completely.
Amith Yamasani12747872015-12-07 14:19:49 -08002711 userData.info.partial = true;
Kenny Guyee58b4f2014-05-23 15:19:53 +01002712 // Mark it as disabled, so that it isn't returned any more when
2713 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002714 userData.info.flags |= UserInfo.FLAG_DISABLED;
2715 writeUserLP(userData);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002716 }
Fyodor Kupolov6c96f7f2017-06-28 18:22:59 -07002717 try {
2718 mAppOpsService.removeUser(userHandle);
2719 } catch (RemoteException e) {
2720 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
2721 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002722
Amith Yamasani12747872015-12-07 14:19:49 -08002723 if (userData.info.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
2724 && userData.info.isManagedProfile()) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002725 // Send broadcast to notify system that the user removed was a
2726 // managed user.
Amith Yamasani12747872015-12-07 14:19:49 -08002727 sendProfileRemovedBroadcast(userData.info.profileGroupId, userData.info.id);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002728 }
2729
2730 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
2731 int res;
2732 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08002733 res = ActivityManager.getService().stopUser(userHandle, /* force= */ true,
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07002734 new IStopUserCallback.Stub() {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002735 @Override
2736 public void userStopped(int userId) {
2737 finishRemoveUser(userId);
2738 }
2739 @Override
2740 public void userStopAborted(int userId) {
2741 }
2742 });
2743 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002744 return false;
2745 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002746 return res == ActivityManager.USER_OP_SUCCESS;
2747 } finally {
2748 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002749 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002750 }
2751
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002752 @VisibleForTesting
2753 void addRemovingUserIdLocked(int userId) {
2754 // We remember deleted user IDs to prevent them from being
2755 // reused during the current boot; they can still be reused
2756 // after a reboot or recycling of userIds.
2757 mRemovingUserIds.put(userId, true);
2758 mRecentlyRemovedIds.add(userId);
2759 // Keep LRU queue of recently removed IDs for recycling
2760 if (mRecentlyRemovedIds.size() > MAX_RECENTLY_REMOVED_IDS_SIZE) {
2761 mRecentlyRemovedIds.removeFirst();
2762 }
2763 }
2764
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002765 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07002766 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002767 // Let other services shutdown any activity and clean up their state before completely
2768 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002769 long ident = Binder.clearCallingIdentity();
2770 try {
2771 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
2772 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002773 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
2774 android.Manifest.permission.MANAGE_USERS,
2775
2776 new BroadcastReceiver() {
2777 @Override
2778 public void onReceive(Context context, Intent intent) {
2779 if (DBG) {
2780 Slog.i(LOG_TAG,
2781 "USER_REMOVED broadcast sent, cleaning up user data "
2782 + userHandle);
2783 }
2784 new Thread() {
Amith Yamasani12747872015-12-07 14:19:49 -08002785 @Override
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002786 public void run() {
Amith Yamasani515d4062015-09-28 11:30:06 -07002787 // Clean up any ActivityManager state
2788 LocalServices.getService(ActivityManagerInternal.class)
2789 .onUserRemoved(userHandle);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002790 removeUserState(userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002791 }
2792 }.start();
2793 }
2794 },
2795
2796 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002797 } finally {
2798 Binder.restoreCallingIdentity(ident);
2799 }
Amith Yamasani2a003292012-08-14 18:25:45 -07002800 }
2801
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002802 private void removeUserState(final int userHandle) {
Paul Crowley91293792016-03-25 15:23:07 -07002803 try {
2804 mContext.getSystemService(StorageManager.class).destroyUserKey(userHandle);
2805 } catch (IllegalStateException e) {
2806 // This may be simply because the user was partially created.
2807 Slog.i(LOG_TAG,
2808 "Destroying key for user " + userHandle + " failed, continuing anyway", e);
2809 }
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002810
Amith Yamasanid04aaa32016-06-13 12:09:36 -07002811 // Cleanup gatekeeper secure user id
2812 try {
2813 final IGateKeeperService gk = GateKeeper.getService();
2814 if (gk != null) {
2815 gk.clearSecureUserId(userHandle);
2816 }
2817 } catch (Exception ex) {
2818 Slog.w(LOG_TAG, "unable to clear GK secure user id");
2819 }
2820
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002821 // Cleanup package manager settings
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002822 mPm.cleanUpUser(this, userHandle);
Amith Yamasanid04aaa32016-06-13 12:09:36 -07002823
2824 // Clean up all data before removing metadata
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -08002825 mUserDataPreparer.destroyUserData(userHandle,
Amith Yamasanid04aaa32016-06-13 12:09:36 -07002826 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2827
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002828 // Remove this user from the list
Fyodor Kupolov82402752015-10-28 14:54:51 -07002829 synchronized (mUsersLock) {
2830 mUsers.remove(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08002831 mIsUserManaged.delete(userHandle);
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00002832 }
2833 synchronized (mUserStates) {
2834 mUserStates.delete(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08002835 }
2836 synchronized (mRestrictionsLock) {
2837 mBaseUserRestrictions.remove(userHandle);
2838 mAppliedUserRestrictions.remove(userHandle);
2839 mCachedEffectiveUserRestrictions.remove(userHandle);
2840 mDevicePolicyLocalUserRestrictions.remove(userHandle);
Pavel Grafov6a40f092016-10-25 15:46:51 +01002841 if (mDevicePolicyGlobalUserRestrictions.get(userHandle) != null) {
2842 mDevicePolicyGlobalUserRestrictions.remove(userHandle);
2843 applyUserRestrictionsForAllUsersLR();
2844 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002845 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002846 // Update the user list
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002847 synchronized (mPackagesLock) {
2848 writeUserListLP();
2849 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06002850 // Remove user file
2851 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
2852 userFile.delete();
Fyodor Kupolov82402752015-10-28 14:54:51 -07002853 updateUserIds();
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002854 if (RELEASE_DELETED_USER_ID) {
2855 synchronized (mUsers) {
2856 mRemovingUserIds.delete(userHandle);
2857 }
2858 }
Amith Yamasani61f57372012-08-31 12:12:28 -07002859 }
2860
Kenny Guyf8d3a232014-05-15 16:09:52 +01002861 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01002862 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01002863 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
2864 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002865 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
Jeff Sharkeyaf6ec292015-12-17 11:19:00 -07002866 managedProfileIntent.putExtra(Intent.EXTRA_USER_HANDLE, removedUserId);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002867 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01002868 }
2869
Amith Yamasani2a003292012-08-14 18:25:45 -07002870 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002871 public Bundle getApplicationRestrictions(String packageName) {
2872 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
2873 }
2874
2875 @Override
2876 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002877 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07002878 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07002879 checkSystemOrRoot("get application restrictions for other user/app " + packageName);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002880 }
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07002881 synchronized (mAppRestrictionsLock) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002882 // Read the restrictions from XML
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07002883 return readApplicationRestrictionsLAr(packageName, userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002884 }
2885 }
2886
2887 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002888 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002889 int userId) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00002890 checkSystemOrRoot("set application restrictions");
Fyodor Kupolov0d88d542016-04-19 11:37:22 -07002891 if (restrictions != null) {
2892 restrictions.setDefusable(true);
2893 }
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07002894 synchronized (mAppRestrictionsLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01002895 if (restrictions == null || restrictions.isEmpty()) {
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07002896 cleanAppRestrictionsForPackageLAr(packageName, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01002897 } else {
2898 // Write the restrictions to XML
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07002899 writeApplicationRestrictionsLAr(packageName, restrictions, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01002900 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002901 }
Robin Lee66e5d962014-04-09 16:44:21 +01002902
Fyodor Kupolovd2846122016-02-11 18:06:34 -08002903 // Notify package of changes via an intent - only sent to explicitly registered receivers.
2904 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
2905 changeIntent.setPackage(packageName);
2906 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
2907 mContext.sendBroadcastAsUser(changeIntent, UserHandle.of(userId));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002908 }
2909
2910 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07002911 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002912 try {
2913 return mContext.getPackageManager().getApplicationInfo(packageName,
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07002914 PackageManager.MATCH_ANY_USER).uid;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002915 } catch (NameNotFoundException nnfe) {
2916 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07002917 } finally {
2918 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002919 }
2920 }
2921
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07002922 @GuardedBy("mAppRestrictionsLock")
2923 private static Bundle readApplicationRestrictionsLAr(String packageName, int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002924 AtomicFile restrictionsFile =
2925 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
2926 packageToRestrictionsFileName(packageName)));
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07002927 return readApplicationRestrictionsLAr(restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002928 }
2929
2930 @VisibleForTesting
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07002931 @GuardedBy("mAppRestrictionsLock")
2932 static Bundle readApplicationRestrictionsLAr(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002933 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002934 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002935 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07002936 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002937 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002938
2939 FileInputStream fis = null;
2940 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002941 fis = restrictionsFile.openRead();
2942 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002943 parser.setInput(fis, StandardCharsets.UTF_8.name());
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002944 XmlUtils.nextElement(parser);
2945 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002946 Slog.e(LOG_TAG, "Unable to read restrictions file "
2947 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002948 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002949 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002950 while (parser.next() != XmlPullParser.END_DOCUMENT) {
2951 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002952 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002953 } catch (IOException|XmlPullParserException e) {
2954 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002955 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002956 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002957 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002958 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002959 }
2960
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002961 private static void readEntry(Bundle restrictions, ArrayList<String> values,
2962 XmlPullParser parser) throws XmlPullParserException, IOException {
2963 int type = parser.getEventType();
2964 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
2965 String key = parser.getAttributeValue(null, ATTR_KEY);
2966 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
2967 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
2968 if (multiple != null) {
2969 values.clear();
2970 int count = Integer.parseInt(multiple);
2971 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
2972 if (type == XmlPullParser.START_TAG
2973 && parser.getName().equals(TAG_VALUE)) {
2974 values.add(parser.nextText().trim());
2975 count--;
2976 }
2977 }
2978 String [] valueStrings = new String[values.size()];
2979 values.toArray(valueStrings);
2980 restrictions.putStringArray(key, valueStrings);
2981 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
2982 restrictions.putBundle(key, readBundleEntry(parser, values));
2983 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
2984 final int outerDepth = parser.getDepth();
2985 ArrayList<Bundle> bundleList = new ArrayList<>();
2986 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2987 Bundle childBundle = readBundleEntry(parser, values);
2988 bundleList.add(childBundle);
2989 }
2990 restrictions.putParcelableArray(key,
2991 bundleList.toArray(new Bundle[bundleList.size()]));
2992 } else {
2993 String value = parser.nextText().trim();
2994 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
2995 restrictions.putBoolean(key, Boolean.parseBoolean(value));
2996 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
2997 restrictions.putInt(key, Integer.parseInt(value));
2998 } else {
2999 restrictions.putString(key, value);
3000 }
3001 }
3002 }
3003 }
3004
3005 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
3006 throws IOException, XmlPullParserException {
3007 Bundle childBundle = new Bundle();
3008 final int outerDepth = parser.getDepth();
3009 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
3010 readEntry(childBundle, values, parser);
3011 }
3012 return childBundle;
3013 }
3014
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003015 @GuardedBy("mAppRestrictionsLock")
3016 private static void writeApplicationRestrictionsLAr(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07003017 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003018 AtomicFile restrictionsFile = new AtomicFile(
3019 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07003020 packageToRestrictionsFileName(packageName)));
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003021 writeApplicationRestrictionsLAr(restrictions, restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003022 }
3023
3024 @VisibleForTesting
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003025 @GuardedBy("mAppRestrictionsLock")
3026 static void writeApplicationRestrictionsLAr(Bundle restrictions, AtomicFile restrictionsFile) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003027 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003028 try {
3029 fos = restrictionsFile.startWrite();
3030 final BufferedOutputStream bos = new BufferedOutputStream(fos);
3031
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003032 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01003033 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003034 serializer.startDocument(null, true);
3035 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
3036
3037 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003038 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003039 serializer.endTag(null, TAG_RESTRICTIONS);
3040
3041 serializer.endDocument();
3042 restrictionsFile.finishWrite(fos);
3043 } catch (Exception e) {
3044 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003045 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
3046 }
3047 }
3048
3049 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
3050 throws IOException {
3051 for (String key : restrictions.keySet()) {
3052 Object value = restrictions.get(key);
3053 serializer.startTag(null, TAG_ENTRY);
3054 serializer.attribute(null, ATTR_KEY, key);
3055
3056 if (value instanceof Boolean) {
3057 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
3058 serializer.text(value.toString());
3059 } else if (value instanceof Integer) {
3060 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
3061 serializer.text(value.toString());
3062 } else if (value == null || value instanceof String) {
3063 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
3064 serializer.text(value != null ? (String) value : "");
3065 } else if (value instanceof Bundle) {
3066 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
3067 writeBundle((Bundle) value, serializer);
3068 } else if (value instanceof Parcelable[]) {
3069 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
3070 Parcelable[] array = (Parcelable[]) value;
3071 for (Parcelable parcelable : array) {
3072 if (!(parcelable instanceof Bundle)) {
3073 throw new IllegalArgumentException("bundle-array can only hold Bundles");
3074 }
3075 serializer.startTag(null, TAG_ENTRY);
3076 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
3077 writeBundle((Bundle) parcelable, serializer);
3078 serializer.endTag(null, TAG_ENTRY);
3079 }
3080 } else {
3081 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
3082 String[] values = (String[]) value;
3083 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
3084 for (String choice : values) {
3085 serializer.startTag(null, TAG_VALUE);
3086 serializer.text(choice != null ? choice : "");
3087 serializer.endTag(null, TAG_VALUE);
3088 }
3089 }
3090 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003091 }
3092 }
3093
3094 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07003095 public int getUserSerialNumber(int userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003096 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07003097 if (!exists(userHandle)) return -1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003098 return getUserInfoLU(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07003099 }
3100 }
3101
3102 @Override
Fyodor Kupolov605b12a2017-05-10 15:58:09 -07003103 public boolean isUserNameSet(int userHandle) {
3104 synchronized (mUsersLock) {
3105 UserInfo userInfo = getUserInfoLU(userHandle);
3106 return userInfo != null && userInfo.name != null;
3107 }
3108 }
3109
3110 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07003111 public int getUserHandle(int userSerialNumber) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003112 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07003113 for (int userId : mUserIds) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003114 UserInfo info = getUserInfoLU(userId);
Kenny Guy945f8832015-02-10 15:17:26 +00003115 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07003116 }
3117 // Not found
3118 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07003119 }
3120 }
3121
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003122 @Override
3123 public long getUserCreationTime(int userHandle) {
3124 int callingUserId = UserHandle.getCallingUserId();
3125 UserInfo userInfo = null;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003126 synchronized (mUsersLock) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003127 if (callingUserId == userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003128 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003129 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003130 UserInfo parent = getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003131 if (parent != null && parent.id == callingUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003132 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003133 }
3134 }
3135 }
3136 if (userInfo == null) {
3137 throw new SecurityException("userHandle can only be the calling user or a managed "
3138 + "profile associated with this user");
3139 }
3140 return userInfo.creationTime;
3141 }
3142
Amith Yamasani0b285492011-04-14 17:35:23 -07003143 /**
3144 * Caches the list of user ids in an array, adjusting the array size when necessary.
3145 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07003146 private void updateUserIds() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003147 int num = 0;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003148 synchronized (mUsersLock) {
3149 final int userSize = mUsers.size();
3150 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003151 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003152 num++;
3153 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003154 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07003155 final int[] newUsers = new int[num];
3156 int n = 0;
3157 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003158 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003159 newUsers[n++] = mUsers.keyAt(i);
3160 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003161 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07003162 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07003163 }
3164 }
3165
3166 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003167 * Called right before a user is started. This gives us a chance to prepare
3168 * app storage and apply any user restrictions.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003169 */
3170 public void onBeforeStartUser(int userId) {
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003171 UserInfo userInfo = getUserInfo(userId);
3172 if (userInfo == null) {
3173 return;
3174 }
3175 final int userSerial = userInfo.serialNumber;
3176 // Migrate only if build fingerprints mismatch
3177 boolean migrateAppsData = !Build.FINGERPRINT.equals(userInfo.lastLoggedInFingerprint);
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -08003178 mUserDataPreparer.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_DE);
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003179 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_DE, migrateAppsData);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003180
3181 if (userId != UserHandle.USER_SYSTEM) {
3182 synchronized (mRestrictionsLock) {
3183 applyUserRestrictionsLR(userId);
3184 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003185 }
3186 }
3187
3188 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003189 * Called right before a user is unlocked. This gives us a chance to prepare
3190 * app storage.
3191 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003192 public void onBeforeUnlockUser(@UserIdInt int userId) {
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003193 UserInfo userInfo = getUserInfo(userId);
3194 if (userInfo == null) {
3195 return;
3196 }
3197 final int userSerial = userInfo.serialNumber;
3198 // Migrate only if build fingerprints mismatch
3199 boolean migrateAppsData = !Build.FINGERPRINT.equals(userInfo.lastLoggedInFingerprint);
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -08003200 mUserDataPreparer.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_CE);
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003201 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_CE, migrateAppsData);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003202 }
3203
3204 /**
Fyodor Kupolov50979d12017-01-27 17:36:32 -08003205 * Examine all users present on given mounted volume, and destroy data
3206 * belonging to users that are no longer valid, or whose user ID has been
3207 * recycled.
3208 */
3209 void reconcileUsers(String volumeUuid) {
3210 mUserDataPreparer.reconcileUsers(volumeUuid, getUsers(true /* excludeDying */));
3211 }
3212
3213 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07003214 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasanieb437d42016-04-29 09:31:25 -07003215 * This is called with ActivityManagerService lock held.
Amith Yamasani920ace02012-09-20 22:15:37 -07003216 * @param userId the user that was just foregrounded
3217 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003218 public void onUserLoggedIn(@UserIdInt int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -08003219 UserData userData = getUserDataNoChecks(userId);
3220 if (userData == null || userData.info.partial) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003221 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
3222 return;
3223 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003224
3225 final long now = System.currentTimeMillis();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003226 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani12747872015-12-07 14:19:49 -08003227 userData.info.lastLoggedInTime = now;
Amith Yamasani920ace02012-09-20 22:15:37 -07003228 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003229 userData.info.lastLoggedInFingerprint = Build.FINGERPRINT;
3230 scheduleWriteUser(userData);
Amith Yamasani920ace02012-09-20 22:15:37 -07003231 }
3232
3233 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07003234 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani0b285492011-04-14 17:35:23 -07003235 */
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003236 @VisibleForTesting
3237 int getNextAvailableId() {
3238 int nextId;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003239 synchronized (mUsersLock) {
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003240 nextId = scanNextAvailableIdLocked();
3241 if (nextId >= 0) {
3242 return nextId;
3243 }
3244 // All ids up to MAX_USER_ID were used. Remove all mRemovingUserIds,
3245 // except most recently removed
3246 if (mRemovingUserIds.size() > 0) {
3247 Slog.i(LOG_TAG, "All available IDs are used. Recycling LRU ids.");
3248 mRemovingUserIds.clear();
3249 for (Integer recentlyRemovedId : mRecentlyRemovedIds) {
3250 mRemovingUserIds.put(recentlyRemovedId, true);
Amith Yamasani195263742012-08-21 15:40:12 -07003251 }
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003252 nextId = scanNextAvailableIdLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003253 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003254 }
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003255 if (nextId < 0) {
3256 throw new IllegalStateException("No user id available!");
3257 }
3258 return nextId;
3259 }
3260
3261 private int scanNextAvailableIdLocked() {
3262 for (int i = MIN_USER_ID; i < MAX_USER_ID; i++) {
3263 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
3264 return i;
3265 }
3266 }
3267 return -1;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003268 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003269
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003270 private static String packageToRestrictionsFileName(String packageName) {
Amith Yamasanifc95e702013-09-26 13:20:17 -07003271 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
3272 }
3273
Amith Yamasani920ace02012-09-20 22:15:37 -07003274 @Override
Amith Yamasani12747872015-12-07 14:19:49 -08003275 public void setSeedAccountData(int userId, String accountName, String accountType,
3276 PersistableBundle accountOptions, boolean persist) {
3277 checkManageUsersPermission("Require MANAGE_USERS permission to set user seed data");
3278 synchronized (mPackagesLock) {
3279 final UserData userData;
3280 synchronized (mUsersLock) {
3281 userData = getUserDataLU(userId);
3282 if (userData == null) {
3283 Slog.e(LOG_TAG, "No such user for settings seed data u=" + userId);
3284 return;
3285 }
3286 userData.seedAccountName = accountName;
3287 userData.seedAccountType = accountType;
3288 userData.seedAccountOptions = accountOptions;
3289 userData.persistSeedData = persist;
3290 }
3291 if (persist) {
3292 writeUserLP(userData);
3293 }
3294 }
3295 }
3296
3297 @Override
3298 public String getSeedAccountName() throws RemoteException {
3299 checkManageUsersPermission("Cannot get seed account information");
3300 synchronized (mUsersLock) {
3301 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3302 return userData.seedAccountName;
3303 }
3304 }
3305
3306 @Override
3307 public String getSeedAccountType() throws RemoteException {
3308 checkManageUsersPermission("Cannot get seed account information");
3309 synchronized (mUsersLock) {
3310 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3311 return userData.seedAccountType;
3312 }
3313 }
3314
3315 @Override
3316 public PersistableBundle getSeedAccountOptions() throws RemoteException {
3317 checkManageUsersPermission("Cannot get seed account information");
3318 synchronized (mUsersLock) {
3319 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3320 return userData.seedAccountOptions;
3321 }
3322 }
3323
3324 @Override
3325 public void clearSeedAccountData() throws RemoteException {
3326 checkManageUsersPermission("Cannot clear seed account information");
3327 synchronized (mPackagesLock) {
3328 UserData userData;
3329 synchronized (mUsersLock) {
3330 userData = getUserDataLU(UserHandle.getCallingUserId());
3331 if (userData == null) return;
3332 userData.clearSeedAccountData();
3333 }
3334 writeUserLP(userData);
3335 }
3336 }
3337
3338 @Override
3339 public boolean someUserHasSeedAccount(String accountName, String accountType)
3340 throws RemoteException {
3341 checkManageUsersPermission("Cannot check seed account information");
3342 synchronized (mUsersLock) {
3343 final int userSize = mUsers.size();
3344 for (int i = 0; i < userSize; i++) {
3345 final UserData data = mUsers.valueAt(i);
3346 if (data.info.isInitialized()) continue;
3347 if (data.seedAccountName == null || !data.seedAccountName.equals(accountName)) {
3348 continue;
3349 }
3350 if (data.seedAccountType == null || !data.seedAccountType.equals(accountType)) {
3351 continue;
3352 }
3353 return true;
3354 }
3355 }
3356 return false;
3357 }
3358
3359 @Override
Todd Kennedy60459ab2015-10-30 11:32:16 -07003360 public void onShellCommand(FileDescriptor in, FileDescriptor out,
Dianne Hackborn354736e2016-08-22 17:00:05 -07003361 FileDescriptor err, String[] args, ShellCallback callback,
3362 ResultReceiver resultReceiver) {
3363 (new Shell()).exec(this, in, out, err, args, callback, resultReceiver);
Todd Kennedy60459ab2015-10-30 11:32:16 -07003364 }
3365
3366 int onShellCommand(Shell shell, String cmd) {
3367 if (cmd == null) {
3368 return shell.handleDefaultCommands(cmd);
3369 }
3370
3371 final PrintWriter pw = shell.getOutPrintWriter();
3372 try {
3373 switch(cmd) {
3374 case "list":
3375 return runList(pw);
3376 }
3377 } catch (RemoteException e) {
3378 pw.println("Remote exception: " + e);
3379 }
3380 return -1;
3381 }
3382
3383 private int runList(PrintWriter pw) throws RemoteException {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003384 final IActivityManager am = ActivityManager.getService();
Todd Kennedy60459ab2015-10-30 11:32:16 -07003385 final List<UserInfo> users = getUsers(false);
3386 if (users == null) {
3387 pw.println("Error: couldn't get users");
3388 return 1;
3389 } else {
3390 pw.println("Users:");
3391 for (int i = 0; i < users.size(); i++) {
Jeff Sharkeye17ac152015-11-06 22:40:29 -08003392 String running = am.isUserRunning(users.get(i).id, 0) ? " running" : "";
Todd Kennedy60459ab2015-10-30 11:32:16 -07003393 pw.println("\t" + users.get(i).toString() + running);
3394 }
3395 return 0;
3396 }
3397 }
3398
3399 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -07003400 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06003401 if (!DumpUtils.checkDumpPermission(mContext, LOG_TAG, pw)) return;
Amith Yamasani920ace02012-09-20 22:15:37 -07003402
3403 long now = System.currentTimeMillis();
3404 StringBuilder sb = new StringBuilder();
3405 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003406 synchronized (mUsersLock) {
3407 pw.println("Users:");
3408 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003409 UserData userData = mUsers.valueAt(i);
3410 if (userData == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003411 continue;
3412 }
Amith Yamasani12747872015-12-07 14:19:49 -08003413 UserInfo userInfo = userData.info;
3414 final int userId = userInfo.id;
3415 pw.print(" "); pw.print(userInfo);
3416 pw.print(" serialNo="); pw.print(userInfo.serialNumber);
Makoto Onukie7927da2015-11-25 10:05:17 -08003417 if (mRemovingUserIds.get(userId)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003418 pw.print(" <removing> ");
3419 }
Amith Yamasani12747872015-12-07 14:19:49 -08003420 if (userInfo.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003421 pw.print(" <partial>");
3422 }
3423 pw.println();
Makoto Onuki88aef752017-03-29 16:52:03 -07003424 pw.print(" State: ");
3425 final int state;
3426 synchronized (mUserStates) {
3427 state = mUserStates.get(userId, -1);
3428 }
3429 pw.println(UserState.stateToString(state));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003430 pw.print(" Created: ");
Amith Yamasani12747872015-12-07 14:19:49 -08003431 if (userInfo.creationTime == 0) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003432 pw.println("<unknown>");
3433 } else {
3434 sb.setLength(0);
Amith Yamasani12747872015-12-07 14:19:49 -08003435 TimeUtils.formatDuration(now - userInfo.creationTime, sb);
Fyodor Kupolov82402752015-10-28 14:54:51 -07003436 sb.append(" ago");
3437 pw.println(sb);
3438 }
3439 pw.print(" Last logged in: ");
Amith Yamasani12747872015-12-07 14:19:49 -08003440 if (userInfo.lastLoggedInTime == 0) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003441 pw.println("<unknown>");
3442 } else {
3443 sb.setLength(0);
Amith Yamasani12747872015-12-07 14:19:49 -08003444 TimeUtils.formatDuration(now - userInfo.lastLoggedInTime, sb);
Fyodor Kupolov82402752015-10-28 14:54:51 -07003445 sb.append(" ago");
3446 pw.println(sb);
3447 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003448 pw.print(" Last logged in fingerprint: ");
3449 pw.println(userInfo.lastLoggedInFingerprint);
Makoto Onukie7927da2015-11-25 10:05:17 -08003450 pw.print(" Has profile owner: ");
3451 pw.println(mIsUserManaged.get(userId));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003452 pw.println(" Restrictions:");
3453 synchronized (mRestrictionsLock) {
3454 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003455 pw, " ", mBaseUserRestrictions.get(userInfo.id));
Pavel Grafov6a40f092016-10-25 15:46:51 +01003456 pw.println(" Device policy global restrictions:");
3457 UserRestrictionsUtils.dumpRestrictions(
3458 pw, " ", mDevicePolicyGlobalUserRestrictions.get(userInfo.id));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003459 pw.println(" Device policy local restrictions:");
3460 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003461 pw, " ", mDevicePolicyLocalUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003462 pw.println(" Effective restrictions:");
3463 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003464 pw, " ", mCachedEffectiveUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003465 }
Amith Yamasani12747872015-12-07 14:19:49 -08003466
3467 if (userData.account != null) {
3468 pw.print(" Account name: " + userData.account);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08003469 pw.println();
3470 }
Amith Yamasani12747872015-12-07 14:19:49 -08003471
3472 if (userData.seedAccountName != null) {
3473 pw.print(" Seed account name: " + userData.seedAccountName);
3474 pw.println();
3475 if (userData.seedAccountType != null) {
3476 pw.print(" account type: " + userData.seedAccountType);
3477 pw.println();
3478 }
3479 if (userData.seedAccountOptions != null) {
3480 pw.print(" account options exist");
3481 pw.println();
3482 }
3483 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003484 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003485 }
Amith Yamasani12747872015-12-07 14:19:49 -08003486 pw.println();
Pavel Grafov6a40f092016-10-25 15:46:51 +01003487 pw.println(" Device owner id:" + mDeviceOwnerUserId);
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01003488 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003489 pw.println(" Guest restrictions:");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003490 synchronized (mGuestRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003491 UserRestrictionsUtils.dumpRestrictions(pw, " ", mGuestRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003492 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003493 synchronized (mUsersLock) {
3494 pw.println();
3495 pw.println(" Device managed: " + mIsDeviceManaged);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003496 if (mRemovingUserIds.size() > 0) {
3497 pw.println();
3498 pw.println(" Recently removed userIds: " + mRecentlyRemovedIds);
3499 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003500 }
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003501 synchronized (mUserStates) {
3502 pw.println(" Started users state: " + mUserStates);
3503 }
Amith Yamasani12747872015-12-07 14:19:49 -08003504 // Dump some capabilities
3505 pw.println();
3506 pw.println(" Max users: " + UserManager.getMaxSupportedUsers());
3507 pw.println(" Supports switchable users: " + UserManager.supportsMultipleUsers());
Lenka Trochtova02fee152015-12-22 14:26:18 +01003508 pw.println(" All guests ephemeral: " + Resources.getSystem().getBoolean(
3509 com.android.internal.R.bool.config_guestUserEphemeral));
Amith Yamasani920ace02012-09-20 22:15:37 -07003510 }
3511 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08003512
3513 final class MainHandler extends Handler {
3514
3515 @Override
3516 public void handleMessage(Message msg) {
3517 switch (msg.what) {
3518 case WRITE_USER_MSG:
3519 removeMessages(WRITE_USER_MSG, msg.obj);
3520 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08003521 int userId = ((UserData) msg.obj).info.id;
3522 UserData userData = getUserDataNoChecks(userId);
3523 if (userData != null) {
3524 writeUserLP(userData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08003525 }
3526 }
3527 }
3528 }
3529 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07003530
3531 /**
3532 * @param userId
3533 * @return whether the user has been initialized yet
3534 */
Todd Kennedy0eb97382017-10-03 16:57:22 -07003535 boolean isUserInitialized(int userId) {
3536 return mLocalService.isUserInitialized(userId);
Amith Yamasanibb054c92015-07-09 14:16:27 -07003537 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003538
3539 private class LocalService extends UserManagerInternal {
Makoto Onuki068c54a2015-10-13 14:34:03 -07003540 @Override
Pavel Grafov6a40f092016-10-25 15:46:51 +01003541 public void setDevicePolicyUserRestrictions(int userId, @Nullable Bundle restrictions,
3542 boolean isDeviceOwner, int cameraRestrictionScope) {
3543 UserManagerService.this.setDevicePolicyUserRestrictionsInner(userId, restrictions,
3544 isDeviceOwner, cameraRestrictionScope);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003545 }
3546
3547 @Override
3548 public Bundle getBaseUserRestrictions(int userId) {
3549 synchronized (mRestrictionsLock) {
3550 return mBaseUserRestrictions.get(userId);
3551 }
3552 }
3553
3554 @Override
3555 public void setBaseUserRestrictionsByDpmsForMigration(
3556 int userId, Bundle baseRestrictions) {
3557 synchronized (mRestrictionsLock) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01003558 if (updateRestrictionsIfNeededLR(
3559 userId, new Bundle(baseRestrictions), mBaseUserRestrictions)) {
3560 invalidateEffectiveUserRestrictionsLR(userId);
3561 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003562 }
3563
Amith Yamasani12747872015-12-07 14:19:49 -08003564 final UserData userData = getUserDataNoChecks(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003565 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08003566 if (userData != null) {
3567 writeUserLP(userData);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003568 } else {
3569 Slog.w(LOG_TAG, "UserInfo not found for " + userId);
3570 }
3571 }
3572 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08003573
3574 @Override
3575 public boolean getUserRestriction(int userId, String key) {
3576 return getUserRestrictions(userId).getBoolean(key);
3577 }
3578
3579 @Override
3580 public void addUserRestrictionsListener(UserRestrictionsListener listener) {
3581 synchronized (mUserRestrictionsListeners) {
3582 mUserRestrictionsListeners.add(listener);
3583 }
3584 }
3585
3586 @Override
3587 public void removeUserRestrictionsListener(UserRestrictionsListener listener) {
3588 synchronized (mUserRestrictionsListeners) {
3589 mUserRestrictionsListeners.remove(listener);
3590 }
3591 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003592
3593 @Override
3594 public void setDeviceManaged(boolean isManaged) {
3595 synchronized (mUsersLock) {
3596 mIsDeviceManaged = isManaged;
3597 }
3598 }
3599
3600 @Override
3601 public void setUserManaged(int userId, boolean isManaged) {
3602 synchronized (mUsersLock) {
3603 mIsUserManaged.put(userId, isManaged);
3604 }
3605 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01003606
3607 @Override
3608 public void setUserIcon(int userId, Bitmap bitmap) {
3609 long ident = Binder.clearCallingIdentity();
3610 try {
3611 synchronized (mPackagesLock) {
3612 UserData userData = getUserDataNoChecks(userId);
3613 if (userData == null || userData.info.partial) {
3614 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
3615 return;
3616 }
3617 writeBitmapLP(userData.info, bitmap);
3618 writeUserLP(userData);
3619 }
3620 sendUserInfoChangedBroadcast(userId);
3621 } finally {
3622 Binder.restoreCallingIdentity(ident);
3623 }
3624 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01003625
3626 @Override
3627 public void setForceEphemeralUsers(boolean forceEphemeralUsers) {
3628 synchronized (mUsersLock) {
3629 mForceEphemeralUsers = forceEphemeralUsers;
3630 }
3631 }
3632
3633 @Override
3634 public void removeAllUsers() {
3635 if (UserHandle.USER_SYSTEM == ActivityManager.getCurrentUser()) {
3636 // Remove the non-system users straight away.
3637 removeNonSystemUsers();
3638 } else {
3639 // Switch to the system user first and then remove the other users.
3640 BroadcastReceiver userSwitchedReceiver = new BroadcastReceiver() {
3641 @Override
3642 public void onReceive(Context context, Intent intent) {
3643 int userId =
3644 intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3645 if (userId != UserHandle.USER_SYSTEM) {
3646 return;
3647 }
3648 mContext.unregisterReceiver(this);
3649 removeNonSystemUsers();
3650 }
3651 };
3652 IntentFilter userSwitchedFilter = new IntentFilter();
3653 userSwitchedFilter.addAction(Intent.ACTION_USER_SWITCHED);
3654 mContext.registerReceiver(
3655 userSwitchedReceiver, userSwitchedFilter, null, mHandler);
3656
3657 // Switch to the system user.
3658 ActivityManager am =
3659 (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
3660 am.switchUser(UserHandle.USER_SYSTEM);
3661 }
3662 }
phweisse9c44062016-02-10 12:57:38 +01003663
3664 @Override
Lenka Trochtova1ddda472016-02-12 10:42:12 +01003665 public void onEphemeralUserStop(int userId) {
3666 synchronized (mUsersLock) {
3667 UserInfo userInfo = getUserInfoLU(userId);
3668 if (userInfo != null && userInfo.isEphemeral()) {
3669 // Do not allow switching back to the ephemeral user again as the user is going
3670 // to be deleted.
3671 userInfo.flags |= UserInfo.FLAG_DISABLED;
3672 if (userInfo.isGuest()) {
3673 // Indicate that the guest will be deleted after it stops.
3674 userInfo.guestToRemove = true;
3675 }
3676 }
3677 }
3678 }
3679
3680 @Override
phweisse9c44062016-02-10 12:57:38 +01003681 public UserInfo createUserEvenWhenDisallowed(String name, int flags) {
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07003682 UserInfo user = createUserInternalUnchecked(name, flags, UserHandle.USER_NULL, null);
phweisse9c44062016-02-10 12:57:38 +01003683 // Keep this in sync with UserManager.createUser
Christine Franks97a54802017-08-09 10:06:43 -07003684 if (user != null && !user.isAdmin() && !user.isDemo()) {
phweisse9c44062016-02-10 12:57:38 +01003685 setUserRestriction(UserManager.DISALLOW_SMS, true, user.id);
3686 setUserRestriction(UserManager.DISALLOW_OUTGOING_CALLS, true, user.id);
3687 }
3688 return user;
3689 }
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003690
3691 @Override
Nicolas Prevotdf1b87d2016-10-25 13:57:08 +01003692 public boolean removeUserEvenWhenDisallowed(int userId) {
3693 return removeUserUnchecked(userId);
3694 }
3695
3696 @Override
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003697 public boolean isUserRunning(int userId) {
3698 synchronized (mUserStates) {
3699 return mUserStates.get(userId, -1) >= 0;
3700 }
3701 }
3702
3703 @Override
3704 public void setUserState(int userId, int userState) {
3705 synchronized (mUserStates) {
3706 mUserStates.put(userId, userState);
3707 }
3708 }
3709
3710 @Override
3711 public void removeUserState(int userId) {
3712 synchronized (mUserStates) {
3713 mUserStates.delete(userId);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003714 }
3715 }
3716
3717 @Override
Michael Wachenschwanz3f2b6552017-05-15 13:53:09 -07003718 public int[] getUserIds() {
3719 return UserManagerService.this.getUserIds();
3720 }
3721
3722 @Override
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003723 public boolean isUserUnlockingOrUnlocked(int userId) {
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07003724 int state;
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003725 synchronized (mUserStates) {
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07003726 state = mUserStates.get(userId, -1);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003727 }
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07003728 // Special case, in the stopping/shutdown state user key can still be unlocked
3729 if (state == UserState.STATE_STOPPING || state == UserState.STATE_SHUTDOWN) {
3730 return StorageManager.isUserKeyUnlocked(userId);
3731 }
3732 return (state == UserState.STATE_RUNNING_UNLOCKING)
3733 || (state == UserState.STATE_RUNNING_UNLOCKED);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003734 }
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08003735
3736 @Override
3737 public boolean isUserUnlocked(int userId) {
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07003738 int state;
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08003739 synchronized (mUserStates) {
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07003740 state = mUserStates.get(userId, -1);
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08003741 }
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07003742 // Special case, in the stopping/shutdown state user key can still be unlocked
3743 if (state == UserState.STATE_STOPPING || state == UserState.STATE_SHUTDOWN) {
3744 return StorageManager.isUserKeyUnlocked(userId);
3745 }
3746 return state == UserState.STATE_RUNNING_UNLOCKED;
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08003747 }
Todd Kennedy0eb97382017-10-03 16:57:22 -07003748
3749 @Override
3750 public boolean isUserInitialized(int userId) {
3751 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
3752 }
3753
3754 @Override
3755 public boolean exists(int userId) {
3756 return getUserInfoNoChecks(userId) != null;
3757 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01003758 }
3759
3760 /* Remove all the users except of the system one. */
3761 private void removeNonSystemUsers() {
3762 ArrayList<UserInfo> usersToRemove = new ArrayList<>();
3763 synchronized (mUsersLock) {
3764 final int userSize = mUsers.size();
3765 for (int i = 0; i < userSize; i++) {
3766 UserInfo ui = mUsers.valueAt(i).info;
3767 if (ui.id != UserHandle.USER_SYSTEM) {
3768 usersToRemove.add(ui);
3769 }
3770 }
3771 }
3772 for (UserInfo ui: usersToRemove) {
3773 removeUser(ui.id);
3774 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003775 }
Todd Kennedy60459ab2015-10-30 11:32:16 -07003776
3777 private class Shell extends ShellCommand {
3778 @Override
3779 public int onCommand(String cmd) {
3780 return onShellCommand(this, cmd);
3781 }
3782
3783 @Override
3784 public void onHelp() {
3785 final PrintWriter pw = getOutPrintWriter();
3786 pw.println("User manager (user) commands:");
3787 pw.println(" help");
3788 pw.println(" Print this help text.");
3789 pw.println("");
3790 pw.println(" list");
3791 pw.println(" Prints all users on the system.");
3792 }
3793 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003794
3795 private static void debug(String message) {
3796 Log.d(LOG_TAG, message +
3797 (DBG_WITH_STACKTRACE ? " called at\n" + Debug.getCallers(10, " ") : ""));
3798 }
Kenny Guy02c89902016-11-15 19:36:38 +00003799
3800 @VisibleForTesting
3801 static int getMaxManagedProfiles() {
3802 // Allow overriding max managed profiles on debuggable builds for testing
3803 // of multiple profiles.
3804 if (!Build.IS_DEBUGGABLE) {
3805 return MAX_MANAGED_PROFILES;
3806 } else {
3807 return SystemProperties.getInt("persist.sys.max_profiles",
3808 MAX_MANAGED_PROFILES);
3809 }
3810 }
3811
3812 @VisibleForTesting
3813 int getFreeProfileBadgeLU(int parentUserId) {
3814 int maxManagedProfiles = getMaxManagedProfiles();
3815 boolean[] usedBadges = new boolean[maxManagedProfiles];
3816 final int userSize = mUsers.size();
3817 for (int i = 0; i < userSize; i++) {
3818 UserInfo ui = mUsers.valueAt(i).info;
3819 // Check which badge indexes are already used by this profile group.
3820 if (ui.isManagedProfile()
3821 && ui.profileGroupId == parentUserId
3822 && !mRemovingUserIds.get(ui.id)
3823 && ui.profileBadge < maxManagedProfiles) {
3824 usedBadges[ui.profileBadge] = true;
3825 }
3826 }
3827 for (int i = 0; i < maxManagedProfiles; i++) {
3828 if (!usedBadges[i]) {
3829 return i;
3830 }
3831 }
3832 return 0;
3833 }
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07003834
3835 /**
3836 * Checks if the given user has a managed profile associated with it.
3837 * @param userId The parent user
3838 * @return
3839 */
3840 boolean hasManagedProfile(int userId) {
3841 synchronized (mUsersLock) {
3842 UserInfo userInfo = getUserInfoLU(userId);
3843 final int userSize = mUsers.size();
3844 for (int i = 0; i < userSize; i++) {
3845 UserInfo profile = mUsers.valueAt(i).info;
3846 if (userId != profile.id && isProfileOf(userInfo, profile)) {
3847 return true;
3848 }
3849 }
3850 return false;
3851 }
3852 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003853}