blob: 62f4a301511d39bfff8d08fed1b32fcdb070e127 [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 Kupolove80085d2015-11-06 18:21:39 -0800131 * <li> Methods suffixed with "LP" should be called within the {@link #mPackagesLock} lock.
Fyodor Kupolov82402752015-10-28 14:54:51 -0700132 * <li> Methods suffixed with "LR" should be called within the {@link #mRestrictionsLock} lock.
133 * <li> Methods suffixed with "LU" should be called within the {@link #mUsersLock} lock.
134 * </ul>
Makoto Onuki068c54a2015-10-13 14:34:03 -0700135 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700136public class UserManagerService extends IUserManager.Stub {
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700137
Amith Yamasani2a003292012-08-14 18:25:45 -0700138 private static final String LOG_TAG = "UserManagerService";
Makoto Onuki81c61ea2016-01-22 11:22:26 -0800139 static final boolean DBG = false; // DO NOT SUBMIT WITH TRUE
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800140 private static final boolean DBG_WITH_STACKTRACE = false; // DO NOT SUBMIT WITH TRUE
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700141 // Can be used for manual testing of id recycling
142 private static final boolean RELEASE_DELETED_USER_ID = false; // DO NOT SUBMIT WITH TRUE
Amith Yamasani16389312012-10-17 21:20:14 -0700143
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700144 private static final String TAG_NAME = "name";
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800145 private static final String TAG_ACCOUNT = "account";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700146 private static final String ATTR_FLAGS = "flags";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700147 private static final String ATTR_ICON_PATH = "icon";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700148 private static final String ATTR_ID = "id";
Amith Yamasani920ace02012-09-20 22:15:37 -0700149 private static final String ATTR_CREATION_TIME = "created";
150 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -0600151 private static final String ATTR_LAST_LOGGED_IN_FINGERPRINT = "lastLoggedInFingerprint";
Amith Yamasani2a003292012-08-14 18:25:45 -0700152 private static final String ATTR_SERIAL_NO = "serialNumber";
153 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700154 private static final String ATTR_PARTIAL = "partial";
Adam Lesinskieddeb492014-09-08 17:50:03 -0700155 private static final String ATTR_GUEST_TO_REMOVE = "guestToRemove";
Amith Yamasani6f34b412012-10-22 18:19:27 -0700156 private static final String ATTR_USER_VERSION = "version";
Kenny Guy2a764942014-04-02 13:29:20 +0100157 private static final String ATTR_PROFILE_GROUP_ID = "profileGroupId";
Kenny Guy02c89902016-11-15 19:36:38 +0000158 private static final String ATTR_PROFILE_BADGE = "profileBadge";
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700159 private static final String ATTR_RESTRICTED_PROFILE_PARENT_ID = "restrictedProfileParentId";
Amith Yamasani12747872015-12-07 14:19:49 -0800160 private static final String ATTR_SEED_ACCOUNT_NAME = "seedAccountName";
161 private static final String ATTR_SEED_ACCOUNT_TYPE = "seedAccountType";
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530162 private static final String TAG_GUEST_RESTRICTIONS = "guestRestrictions";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700163 private static final String TAG_USERS = "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700164 private static final String TAG_USER = "user";
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800165 private static final String TAG_RESTRICTIONS = "restrictions";
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800166 private static final String TAG_DEVICE_POLICY_RESTRICTIONS = "device_policy_restrictions";
Pavel Grafov6a40f092016-10-25 15:46:51 +0100167 private static final String TAG_DEVICE_POLICY_GLOBAL_RESTRICTIONS =
168 "device_policy_global_restrictions";
169 /** Legacy name for device owner id tag. */
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +0100170 private static final String TAG_GLOBAL_RESTRICTION_OWNER_ID = "globalRestrictionOwnerUserId";
Pavel Grafov6a40f092016-10-25 15:46:51 +0100171 private static final String TAG_DEVICE_OWNER_USER_ID = "deviceOwnerUserId";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800172 private static final String TAG_ENTRY = "entry";
173 private static final String TAG_VALUE = "value";
Amith Yamasani12747872015-12-07 14:19:49 -0800174 private static final String TAG_SEED_ACCOUNT_OPTIONS = "seedAccountOptions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800175 private static final String ATTR_KEY = "key";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700176 private static final String ATTR_VALUE_TYPE = "type";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800177 private static final String ATTR_MULTIPLE = "m";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700178
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700179 private static final String ATTR_TYPE_STRING_ARRAY = "sa";
180 private static final String ATTR_TYPE_STRING = "s";
181 private static final String ATTR_TYPE_BOOLEAN = "b";
Amith Yamasani5b5aa402014-06-01 20:10:14 -0700182 private static final String ATTR_TYPE_INTEGER = "i";
Fyodor Kupolov262f9952015-03-23 18:55:11 -0700183 private static final String ATTR_TYPE_BUNDLE = "B";
184 private static final String ATTR_TYPE_BUNDLE_ARRAY = "BA";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700185
Amith Yamasani0b285492011-04-14 17:35:23 -0700186 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700187 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700188 private static final String USER_PHOTO_FILENAME = "photo.png";
Adrian Roos1bdff912015-02-17 15:51:35 +0100189 private static final String USER_PHOTO_FILENAME_TMP = USER_PHOTO_FILENAME + ".tmp";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700190
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800191 private static final String RESTRICTIONS_FILE_PREFIX = "res_";
Amith Yamasanifc95e702013-09-26 13:20:17 -0700192 private static final String XML_SUFFIX = ".xml";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800193
Sudheer Shankaf5cea032016-06-08 17:13:24 -0700194 private static final int ALLOWED_FLAGS_FOR_CREATE_USERS_PERMISSION =
195 UserInfo.FLAG_MANAGED_PROFILE
196 | UserInfo.FLAG_EPHEMERAL
197 | UserInfo.FLAG_RESTRICTED
Sudheer Shanka234d1af2016-08-26 15:42:53 -0700198 | UserInfo.FLAG_GUEST
199 | UserInfo.FLAG_DEMO;
Sudheer Shankaf5cea032016-06-08 17:13:24 -0700200
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700201 @VisibleForTesting
202 static final int MIN_USER_ID = 10;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700203 // We need to keep process uid within Integer.MAX_VALUE.
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700204 @VisibleForTesting
205 static final int MAX_USER_ID = Integer.MAX_VALUE / UserHandle.PER_USER_RANGE;
206
207 // Max size of the queue of recently removed users
208 @VisibleForTesting
209 static final int MAX_RECENTLY_REMOVED_IDS_SIZE = 100;
Amith Yamasani634cf312012-10-04 17:34:21 -0700210
Pavel Grafov6a40f092016-10-25 15:46:51 +0100211 private static final int USER_VERSION = 7;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700212
Amith Yamasani920ace02012-09-20 22:15:37 -0700213 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
214
Nicolas Prevotb8186812015-08-06 15:00:03 +0100215 // Maximum number of managed profiles permitted per user is 1. This cannot be increased
Amith Yamasani95ab7842014-08-11 17:09:26 -0700216 // without first making sure that the rest of the framework is prepared for it.
Kenny Guy02c89902016-11-15 19:36:38 +0000217 @VisibleForTesting
218 static final int MAX_MANAGED_PROFILES = 1;
Amith Yamasani95ab7842014-08-11 17:09:26 -0700219
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800220 static final int WRITE_USER_MSG = 1;
221 static final int WRITE_USER_DELAY = 2*1000; // 2 seconds
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530222
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -0800223 // Tron counters
224 private static final String TRON_GUEST_CREATED = "users_guest_created";
225 private static final String TRON_USER_CREATED = "users_user_created";
Christine Franks88220562017-05-24 11:11:21 -0700226 private static final String TRON_DEMO_CREATED = "users_demo_created";
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -0800227
Dianne Hackborn4428e172012-08-24 17:43:05 -0700228 private final Context mContext;
229 private final PackageManagerService mPm;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700230 private final Object mPackagesLock;
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800231 private final UserDataPreparer mUserDataPreparer;
Fyodor Kupolov82402752015-10-28 14:54:51 -0700232 // Short-term lock for internal state, when interaction/sync with PM is not required
Jeff Sharkey5f3e9342017-03-13 14:53:11 -0600233 private final Object mUsersLock = LockGuard.installNewLock(LockGuard.INDEX_USER);
Fyodor Kupolov82402752015-10-28 14:54:51 -0700234 private final Object mRestrictionsLock = new Object();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700235
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800236 private final Handler mHandler;
237
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700238 private final File mUsersDir;
239 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700240
Svet Ganov9cea80cd2016-02-16 11:47:00 -0800241 private static final IBinder mUserRestriconToken = new Binder();
242
Makoto Onuki068c54a2015-10-13 14:34:03 -0700243 /**
Amith Yamasani12747872015-12-07 14:19:49 -0800244 * User-related information that is used for persisting to flash. Only UserInfo is
245 * directly exposed to other system apps.
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800246 */
Kenny Guy02c89902016-11-15 19:36:38 +0000247 @VisibleForTesting
248 static class UserData {
Amith Yamasani12747872015-12-07 14:19:49 -0800249 // Basic user information and properties
250 UserInfo info;
251 // Account name used when there is a strong association between a user and an account
252 String account;
253 // Account information for seeding into a newly created user. This could also be
254 // used for login validation for an existing user, for updating their credentials.
255 // In the latter case, data may not need to be persisted as it is only valid for the
256 // current login session.
257 String seedAccountName;
258 String seedAccountType;
259 PersistableBundle seedAccountOptions;
260 // Whether to perist the seed account information to be available after a boot
261 boolean persistSeedData;
262
263 void clearSeedAccountData() {
264 seedAccountName = null;
265 seedAccountType = null;
266 seedAccountOptions = null;
267 persistSeedData = false;
268 }
269 }
270
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800271 @GuardedBy("mUsersLock")
Amith Yamasani12747872015-12-07 14:19:49 -0800272 private final SparseArray<UserData> mUsers = new SparseArray<>();
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800273
274 /**
Makoto Onuki068c54a2015-10-13 14:34:03 -0700275 * User restrictions set via UserManager. This doesn't include restrictions set by
Pavel Grafov6a40f092016-10-25 15:46:51 +0100276 * device owner / profile owners. Only non-empty restriction bundles are stored.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700277 *
278 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
279 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
280 * maybe shared between {@link #mBaseUserRestrictions} and
281 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
282 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700283 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700284 */
285 @GuardedBy("mRestrictionsLock")
286 private final SparseArray<Bundle> mBaseUserRestrictions = new SparseArray<>();
287
288 /**
289 * Cached user restrictions that are in effect -- i.e. {@link #mBaseUserRestrictions} combined
290 * with device / profile owner restrictions. We'll initialize it lazily; use
291 * {@link #getEffectiveUserRestrictions} to access it.
292 *
293 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
294 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
295 * maybe shared between {@link #mBaseUserRestrictions} and
296 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
297 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700298 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700299 */
300 @GuardedBy("mRestrictionsLock")
301 private final SparseArray<Bundle> mCachedEffectiveUserRestrictions = new SparseArray<>();
302
Makoto Onuki4f160732015-10-27 17:15:38 -0700303 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800304 * User restrictions that have already been applied in
305 * {@link #updateUserRestrictionsInternalLR(Bundle, int)}. We use it to detect restrictions
306 * that have changed since the last
307 * {@link #updateUserRestrictionsInternalLR(Bundle, int)} call.
Makoto Onuki4f160732015-10-27 17:15:38 -0700308 */
309 @GuardedBy("mRestrictionsLock")
310 private final SparseArray<Bundle> mAppliedUserRestrictions = new SparseArray<>();
311
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800312 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800313 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
Pavel Grafov6a40f092016-10-25 15:46:51 +0100314 * that should be applied to all users, including guests. Only non-empty restriction bundles are
315 * stored.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800316 */
317 @GuardedBy("mRestrictionsLock")
Pavel Grafov6a40f092016-10-25 15:46:51 +0100318 private final SparseArray<Bundle> mDevicePolicyGlobalUserRestrictions = new SparseArray<>();
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800319
320 /**
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +0100321 * Id of the user that set global restrictions.
322 */
323 @GuardedBy("mRestrictionsLock")
Pavel Grafov6a40f092016-10-25 15:46:51 +0100324 private int mDeviceOwnerUserId = UserHandle.USER_NULL;
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +0100325
326 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800327 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
Pavel Grafov6a40f092016-10-25 15:46:51 +0100328 * for each user. Only non-empty restriction bundles are stored.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800329 */
330 @GuardedBy("mRestrictionsLock")
331 private final SparseArray<Bundle> mDevicePolicyLocalUserRestrictions = new SparseArray<>();
332
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800333 @GuardedBy("mGuestRestrictions")
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530334 private final Bundle mGuestRestrictions = new Bundle();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800335
336 /**
337 * Set of user IDs being actively removed. Removed IDs linger in this set
338 * for several seconds to work around a VFS caching issue.
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700339 * Use {@link #addRemovingUserIdLocked(int)} to add elements to this array
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800340 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700341 @GuardedBy("mUsersLock")
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800342 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700343
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700344 /**
345 * Queue of recently removed userIds. Used for recycling of userIds
346 */
347 @GuardedBy("mUsersLock")
348 private final LinkedList<Integer> mRecentlyRemovedIds = new LinkedList<>();
349
Fyodor Kupolov82402752015-10-28 14:54:51 -0700350 @GuardedBy("mUsersLock")
Amith Yamasani0b285492011-04-14 17:35:23 -0700351 private int[] mUserIds;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800352 @GuardedBy("mPackagesLock")
Amith Yamasani2a003292012-08-14 18:25:45 -0700353 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700354 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700355
Jason Monk62062992014-05-06 09:55:28 -0400356 private IAppOpsService mAppOpsService;
357
Makoto Onuki068c54a2015-10-13 14:34:03 -0700358 private final LocalService mLocalService;
359
Makoto Onukie7927da2015-11-25 10:05:17 -0800360 @GuardedBy("mUsersLock")
361 private boolean mIsDeviceManaged;
362
363 @GuardedBy("mUsersLock")
364 private final SparseBooleanArray mIsUserManaged = new SparseBooleanArray();
365
Makoto Onukid45a4a22015-11-02 17:17:38 -0800366 @GuardedBy("mUserRestrictionsListeners")
367 private final ArrayList<UserRestrictionsListener> mUserRestrictionsListeners =
368 new ArrayList<>();
369
Clara Bayarria1771112015-12-18 16:29:18 +0000370 private final LockPatternUtils mLockPatternUtils;
371
Ricky Waib1dd80b2016-06-07 18:00:55 +0100372 private final String ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK =
373 "com.android.server.pm.DISABLE_QUIET_MODE_AFTER_UNLOCK";
374
375 private final BroadcastReceiver mDisableQuietModeCallback = new BroadcastReceiver() {
376 @Override
377 public void onReceive(Context context, Intent intent) {
378 if (ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK.equals(intent.getAction())) {
379 final IntentSender target = intent.getParcelableExtra(Intent.EXTRA_INTENT);
380 final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_ID, 0);
381 setQuietModeEnabled(userHandle, false);
382 if (target != null) {
383 try {
384 mContext.startIntentSender(target, null, 0, 0, 0);
385 } catch (IntentSender.SendIntentException e) {
386 /* ignore */
387 }
388 }
389 }
390 }
391 };
392
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +0100393 /**
394 * Whether all users should be created ephemeral.
395 */
396 @GuardedBy("mUsersLock")
397 private boolean mForceEphemeralUsers;
398
Amith Yamasaniea1b9d72016-05-27 15:57:38 +0000399 @GuardedBy("mUserStates")
400 private final SparseIntArray mUserStates = new SparseIntArray();
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -0700401
Amith Yamasani258848d2012-08-10 17:06:33 -0700402 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700403
Dianne Hackborn4428e172012-08-24 17:43:05 -0700404 public static UserManagerService getInstance() {
405 synchronized (UserManagerService.class) {
406 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700407 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700408 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700409
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700410 public static class LifeCycle extends SystemService {
411
412 private UserManagerService mUms;
413
414 /**
415 * @param context
416 */
417 public LifeCycle(Context context) {
418 super(context);
419 }
420
421 @Override
422 public void onStart() {
423 mUms = UserManagerService.getInstance();
424 publishBinderService(Context.USER_SERVICE, mUms);
425 }
426
427 @Override
428 public void onBootPhase(int phase) {
429 if (phase == SystemService.PHASE_ACTIVITY_MANAGER_READY) {
430 mUms.cleanupPartialUsers();
431 }
432 }
433 }
434
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700435 // TODO b/28848102 Add support for test dependencies injection
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800436 @VisibleForTesting
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700437 UserManagerService(Context context) {
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800438 this(context, null, null, new Object(), context.getCacheDir());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700439 }
440
Dianne Hackborn4428e172012-08-24 17:43:05 -0700441 /**
442 * Called by package manager to create the service. This is closely
443 * associated with the package manager, and the given lock is the
444 * package manager's own lock.
445 */
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800446 UserManagerService(Context context, PackageManagerService pm, UserDataPreparer userDataPreparer,
447 Object packagesLock) {
448 this(context, pm, userDataPreparer, packagesLock, Environment.getDataDirectory());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700449 }
450
Dianne Hackborn4428e172012-08-24 17:43:05 -0700451 private UserManagerService(Context context, PackageManagerService pm,
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800452 UserDataPreparer userDataPreparer, Object packagesLock, File dataDir) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700453 mContext = context;
454 mPm = pm;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700455 mPackagesLock = packagesLock;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800456 mHandler = new MainHandler();
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800457 mUserDataPreparer = userDataPreparer;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800458 synchronized (mPackagesLock) {
459 mUsersDir = new File(dataDir, USER_INFO_DIR);
460 mUsersDir.mkdirs();
461 // Make zeroth user directory, for services to migrate their files to that location
462 File userZeroDir = new File(mUsersDir, String.valueOf(UserHandle.USER_SYSTEM));
463 userZeroDir.mkdirs();
464 FileUtils.setPermissions(mUsersDir.toString(),
465 FileUtils.S_IRWXU | FileUtils.S_IRWXG | FileUtils.S_IROTH | FileUtils.S_IXOTH,
466 -1, -1);
467 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
468 initDefaultGuestRestrictions();
469 readUserListLP();
470 sInstance = this;
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700471 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700472 mLocalService = new LocalService();
473 LocalServices.addService(UserManagerInternal.class, mLocalService);
Clara Bayarria1771112015-12-18 16:29:18 +0000474 mLockPatternUtils = new LockPatternUtils(mContext);
Amith Yamasaniea1b9d72016-05-27 15:57:38 +0000475 mUserStates.put(UserHandle.USER_SYSTEM, UserState.STATE_BOOTING);
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700476 }
477
478 void systemReady() {
Jason Monk62062992014-05-06 09:55:28 -0400479 mAppOpsService = IAppOpsService.Stub.asInterface(
480 ServiceManager.getService(Context.APP_OPS_SERVICE));
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800481
482 synchronized (mRestrictionsLock) {
483 applyUserRestrictionsLR(UserHandle.USER_SYSTEM);
Jason Monk62062992014-05-06 09:55:28 -0400484 }
Samuel Tand9453b82016-03-14 15:57:02 -0700485
486 UserInfo currentGuestUser = findCurrentGuestUser();
487 if (currentGuestUser != null && !hasUserRestriction(
488 UserManager.DISALLOW_CONFIG_WIFI, currentGuestUser.id)) {
489 // If a guest user currently exists, apply the DISALLOW_CONFIG_WIFI option
490 // to it, in case this guest was created in a previous version where this
491 // user restriction was not a default guest restriction.
492 setUserRestriction(UserManager.DISALLOW_CONFIG_WIFI, true, currentGuestUser.id);
493 }
Amith Yamasanieb437d42016-04-29 09:31:25 -0700494
Ricky Waib1dd80b2016-06-07 18:00:55 +0100495 mContext.registerReceiver(mDisableQuietModeCallback,
496 new IntentFilter(ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK),
497 null, mHandler);
Amith Yamasani258848d2012-08-10 17:06:33 -0700498 }
499
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700500 void cleanupPartialUsers() {
501 // Prune out any partially created, partially removed and ephemeral users.
502 ArrayList<UserInfo> partials = new ArrayList<>();
503 synchronized (mUsersLock) {
504 final int userSize = mUsers.size();
505 for (int i = 0; i < userSize; i++) {
506 UserInfo ui = mUsers.valueAt(i).info;
507 if ((ui.partial || ui.guestToRemove || ui.isEphemeral()) && i != 0) {
508 partials.add(ui);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700509 addRemovingUserIdLocked(ui.id);
Amith Yamasaniae261892016-06-27 10:40:09 -0700510 ui.partial = true;
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700511 }
512 }
513 }
514 final int partialsSize = partials.size();
515 for (int i = 0; i < partialsSize; i++) {
516 UserInfo ui = partials.get(i);
517 Slog.w(LOG_TAG, "Removing partially created user " + ui.id
518 + " (name=" + ui.name + ")");
519 removeUserState(ui.id);
520 }
521 }
522
Amith Yamasani258848d2012-08-10 17:06:33 -0700523 @Override
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800524 public String getUserAccount(int userId) {
525 checkManageUserAndAcrossUsersFullPermission("get user account");
526 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800527 return mUsers.get(userId).account;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800528 }
529 }
530
531 @Override
532 public void setUserAccount(int userId, String accountName) {
533 checkManageUserAndAcrossUsersFullPermission("set user account");
Amith Yamasani12747872015-12-07 14:19:49 -0800534 UserData userToUpdate = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800535 synchronized (mPackagesLock) {
536 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800537 final UserData userData = mUsers.get(userId);
538 if (userData == null) {
539 Slog.e(LOG_TAG, "User not found for setting user account: u" + userId);
540 return;
541 }
542 String currentAccount = userData.account;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800543 if (!Objects.equal(currentAccount, accountName)) {
Amith Yamasani12747872015-12-07 14:19:49 -0800544 userData.account = accountName;
545 userToUpdate = userData;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800546 }
547 }
548
549 if (userToUpdate != null) {
550 writeUserLP(userToUpdate);
551 }
552 }
553 }
554
555 @Override
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700556 public UserInfo getPrimaryUser() {
557 checkManageUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700558 synchronized (mUsersLock) {
Amith Yamasani515d4062015-09-28 11:30:06 -0700559 final int userSize = mUsers.size();
560 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800561 UserInfo ui = mUsers.valueAt(i).info;
Xiaohui Chend3e9e182015-11-18 13:37:32 -0800562 if (ui.isPrimary() && !mRemovingUserIds.get(ui.id)) {
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700563 return ui;
564 }
565 }
566 }
567 return null;
568 }
569
570 @Override
Xiaohui Chen594f2082015-08-18 11:04:20 -0700571 public @NonNull List<UserInfo> getUsers(boolean excludeDying) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -0700572 checkManageOrCreateUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700573 synchronized (mUsersLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700574 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasani515d4062015-09-28 11:30:06 -0700575 final int userSize = mUsers.size();
576 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800577 UserInfo ui = mUsers.valueAt(i).info;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700578 if (ui.partial) {
579 continue;
580 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800581 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Amith Yamasani6f48d6e2016-03-23 14:28:25 -0700582 users.add(userWithName(ui));
Amith Yamasani920ace02012-09-20 22:15:37 -0700583 }
Amith Yamasani13593602012-03-22 16:16:17 -0700584 }
585 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700586 }
Amith Yamasani13593602012-03-22 16:16:17 -0700587 }
588
Amith Yamasani258848d2012-08-10 17:06:33 -0700589 @Override
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100590 public List<UserInfo> getProfiles(int userId, boolean enabledOnly) {
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700591 boolean returnFullInfo = true;
Amith Yamasani4f582632014-02-19 14:31:52 -0800592 if (userId != UserHandle.getCallingUserId()) {
Sudheer Shanka74680912016-07-29 11:03:37 -0700593 checkManageOrCreateUsersPermission("getting profiles related to user " + userId);
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700594 } else {
595 returnFullInfo = hasManageUsersPermission();
Amith Yamasani4f582632014-02-19 14:31:52 -0800596 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700597 final long ident = Binder.clearCallingIdentity();
598 try {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700599 synchronized (mUsersLock) {
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700600 return getProfilesLU(userId, enabledOnly, returnFullInfo);
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100601 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700602 } finally {
603 Binder.restoreCallingIdentity(ident);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000604 }
605 }
606
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700607 @Override
608 public int[] getProfileIds(int userId, boolean enabledOnly) {
609 if (userId != UserHandle.getCallingUserId()) {
bohu12d23a12016-09-26 16:20:07 -0700610 checkManageOrCreateUsersPermission("getting profiles related to user " + userId);
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700611 }
612 final long ident = Binder.clearCallingIdentity();
613 try {
614 synchronized (mUsersLock) {
615 return getProfileIdsLU(userId, enabledOnly).toArray();
616 }
617 } finally {
618 Binder.restoreCallingIdentity(ident);
619 }
620 }
621
Amith Yamasanibe465322014-04-24 13:45:17 -0700622 /** Assume permissions already checked and caller's identity cleared */
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700623 private List<UserInfo> getProfilesLU(int userId, boolean enabledOnly, boolean fullInfo) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700624 IntArray profileIds = getProfileIdsLU(userId, enabledOnly);
625 ArrayList<UserInfo> users = new ArrayList<>(profileIds.size());
626 for (int i = 0; i < profileIds.size(); i++) {
627 int profileId = profileIds.get(i);
628 UserInfo userInfo = mUsers.get(profileId).info;
629 // If full info is not required - clear PII data to prevent 3P apps from reading it
630 if (!fullInfo) {
631 userInfo = new UserInfo(userInfo);
632 userInfo.name = null;
633 userInfo.iconPath = null;
634 } else {
635 userInfo = userWithName(userInfo);
636 }
637 users.add(userInfo);
638 }
639 return users;
640 }
641
642 /**
643 * Assume permissions already checked and caller's identity cleared
644 */
645 private IntArray getProfileIdsLU(int userId, boolean enabledOnly) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700646 UserInfo user = getUserInfoLU(userId);
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700647 IntArray result = new IntArray(mUsers.size());
Amith Yamasanidda003f2014-08-28 18:06:51 -0700648 if (user == null) {
649 // Probably a dying user
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700650 return result;
Amith Yamasanidda003f2014-08-28 18:06:51 -0700651 }
Amith Yamasani515d4062015-09-28 11:30:06 -0700652 final int userSize = mUsers.size();
653 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800654 UserInfo profile = mUsers.valueAt(i).info;
Amith Yamasanibe465322014-04-24 13:45:17 -0700655 if (!isProfileOf(user, profile)) {
656 continue;
657 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100658 if (enabledOnly && !profile.isEnabled()) {
659 continue;
Amith Yamasanibe465322014-04-24 13:45:17 -0700660 }
Amith Yamasani70fcf0c2014-07-11 08:40:19 -0700661 if (mRemovingUserIds.get(profile.id)) {
662 continue;
663 }
Tony Mak80189cd2016-04-05 17:21:42 +0100664 if (profile.partial) {
665 continue;
666 }
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700667 result.add(profile.id);
Amith Yamasanibe465322014-04-24 13:45:17 -0700668 }
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700669 return result;
Amith Yamasanibe465322014-04-24 13:45:17 -0700670 }
671
Jessica Hummelbe81c802014-04-22 15:49:22 +0100672 @Override
Andres Moralesc5548c02015-08-05 10:23:12 -0700673 public int getCredentialOwnerProfile(int userHandle) {
674 checkManageUsersPermission("get the credential owner");
Clara Bayarria1771112015-12-18 16:29:18 +0000675 if (!mLockPatternUtils.isSeparateProfileChallengeEnabled(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700676 synchronized (mUsersLock) {
677 UserInfo profileParent = getProfileParentLU(userHandle);
Andres Moralesc5548c02015-08-05 10:23:12 -0700678 if (profileParent != null) {
679 return profileParent.id;
680 }
681 }
682 }
683
684 return userHandle;
685 }
686
687 @Override
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700688 public boolean isSameProfileGroup(int userId, int otherUserId) {
689 if (userId == otherUserId) return true;
690 checkManageUsersPermission("check if in the same profile group");
Fyodor Kupolov0fb772e2016-10-13 16:27:34 -0700691 return isSameProfileGroupNoChecks(userId, otherUserId);
692 }
693
694 private boolean isSameProfileGroupNoChecks(int userId, int otherUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700695 synchronized (mUsersLock) {
696 UserInfo userInfo = getUserInfoLU(userId);
697 if (userInfo == null || userInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
698 return false;
699 }
700 UserInfo otherUserInfo = getUserInfoLU(otherUserId);
701 if (otherUserInfo == null
702 || otherUserInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
703 return false;
704 }
705 return userInfo.profileGroupId == otherUserInfo.profileGroupId;
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700706 }
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700707 }
708
709 @Override
Jessica Hummelbe81c802014-04-22 15:49:22 +0100710 public UserInfo getProfileParent(int userHandle) {
711 checkManageUsersPermission("get the profile parent");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700712 synchronized (mUsersLock) {
713 return getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700714 }
715 }
716
Jakub Pawlowski0f1f5b72017-11-15 14:50:43 -0800717 @Override
718 public int getProfileParentId(int userHandle) {
719 checkManageUsersPermission("get the profile parent");
720 synchronized (mUsersLock) {
721 UserInfo profileParent = getProfileParentLU(userHandle);
722 if (profileParent == null) {
723 return userHandle;
724 }
725
726 return profileParent.id;
727 }
728 }
729
Fyodor Kupolov82402752015-10-28 14:54:51 -0700730 private UserInfo getProfileParentLU(int userHandle) {
731 UserInfo profile = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700732 if (profile == null) {
733 return null;
734 }
735 int parentUserId = profile.profileGroupId;
Amith Yamasani801e3422017-01-25 11:35:44 -0800736 if (parentUserId == userHandle || parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700737 return null;
738 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700739 return getUserInfoLU(parentUserId);
Jessica Hummelbe81c802014-04-22 15:49:22 +0100740 }
741 }
742
Fyodor Kupolov82402752015-10-28 14:54:51 -0700743 private static boolean isProfileOf(UserInfo user, UserInfo profile) {
Kenny Guy2a764942014-04-02 13:29:20 +0100744 return user.id == profile.id ||
745 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
746 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000747 }
748
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000749 private void broadcastProfileAvailabilityChanges(UserHandle profileHandle,
Rubin Xuf13c9802016-01-21 18:06:00 +0000750 UserHandle parentHandle, boolean inQuietMode) {
Rubin Xue95057a2016-04-01 16:49:25 +0100751 Intent intent = new Intent();
752 if (inQuietMode) {
753 intent.setAction(Intent.ACTION_MANAGED_PROFILE_UNAVAILABLE);
754 } else {
755 intent.setAction(Intent.ACTION_MANAGED_PROFILE_AVAILABLE);
756 }
Rubin Xuf13c9802016-01-21 18:06:00 +0000757 intent.putExtra(Intent.EXTRA_QUIET_MODE, inQuietMode);
758 intent.putExtra(Intent.EXTRA_USER, profileHandle);
759 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileHandle.getIdentifier());
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000760 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Rubin Xuf13c9802016-01-21 18:06:00 +0000761 mContext.sendBroadcastAsUser(intent, parentHandle);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000762 }
763
764 @Override
765 public void setQuietModeEnabled(int userHandle, boolean enableQuietMode) {
766 checkManageUsersPermission("silence profile");
767 boolean changed = false;
768 UserInfo profile, parent;
769 synchronized (mPackagesLock) {
770 synchronized (mUsersLock) {
771 profile = getUserInfoLU(userHandle);
772 parent = getProfileParentLU(userHandle);
773
774 }
775 if (profile == null || !profile.isManagedProfile()) {
776 throw new IllegalArgumentException("User " + userHandle + " is not a profile");
777 }
778 if (profile.isQuietModeEnabled() != enableQuietMode) {
779 profile.flags ^= UserInfo.FLAG_QUIET_MODE;
Amith Yamasani12747872015-12-07 14:19:49 -0800780 writeUserLP(getUserDataLU(profile.id));
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000781 changed = true;
782 }
783 }
784 if (changed) {
Rubin Xuf13c9802016-01-21 18:06:00 +0000785 long identity = Binder.clearCallingIdentity();
786 try {
787 if (enableQuietMode) {
Sudheer Shankadc589ac2016-11-10 15:30:17 -0800788 ActivityManager.getService().stopUser(userHandle, /* force */true, null);
Rubin Xuf8451b92016-04-01 15:50:58 +0100789 LocalServices.getService(ActivityManagerInternal.class)
790 .killForegroundAppsForUser(userHandle);
Rubin Xuf13c9802016-01-21 18:06:00 +0000791 } else {
Sudheer Shankadc589ac2016-11-10 15:30:17 -0800792 ActivityManager.getService().startUserInBackground(userHandle);
Rubin Xuf13c9802016-01-21 18:06:00 +0000793 }
794 } catch (RemoteException e) {
795 Slog.e(LOG_TAG, "fail to start/stop user for quiet mode", e);
796 } finally {
797 Binder.restoreCallingIdentity(identity);
798 }
799
800 broadcastProfileAvailabilityChanges(profile.getUserHandle(), parent.getUserHandle(),
801 enableQuietMode);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000802 }
803 }
804
805 @Override
806 public boolean isQuietModeEnabled(int userHandle) {
807 synchronized (mPackagesLock) {
808 UserInfo info;
809 synchronized (mUsersLock) {
810 info = getUserInfoLU(userHandle);
811 }
812 if (info == null || !info.isManagedProfile()) {
Rubin Xuf13c9802016-01-21 18:06:00 +0000813 return false;
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000814 }
815 return info.isQuietModeEnabled();
816 }
817 }
818
Kenny Guya52dc3e2014-02-11 15:33:14 +0000819 @Override
Benjamin Franzf02420c2016-04-04 18:52:21 +0100820 public boolean trySetQuietModeDisabled(int userHandle, IntentSender target) {
Ricky Waib1dd80b2016-06-07 18:00:55 +0100821 checkManageUsersPermission("silence profile");
Jeff Sharkeyce18c812016-04-27 16:00:41 -0600822 if (StorageManager.isUserKeyUnlocked(userHandle)
Ricky Wai9cc7ad62016-05-11 18:00:20 +0100823 || !mLockPatternUtils.isSecure(userHandle)) {
Benjamin Franzf02420c2016-04-04 18:52:21 +0100824 // if the user is already unlocked, no need to show a profile challenge
825 setQuietModeEnabled(userHandle, false);
826 return true;
827 }
828
829 long identity = Binder.clearCallingIdentity();
830 try {
831 // otherwise, we show a profile challenge to trigger decryption of the user
832 final KeyguardManager km = (KeyguardManager) mContext.getSystemService(
833 Context.KEYGUARD_SERVICE);
Ricky Wai7881cf82016-04-15 17:20:12 +0100834 // We should use userHandle not credentialOwnerUserId here, as even if it is unified
835 // lock, confirm screenlock page will know and show personal challenge, and unlock
836 // work profile when personal challenge is correct
Benjamin Franzf02420c2016-04-04 18:52:21 +0100837 final Intent unlockIntent = km.createConfirmDeviceCredentialIntent(null, null,
838 userHandle);
839 if (unlockIntent == null) {
840 return false;
841 }
Ricky Waib1dd80b2016-06-07 18:00:55 +0100842 final Intent callBackIntent = new Intent(
843 ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK);
Benjamin Franzf02420c2016-04-04 18:52:21 +0100844 if (target != null) {
Ricky Waib1dd80b2016-06-07 18:00:55 +0100845 callBackIntent.putExtra(Intent.EXTRA_INTENT, target);
Benjamin Franzf02420c2016-04-04 18:52:21 +0100846 }
Ricky Waib1dd80b2016-06-07 18:00:55 +0100847 callBackIntent.putExtra(Intent.EXTRA_USER_ID, userHandle);
848 callBackIntent.setPackage(mContext.getPackageName());
849 callBackIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
850 final PendingIntent pendingIntent = PendingIntent.getBroadcast(
851 mContext,
852 0,
853 callBackIntent,
854 PendingIntent.FLAG_CANCEL_CURRENT |
855 PendingIntent.FLAG_ONE_SHOT |
856 PendingIntent.FLAG_IMMUTABLE);
857 // After unlocking the challenge, it will disable quiet mode and run the original
858 // intentSender
859 unlockIntent.putExtra(Intent.EXTRA_INTENT, pendingIntent.getIntentSender());
Benjamin Franzf02420c2016-04-04 18:52:21 +0100860 unlockIntent.setFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
861 mContext.startActivity(unlockIntent);
862 } finally {
863 Binder.restoreCallingIdentity(identity);
864 }
865 return false;
866 }
867
868 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100869 public void setUserEnabled(int userId) {
870 checkManageUsersPermission("enable user");
871 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700872 UserInfo info;
873 synchronized (mUsersLock) {
874 info = getUserInfoLU(userId);
875 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100876 if (info != null && !info.isEnabled()) {
877 info.flags ^= UserInfo.FLAG_DISABLED;
Amith Yamasani12747872015-12-07 14:19:49 -0800878 writeUserLP(getUserDataLU(info.id));
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100879 }
880 }
881 }
882
Andrew Scull85a63bc2016-10-24 13:47:47 +0100883 /**
884 * Evicts a user's CE key by stopping and restarting the user.
885 *
886 * The key is evicted automatically by the user controller when the user has stopped.
887 */
888 @Override
889 public void evictCredentialEncryptionKey(@UserIdInt int userId) {
890 checkManageUsersPermission("evict CE key");
891 final IActivityManager am = ActivityManagerNative.getDefault();
892 final long identity = Binder.clearCallingIdentity();
893 try {
894 am.restartUserInBackground(userId);
895 } catch (RemoteException re) {
896 throw re.rethrowAsRuntimeException();
897 } finally {
898 Binder.restoreCallingIdentity(identity);
899 }
900 }
901
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100902 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700903 public UserInfo getUserInfo(int userId) {
Sudheer Shankaaccaa082016-06-14 16:22:57 -0700904 checkManageOrCreateUsersPermission("query user");
Tony Mak8673b282016-03-21 21:10:59 +0000905 synchronized (mUsersLock) {
Amith Yamasani6f48d6e2016-03-23 14:28:25 -0700906 return userWithName(getUserInfoLU(userId));
907 }
908 }
909
910 /**
911 * Returns a UserInfo object with the name filled in, for Owner, or the original
912 * if the name is already set.
913 */
914 private UserInfo userWithName(UserInfo orig) {
915 if (orig != null && orig.name == null && orig.id == UserHandle.USER_SYSTEM) {
916 UserInfo withName = new UserInfo(orig);
917 withName.name = getOwnerName();
918 return withName;
919 } else {
920 return orig;
Tony Mak8673b282016-03-21 21:10:59 +0000921 }
922 }
923
924 @Override
Kenny Guy02c89902016-11-15 19:36:38 +0000925 public int getManagedProfileBadge(@UserIdInt int userId) {
926 int callingUserId = UserHandle.getCallingUserId();
927 if (callingUserId != userId && !hasManageUsersPermission()) {
928 if (!isSameProfileGroupNoChecks(callingUserId, userId)) {
929 throw new SecurityException(
930 "You need MANAGE_USERS permission to: check if specified user a " +
931 "managed profile outside your profile group");
932 }
933 }
934 synchronized (mUsersLock) {
935 UserInfo userInfo = getUserInfoLU(userId);
936 return userInfo != null ? userInfo.profileBadge : 0;
937 }
938 }
939
940 @Override
Tony Mak8673b282016-03-21 21:10:59 +0000941 public boolean isManagedProfile(int userId) {
Tony Makb531d082016-03-16 14:49:52 +0000942 int callingUserId = UserHandle.getCallingUserId();
943 if (callingUserId != userId && !hasManageUsersPermission()) {
Fyodor Kupolov0fb772e2016-10-13 16:27:34 -0700944 if (!isSameProfileGroupNoChecks(callingUserId, userId)) {
Fyodor Kupolovc413f702016-10-06 17:11:14 -0700945 throw new SecurityException(
946 "You need MANAGE_USERS permission to: check if specified user a " +
947 "managed profile outside your profile group");
Tony Makb531d082016-03-16 14:49:52 +0000948 }
Tony Mak4dc008c2016-03-16 10:46:49 +0000949 }
Fyodor Kupolov82402752015-10-28 14:54:51 -0700950 synchronized (mUsersLock) {
Amith Yamasani1c41dc82016-06-28 16:13:15 -0700951 UserInfo userInfo = getUserInfoLU(userId);
Tony Mak8673b282016-03-21 21:10:59 +0000952 return userInfo != null && userInfo.isManagedProfile();
Amith Yamasani13593602012-03-22 16:16:17 -0700953 }
954 }
955
Amith Yamasani71e6c692013-03-24 17:39:28 -0700956 @Override
Fyodor Kupolovc413f702016-10-06 17:11:14 -0700957 public boolean isUserUnlockingOrUnlocked(int userId) {
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -0800958 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isUserUnlockingOrUnlocked");
Fyodor Kupolovc413f702016-10-06 17:11:14 -0700959 return mLocalService.isUserUnlockingOrUnlocked(userId);
960 }
961
962 @Override
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -0800963 public boolean isUserUnlocked(int userId) {
964 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isUserUnlocked");
965 return mLocalService.isUserUnlockingOrUnlocked(userId);
966 }
967
968 @Override
969 public boolean isUserRunning(int userId) {
970 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isUserRunning");
971 return mLocalService.isUserRunning(userId);
972 }
973
974 private void checkManageOrInteractPermIfCallerInOtherProfileGroup(int userId, String name) {
975 int callingUserId = UserHandle.getCallingUserId();
976 if (callingUserId == userId || isSameProfileGroupNoChecks(callingUserId, userId) ||
977 hasManageUsersPermission()) {
978 return;
979 }
980 if (ActivityManager.checkComponentPermission(Manifest.permission.INTERACT_ACROSS_USERS,
981 Binder.getCallingUid(), -1, true) != PackageManager.PERMISSION_GRANTED) {
982 throw new SecurityException("You need INTERACT_ACROSS_USERS or MANAGE_USERS permission "
983 + "to: check " + name);
984 }
985 }
986
987 @Override
Amith Yamasani1c41dc82016-06-28 16:13:15 -0700988 public boolean isDemoUser(int userId) {
989 int callingUserId = UserHandle.getCallingUserId();
990 if (callingUserId != userId && !hasManageUsersPermission()) {
991 throw new SecurityException("You need MANAGE_USERS permission to query if u=" + userId
992 + " is a demo user");
993 }
994 synchronized (mUsersLock) {
995 UserInfo userInfo = getUserInfoLU(userId);
996 return userInfo != null && userInfo.isDemo();
997 }
998 }
999
1000 @Override
Amith Yamasani71e6c692013-03-24 17:39:28 -07001001 public boolean isRestricted() {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001002 synchronized (mUsersLock) {
1003 return getUserInfoLU(UserHandle.getCallingUserId()).isRestricted();
Amith Yamasani71e6c692013-03-24 17:39:28 -07001004 }
1005 }
1006
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001007 @Override
1008 public boolean canHaveRestrictedProfile(int userId) {
1009 checkManageUsersPermission("canHaveRestrictedProfile");
Fyodor Kupolov82402752015-10-28 14:54:51 -07001010 synchronized (mUsersLock) {
1011 final UserInfo userInfo = getUserInfoLU(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001012 if (userInfo == null || !userInfo.canHaveProfile()) {
1013 return false;
1014 }
1015 if (!userInfo.isAdmin()) {
1016 return false;
1017 }
Makoto Onukie7927da2015-11-25 10:05:17 -08001018 // restricted profile can be created if there is no DO set and the admin user has no PO;
1019 return !mIsDeviceManaged && !mIsUserManaged.get(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001020 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001021 }
1022
Amith Yamasani195263742012-08-21 15:40:12 -07001023 /*
1024 * Should be locked on mUsers before calling this.
1025 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001026 private UserInfo getUserInfoLU(int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -08001027 final UserData userData = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -07001028 // If it is partial and not in the process of being removed, return as unknown user.
Amith Yamasani12747872015-12-07 14:19:49 -08001029 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001030 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
1031 return null;
1032 }
Amith Yamasani12747872015-12-07 14:19:49 -08001033 return userData != null ? userData.info : null;
1034 }
1035
1036 private UserData getUserDataLU(int userId) {
1037 final UserData userData = mUsers.get(userId);
1038 // If it is partial and not in the process of being removed, return as unknown user.
1039 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
1040 return null;
1041 }
1042 return userData;
Amith Yamasani195263742012-08-21 15:40:12 -07001043 }
1044
Fyodor Kupolov82402752015-10-28 14:54:51 -07001045 /**
1046 * Obtains {@link #mUsersLock} and return UserInfo from mUsers.
1047 * <p>No permissions checking or any addition checks are made</p>
1048 */
1049 private UserInfo getUserInfoNoChecks(int userId) {
1050 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001051 final UserData userData = mUsers.get(userId);
1052 return userData != null ? userData.info : null;
1053 }
1054 }
1055
1056 /**
1057 * Obtains {@link #mUsersLock} and return UserData from mUsers.
1058 * <p>No permissions checking or any addition checks are made</p>
1059 */
1060 private UserData getUserDataNoChecks(int userId) {
1061 synchronized (mUsersLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001062 return mUsers.get(userId);
1063 }
1064 }
1065
Amith Yamasani236b2b52015-08-18 14:32:14 -07001066 /** Called by PackageManagerService */
Amith Yamasani13593602012-03-22 16:16:17 -07001067 public boolean exists(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001068 return getUserInfoNoChecks(userId) != null;
Amith Yamasani13593602012-03-22 16:16:17 -07001069 }
1070
Amith Yamasani258848d2012-08-10 17:06:33 -07001071 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001072 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001073 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001074 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -07001075 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001076 UserData userData = getUserDataNoChecks(userId);
1077 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001078 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
1079 return;
1080 }
Amith Yamasani12747872015-12-07 14:19:49 -08001081 if (name != null && !name.equals(userData.info.name)) {
1082 userData.info.name = name;
1083 writeUserLP(userData);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001084 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -07001085 }
1086 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001087 if (changed) {
1088 sendUserInfoChangedBroadcast(userId);
1089 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001090 }
1091
Amith Yamasani258848d2012-08-10 17:06:33 -07001092 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001093 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001094 checkManageUsersPermission("update users");
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01001095 if (hasUserRestriction(UserManager.DISALLOW_SET_USER_ICON, userId)) {
1096 Log.w(LOG_TAG, "Cannot set user icon. DISALLOW_SET_USER_ICON is enabled.");
1097 return;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001098 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01001099 mLocalService.setUserIcon(userId, bitmap);
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001100 }
1101
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01001102
1103
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001104 private void sendUserInfoChangedBroadcast(int userId) {
1105 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
1106 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
1107 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -07001108 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001109 }
1110
Amith Yamasani258848d2012-08-10 17:06:33 -07001111 @Override
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001112 public ParcelFileDescriptor getUserIcon(int targetUserId) {
Adrian Roos1bdff912015-02-17 15:51:35 +01001113 String iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001114 synchronized (mPackagesLock) {
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001115 UserInfo targetUserInfo = getUserInfoNoChecks(targetUserId);
1116 if (targetUserInfo == null || targetUserInfo.partial) {
1117 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + targetUserId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001118 return null;
1119 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001120
1121 final int callingUserId = UserHandle.getCallingUserId();
1122 final int callingGroupId = getUserInfoNoChecks(callingUserId).profileGroupId;
1123 final int targetGroupId = targetUserInfo.profileGroupId;
1124 final boolean sameGroup = (callingGroupId != UserInfo.NO_PROFILE_GROUP_ID
1125 && callingGroupId == targetGroupId);
1126 if ((callingUserId != targetUserId) && !sameGroup) {
Nicolas Prevot88cc3462014-05-14 14:51:48 +01001127 checkManageUsersPermission("get the icon of a user who is not related");
1128 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001129
1130 if (targetUserInfo.iconPath == null) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001131 return null;
1132 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001133 iconPath = targetUserInfo.iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001134 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001135
1136 try {
1137 return ParcelFileDescriptor.open(
1138 new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
1139 } catch (FileNotFoundException e) {
1140 Log.e(LOG_TAG, "Couldn't find icon file", e);
1141 }
1142 return null;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001143 }
1144
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001145 public void makeInitialized(int userId) {
1146 checkManageUsersPermission("makeInitialized");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001147 boolean scheduleWriteUser = false;
Amith Yamasani12747872015-12-07 14:19:49 -08001148 UserData userData;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001149 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001150 userData = mUsers.get(userId);
1151 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001152 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001153 return;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001154 }
Amith Yamasani12747872015-12-07 14:19:49 -08001155 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1156 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001157 scheduleWriteUser = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001158 }
1159 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001160 if (scheduleWriteUser) {
Amith Yamasani12747872015-12-07 14:19:49 -08001161 scheduleWriteUser(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001162 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001163 }
1164
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001165 /**
1166 * If default guest restrictions haven't been initialized yet, add the basic
1167 * restrictions.
1168 */
1169 private void initDefaultGuestRestrictions() {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001170 synchronized (mGuestRestrictions) {
1171 if (mGuestRestrictions.isEmpty()) {
Samuel Tand9453b82016-03-14 15:57:02 -07001172 mGuestRestrictions.putBoolean(UserManager.DISALLOW_CONFIG_WIFI, true);
Fyodor Kupolove04462c2015-11-30 15:02:53 -08001173 mGuestRestrictions.putBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, true);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001174 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
1175 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
1176 }
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001177 }
1178 }
1179
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001180 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301181 public Bundle getDefaultGuestRestrictions() {
1182 checkManageUsersPermission("getDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001183 synchronized (mGuestRestrictions) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301184 return new Bundle(mGuestRestrictions);
1185 }
1186 }
1187
1188 @Override
1189 public void setDefaultGuestRestrictions(Bundle restrictions) {
1190 checkManageUsersPermission("setDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001191 synchronized (mGuestRestrictions) {
1192 mGuestRestrictions.clear();
1193 mGuestRestrictions.putAll(restrictions);
1194 }
1195 synchronized (mPackagesLock) {
1196 writeUserListLP();
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301197 }
1198 }
1199
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001200 /**
Pavel Grafov6a40f092016-10-25 15:46:51 +01001201 * See {@link UserManagerInternal#setDevicePolicyUserRestrictions}
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001202 */
Pavel Grafov6a40f092016-10-25 15:46:51 +01001203 private void setDevicePolicyUserRestrictionsInner(int userId, @Nullable Bundle restrictions,
1204 boolean isDeviceOwner, int cameraRestrictionScope) {
1205 final Bundle global = new Bundle();
1206 final Bundle local = new Bundle();
1207
1208 // Sort restrictions into local and global ensuring they don't overlap.
1209 UserRestrictionsUtils.sortToGlobalAndLocal(restrictions, isDeviceOwner,
1210 cameraRestrictionScope, global, local);
1211
1212 boolean globalChanged, localChanged;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001213 synchronized (mRestrictionsLock) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001214 // Update global and local restrictions if they were changed.
1215 globalChanged = updateRestrictionsIfNeededLR(
1216 userId, global, mDevicePolicyGlobalUserRestrictions);
1217 localChanged = updateRestrictionsIfNeededLR(
1218 userId, local, mDevicePolicyLocalUserRestrictions);
1219
1220 if (isDeviceOwner) {
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001221 // Remember the global restriction owner userId to be able to make a distinction
1222 // in getUserRestrictionSource on who set local policies.
Pavel Grafov6a40f092016-10-25 15:46:51 +01001223 mDeviceOwnerUserId = userId;
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001224 } else {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001225 if (mDeviceOwnerUserId == userId) {
Zoltan Szatmary-Ban8a5536d2016-05-27 17:56:44 +01001226 // When profile owner sets restrictions it passes null global bundle and we
1227 // reset global restriction owner userId.
1228 // This means this user used to have DO, but now the DO is gone and the user
1229 // instead has PO.
Pavel Grafov6a40f092016-10-25 15:46:51 +01001230 mDeviceOwnerUserId = UserHandle.USER_NULL;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001231 }
1232 }
1233 }
1234 if (DBG) {
1235 Log.d(LOG_TAG, "setDevicePolicyUserRestrictions: userId=" + userId
1236 + " global=" + global + (globalChanged ? " (changed)" : "")
1237 + " local=" + local + (localChanged ? " (changed)" : "")
1238 );
1239 }
1240 // Don't call them within the mRestrictionsLock.
1241 synchronized (mPackagesLock) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001242 if (localChanged || globalChanged) {
Amith Yamasani12747872015-12-07 14:19:49 -08001243 writeUserLP(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001244 }
1245 }
1246
1247 synchronized (mRestrictionsLock) {
1248 if (globalChanged) {
1249 applyUserRestrictionsForAllUsersLR();
1250 } else if (localChanged) {
1251 applyUserRestrictionsLR(userId);
1252 }
1253 }
1254 }
1255
Pavel Grafov6a40f092016-10-25 15:46:51 +01001256 /**
1257 * Updates restriction bundle for a given user in a given restriction array. If new bundle is
1258 * empty, record is removed from the array.
1259 * @return whether restrictions bundle is different from the old one.
1260 */
1261 private boolean updateRestrictionsIfNeededLR(int userId, @Nullable Bundle restrictions,
1262 SparseArray<Bundle> restrictionsArray) {
1263 final boolean changed =
1264 !UserRestrictionsUtils.areEqual(restrictionsArray.get(userId), restrictions);
1265 if (changed) {
1266 if (!UserRestrictionsUtils.isEmpty(restrictions)) {
1267 restrictionsArray.put(userId, restrictions);
1268 } else {
1269 restrictionsArray.delete(userId);
1270 }
1271 }
1272 return changed;
1273 }
1274
Makoto Onuki068c54a2015-10-13 14:34:03 -07001275 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001276 private Bundle computeEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001277 final Bundle baseRestrictions =
1278 UserRestrictionsUtils.nonNull(mBaseUserRestrictions.get(userId));
Pavel Grafov6a40f092016-10-25 15:46:51 +01001279 final Bundle global = UserRestrictionsUtils.mergeAll(mDevicePolicyGlobalUserRestrictions);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001280 final Bundle local = mDevicePolicyLocalUserRestrictions.get(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001281
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001282 if (UserRestrictionsUtils.isEmpty(global) && UserRestrictionsUtils.isEmpty(local)) {
1283 // Common case first.
1284 return baseRestrictions;
Makoto Onuki068c54a2015-10-13 14:34:03 -07001285 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001286 final Bundle effective = UserRestrictionsUtils.clone(baseRestrictions);
1287 UserRestrictionsUtils.merge(effective, global);
1288 UserRestrictionsUtils.merge(effective, local);
1289
Makoto Onuki068c54a2015-10-13 14:34:03 -07001290 return effective;
1291 }
1292
1293 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001294 private void invalidateEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki068c54a2015-10-13 14:34:03 -07001295 if (DBG) {
1296 Log.d(LOG_TAG, "invalidateEffectiveUserRestrictions userId=" + userId);
1297 }
1298 mCachedEffectiveUserRestrictions.remove(userId);
1299 }
1300
1301 private Bundle getEffectiveUserRestrictions(int userId) {
1302 synchronized (mRestrictionsLock) {
1303 Bundle restrictions = mCachedEffectiveUserRestrictions.get(userId);
1304 if (restrictions == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001305 restrictions = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001306 mCachedEffectiveUserRestrictions.put(userId, restrictions);
1307 }
1308 return restrictions;
Amith Yamasani8cd28b52014-06-08 17:54:27 -07001309 }
1310 }
1311
Makoto Onuki068c54a2015-10-13 14:34:03 -07001312 /** @return a specific user restriction that's in effect currently. */
1313 @Override
1314 public boolean hasUserRestriction(String restrictionKey, int userId) {
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001315 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1316 return false;
1317 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001318 Bundle restrictions = getEffectiveUserRestrictions(userId);
1319 return restrictions != null && restrictions.getBoolean(restrictionKey);
1320 }
1321
1322 /**
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001323 * @hide
1324 *
1325 * Returns who set a user restriction on a user.
1326 * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
1327 * @param restrictionKey the string key representing the restriction
1328 * @param userId the id of the user for whom to retrieve the restrictions.
1329 * @return The source of user restriction. Any combination of
1330 * {@link UserManager#RESTRICTION_NOT_SET},
1331 * {@link UserManager#RESTRICTION_SOURCE_SYSTEM},
1332 * {@link UserManager#RESTRICTION_SOURCE_DEVICE_OWNER}
1333 * and {@link UserManager#RESTRICTION_SOURCE_PROFILE_OWNER}
1334 */
1335 @Override
1336 public int getUserRestrictionSource(String restrictionKey, int userId) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001337 List<EnforcingUser> enforcingUsers = getUserRestrictionSources(restrictionKey, userId);
1338 // Get "bitwise or" of restriction sources for all enforcing users.
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001339 int result = UserManager.RESTRICTION_NOT_SET;
Pavel Grafov6a40f092016-10-25 15:46:51 +01001340 for (int i = enforcingUsers.size() - 1; i >= 0; i--) {
1341 result |= enforcingUsers.get(i).getUserRestrictionSource();
1342 }
1343 return result;
1344 }
1345
1346 @Override
1347 public List<EnforcingUser> getUserRestrictionSources(
1348 String restrictionKey, @UserIdInt int userId) {
1349 checkManageUsersPermission("getUserRestrictionSource");
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001350
1351 // Shortcut for the most common case
1352 if (!hasUserRestriction(restrictionKey, userId)) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001353 return Collections.emptyList();
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001354 }
1355
Pavel Grafov6a40f092016-10-25 15:46:51 +01001356 final List<EnforcingUser> result = new ArrayList<>();
1357
1358 // Check if it is base restriction.
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001359 if (hasBaseUserRestriction(restrictionKey, userId)) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001360 result.add(new EnforcingUser(
1361 UserHandle.USER_NULL, UserManager.RESTRICTION_SOURCE_SYSTEM));
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001362 }
1363
Pavel Grafov6a40f092016-10-25 15:46:51 +01001364 synchronized (mRestrictionsLock) {
1365 // Check if it is set by profile owner.
1366 Bundle profileOwnerRestrictions = mDevicePolicyLocalUserRestrictions.get(userId);
1367 if (UserRestrictionsUtils.contains(profileOwnerRestrictions, restrictionKey)) {
1368 result.add(getEnforcingUserLocked(userId));
1369 }
1370
1371 // Iterate over all users who enforce global restrictions.
1372 for (int i = mDevicePolicyGlobalUserRestrictions.size() - 1; i >= 0; i--) {
1373 Bundle globalRestrictions = mDevicePolicyGlobalUserRestrictions.valueAt(i);
1374 int profileUserId = mDevicePolicyGlobalUserRestrictions.keyAt(i);
1375 if (UserRestrictionsUtils.contains(globalRestrictions, restrictionKey)) {
1376 result.add(getEnforcingUserLocked(profileUserId));
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001377 }
1378 }
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001379 }
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001380 return result;
1381 }
1382
Pavel Grafov6a40f092016-10-25 15:46:51 +01001383 private EnforcingUser getEnforcingUserLocked(@UserIdInt int userId) {
1384 int source = mDeviceOwnerUserId == userId ? UserManager.RESTRICTION_SOURCE_DEVICE_OWNER
1385 : UserManager.RESTRICTION_SOURCE_PROFILE_OWNER;
1386 return new EnforcingUser(userId, source);
1387 }
1388
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001389 /**
Makoto Onuki068c54a2015-10-13 14:34:03 -07001390 * @return UserRestrictions that are in effect currently. This always returns a new
1391 * {@link Bundle}.
1392 */
Amith Yamasani8cd28b52014-06-08 17:54:27 -07001393 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001394 public Bundle getUserRestrictions(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001395 return UserRestrictionsUtils.clone(getEffectiveUserRestrictions(userId));
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001396 }
1397
1398 @Override
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +00001399 public boolean hasBaseUserRestriction(String restrictionKey, int userId) {
1400 checkManageUsersPermission("hasBaseUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001401 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1402 return false;
1403 }
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +00001404 synchronized (mRestrictionsLock) {
1405 Bundle bundle = mBaseUserRestrictions.get(userId);
1406 return (bundle != null && bundle.getBoolean(restrictionKey, false));
1407 }
1408 }
1409
1410 @Override
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001411 public void setUserRestriction(String key, boolean value, int userId) {
Fyodor Kupolovd4b26042015-07-27 14:30:59 -07001412 checkManageUsersPermission("setUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001413 if (!UserRestrictionsUtils.isValidRestriction(key)) {
1414 return;
1415 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001416 synchronized (mRestrictionsLock) {
1417 // Note we can't modify Bundles stored in mBaseUserRestrictions directly, so create
1418 // a copy.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001419 final Bundle newRestrictions = UserRestrictionsUtils.clone(
1420 mBaseUserRestrictions.get(userId));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001421 newRestrictions.putBoolean(key, value);
1422
Fyodor Kupolov82402752015-10-28 14:54:51 -07001423 updateUserRestrictionsInternalLR(newRestrictions, userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001424 }
1425 }
1426
Makoto Onuki068c54a2015-10-13 14:34:03 -07001427 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001428 * Optionally updating user restrictions, calculate the effective user restrictions and also
1429 * propagate to other services and system settings.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001430 *
Pavel Grafov6a40f092016-10-25 15:46:51 +01001431 * @param newBaseRestrictions User restrictions to set.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001432 * If null, will not update user restrictions and only does the propagation.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001433 * @param userId target user ID.
1434 */
1435 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001436 private void updateUserRestrictionsInternalLR(
Pavel Grafov6a40f092016-10-25 15:46:51 +01001437 @Nullable Bundle newBaseRestrictions, int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001438 final Bundle prevAppliedRestrictions = UserRestrictionsUtils.nonNull(
1439 mAppliedUserRestrictions.get(userId));
1440
1441 // Update base restrictions.
Pavel Grafov6a40f092016-10-25 15:46:51 +01001442 if (newBaseRestrictions != null) {
1443 // If newBaseRestrictions == the current one, it's probably a bug.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001444 final Bundle prevBaseRestrictions = mBaseUserRestrictions.get(userId);
1445
Pavel Grafov6a40f092016-10-25 15:46:51 +01001446 Preconditions.checkState(prevBaseRestrictions != newBaseRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001447 Preconditions.checkState(mCachedEffectiveUserRestrictions.get(userId)
Pavel Grafov6a40f092016-10-25 15:46:51 +01001448 != newBaseRestrictions);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001449
Pavel Grafov6a40f092016-10-25 15:46:51 +01001450 if (updateRestrictionsIfNeededLR(userId, newBaseRestrictions, mBaseUserRestrictions)) {
Amith Yamasani12747872015-12-07 14:19:49 -08001451 scheduleWriteUser(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001452 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001453 }
1454
Fyodor Kupolov82402752015-10-28 14:54:51 -07001455 final Bundle effective = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001456
Makoto Onuki759a7632015-10-28 16:43:10 -07001457 mCachedEffectiveUserRestrictions.put(userId, effective);
1458
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001459 // Apply the new restrictions.
Makoto Onuki4f160732015-10-27 17:15:38 -07001460 if (DBG) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001461 debug("Applying user restrictions: userId=" + userId
1462 + " new=" + effective + " prev=" + prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001463 }
1464
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001465 if (mAppOpsService != null) { // We skip it until system-ready.
Fyodor Kupolovec30ca32016-06-16 15:09:29 -07001466 mHandler.post(new Runnable() {
1467 @Override
1468 public void run() {
1469 try {
1470 mAppOpsService.setUserRestrictions(effective, mUserRestriconToken, userId);
1471 } catch (RemoteException e) {
1472 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
1473 }
1474 }
1475 });
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001476 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001477
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001478 propagateUserRestrictionsLR(userId, effective, prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001479
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001480 mAppliedUserRestrictions.put(userId, new Bundle(effective));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001481 }
1482
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001483 private void propagateUserRestrictionsLR(final int userId,
Makoto Onukid45a4a22015-11-02 17:17:38 -08001484 Bundle newRestrictions, Bundle prevRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001485 // Note this method doesn't touch any state, meaning it doesn't require mRestrictionsLock
1486 // actually, but we still need some kind of synchronization otherwise we might end up
1487 // calling listeners out-of-order, thus "LR".
1488
1489 if (UserRestrictionsUtils.areEqual(newRestrictions, prevRestrictions)) {
1490 return;
1491 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08001492
1493 final Bundle newRestrictionsFinal = new Bundle(newRestrictions);
1494 final Bundle prevRestrictionsFinal = new Bundle(prevRestrictions);
1495
1496 mHandler.post(new Runnable() {
1497 @Override
1498 public void run() {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07001499 UserRestrictionsUtils.applyUserRestrictions(
1500 mContext, userId, newRestrictionsFinal, prevRestrictionsFinal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001501
Makoto Onukid45a4a22015-11-02 17:17:38 -08001502 final UserRestrictionsListener[] listeners;
1503 synchronized (mUserRestrictionsListeners) {
1504 listeners = new UserRestrictionsListener[mUserRestrictionsListeners.size()];
1505 mUserRestrictionsListeners.toArray(listeners);
1506 }
1507 for (int i = 0; i < listeners.length; i++) {
1508 listeners[i].onUserRestrictionsChanged(userId,
1509 newRestrictionsFinal, prevRestrictionsFinal);
1510 }
Makoto Onukie72f81b2017-03-16 14:08:19 -07001511
1512 final Intent broadcast = new Intent(UserManager.ACTION_USER_RESTRICTIONS_CHANGED)
1513 .setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
1514 mContext.sendBroadcastAsUser(broadcast, UserHandle.of(userId));
Makoto Onukid45a4a22015-11-02 17:17:38 -08001515 }
1516 });
1517 }
1518
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001519 // Package private for the inner class.
1520 void applyUserRestrictionsLR(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001521 updateUserRestrictionsInternalLR(null, userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001522 }
1523
1524 @GuardedBy("mRestrictionsLock")
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001525 // Package private for the inner class.
1526 void applyUserRestrictionsForAllUsersLR() {
1527 if (DBG) {
1528 debug("applyUserRestrictionsForAllUsersLR");
1529 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001530 // First, invalidate all cached values.
Makoto Onuki4f160732015-10-27 17:15:38 -07001531 mCachedEffectiveUserRestrictions.clear();
1532
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001533 // We don't want to call into ActivityManagerService while taking a lock, so we'll call
Makoto Onuki068c54a2015-10-13 14:34:03 -07001534 // it on a handler.
1535 final Runnable r = new Runnable() {
1536 @Override
1537 public void run() {
1538 // Then get the list of running users.
1539 final int[] runningUsers;
1540 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001541 runningUsers = ActivityManager.getService().getRunningUserIds();
Makoto Onuki068c54a2015-10-13 14:34:03 -07001542 } catch (RemoteException e) {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001543 Log.w(LOG_TAG, "Unable to access ActivityManagerService");
Makoto Onuki068c54a2015-10-13 14:34:03 -07001544 return;
1545 }
1546 // Then re-calculate the effective restrictions and apply, only for running users.
1547 // It's okay if a new user has started after the getRunningUserIds() call,
1548 // because we'll do the same thing (re-calculate the restrictions and apply)
1549 // when we start a user.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001550 synchronized (mRestrictionsLock) {
1551 for (int i = 0; i < runningUsers.length; i++) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001552 applyUserRestrictionsLR(runningUsers[i]);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001553 }
1554 }
1555 }
1556 };
1557 mHandler.post(r);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001558 }
1559
Amith Yamasani258848d2012-08-10 17:06:33 -07001560 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001561 * Check if we've hit the limit of how many users can be created.
1562 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001563 private boolean isUserLimitReached() {
1564 int count;
1565 synchronized (mUsersLock) {
1566 count = getAliveUsersExcludingGuestsCountLU();
1567 }
1568 return count >= UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001569 }
1570
1571 @Override
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001572 public boolean canAddMoreManagedProfiles(int userId, boolean allowedToRemoveOne) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001573 checkManageUsersPermission("check if more managed profiles can be added.");
1574 if (ActivityManager.isLowRamDeviceStatic()) {
1575 return false;
1576 }
Fyodor Kupolovb6157992015-06-05 15:32:28 -07001577 if (!mContext.getPackageManager().hasSystemFeature(
1578 PackageManager.FEATURE_MANAGED_USERS)) {
1579 return false;
1580 }
Nicolas Prevotb8186812015-08-06 15:00:03 +01001581 // Limit number of managed profiles that can be created
Benjamin Franzc8776152017-01-06 14:16:41 +00001582 final int managedProfilesCount = getProfiles(userId, false).size() - 1;
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001583 final int profilesRemovedCount = managedProfilesCount > 0 && allowedToRemoveOne ? 1 : 0;
Kenny Guy02c89902016-11-15 19:36:38 +00001584 if (managedProfilesCount - profilesRemovedCount >= getMaxManagedProfiles()) {
Nicolas Prevotb8186812015-08-06 15:00:03 +01001585 return false;
1586 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001587 synchronized(mUsersLock) {
1588 UserInfo userInfo = getUserInfoLU(userId);
yuanhao47f9f7c2017-01-18 09:54:45 +08001589 if (userInfo == null || !userInfo.canHaveProfile()) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001590 return false;
1591 }
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001592 int usersCountAfterRemoving = getAliveUsersExcludingGuestsCountLU()
1593 - profilesRemovedCount;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001594 // We allow creating a managed profile in the special case where there is only one user.
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001595 return usersCountAfterRemoving == 1
1596 || usersCountAfterRemoving < UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001597 }
1598 }
1599
Fyodor Kupolov82402752015-10-28 14:54:51 -07001600 private int getAliveUsersExcludingGuestsCountLU() {
Amith Yamasanif584f012014-05-19 17:57:25 -07001601 int aliveUserCount = 0;
1602 final int totalUserCount = mUsers.size();
1603 // Skip over users being removed
1604 for (int i = 0; i < totalUserCount; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001605 UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov6e99d3f2016-11-01 17:18:41 -07001606 if (!mRemovingUserIds.get(user.id) && !user.isGuest()) {
Amith Yamasanif584f012014-05-19 17:57:25 -07001607 aliveUserCount++;
1608 }
1609 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001610 return aliveUserCount;
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001611 }
1612
1613 /**
Amith Yamasani195263742012-08-21 15:40:12 -07001614 * Enforces that only the system UID or root's UID or apps that have the
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001615 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} and
1616 * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL INTERACT_ACROSS_USERS_FULL}
1617 * permissions can make certain calls to the UserManager.
1618 *
1619 * @param message used as message if SecurityException is thrown
1620 * @throws SecurityException if the caller does not have enough privilege.
1621 */
1622 private static final void checkManageUserAndAcrossUsersFullPermission(String message) {
1623 final int uid = Binder.getCallingUid();
1624 if (uid != Process.SYSTEM_UID && uid != 0
1625 && ActivityManager.checkComponentPermission(
1626 Manifest.permission.MANAGE_USERS,
1627 uid, -1, true) != PackageManager.PERMISSION_GRANTED
1628 && ActivityManager.checkComponentPermission(
1629 Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1630 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
1631 throw new SecurityException(
1632 "You need MANAGE_USERS and INTERACT_ACROSS_USERS_FULL permission to: "
1633 + message);
1634 }
1635 }
1636
1637 /**
1638 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001639 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -07001640 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -07001641 *
1642 * @param message used as message if SecurityException is thrown
1643 * @throws SecurityException if the caller is not system or root
Tony Mak4dc008c2016-03-16 10:46:49 +00001644 * @see #hasManageUsersPermission()
Amith Yamasani258848d2012-08-10 17:06:33 -07001645 */
Amith Yamasanibe465322014-04-24 13:45:17 -07001646 private static final void checkManageUsersPermission(String message) {
Tony Mak4dc008c2016-03-16 10:46:49 +00001647 if (!hasManageUsersPermission()) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001648 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
1649 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -04001650 }
1651
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001652 /**
Sudheer Shankaf5cea032016-06-08 17:13:24 -07001653 * Enforces that only the system UID or root's UID or apps that have the
1654 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or
1655 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS}
1656 * can make certain calls to the UserManager.
1657 *
1658 * @param message used as message if SecurityException is thrown
1659 * @throws SecurityException if the caller is not system or root
1660 * @see #hasManageOrCreateUsersPermission()
1661 */
1662 private static final void checkManageOrCreateUsersPermission(String message) {
1663 if (!hasManageOrCreateUsersPermission()) {
1664 throw new SecurityException(
1665 "You either need MANAGE_USERS or CREATE_USERS permission to: " + message);
1666 }
1667 }
1668
1669 /**
1670 * Similar to {@link #checkManageOrCreateUsersPermission(String)} but when the caller is tries
1671 * to create user/profiles other than what is allowed for
1672 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS} permission, then it will only
1673 * allow callers with {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} permission.
1674 */
1675 private static final void checkManageOrCreateUsersPermission(int creationFlags) {
1676 if ((creationFlags & ~ALLOWED_FLAGS_FOR_CREATE_USERS_PERMISSION) == 0) {
1677 if (!hasManageOrCreateUsersPermission()) {
1678 throw new SecurityException("You either need MANAGE_USERS or CREATE_USERS "
1679 + "permission to create an user with flags: " + creationFlags);
1680 }
1681 } else if (!hasManageUsersPermission()) {
1682 throw new SecurityException("You need MANAGE_USERS permission to create an user "
1683 + " with flags: " + creationFlags);
1684 }
1685 }
1686
1687 /**
Tony Mak4dc008c2016-03-16 10:46:49 +00001688 * @return whether the calling UID is system UID or root's UID or the calling app has the
1689 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}.
1690 */
1691 private static final boolean hasManageUsersPermission() {
1692 final int callingUid = Binder.getCallingUid();
1693 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
1694 || callingUid == Process.ROOT_UID
1695 || ActivityManager.checkComponentPermission(
1696 android.Manifest.permission.MANAGE_USERS,
1697 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED;
1698 }
1699
1700 /**
Sudheer Shankaf5cea032016-06-08 17:13:24 -07001701 * @return whether the calling UID is system UID or root's UID or the calling app has the
1702 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or
1703 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS}.
1704 */
1705 private static final boolean hasManageOrCreateUsersPermission() {
1706 final int callingUid = Binder.getCallingUid();
1707 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
1708 || callingUid == Process.ROOT_UID
1709 || ActivityManager.checkComponentPermission(
1710 android.Manifest.permission.MANAGE_USERS,
1711 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED
1712 || ActivityManager.checkComponentPermission(
1713 android.Manifest.permission.CREATE_USERS,
1714 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED;
1715 }
1716
1717 /**
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001718 * Enforces that only the system UID or root's UID (on any user) can make certain calls to the
1719 * UserManager.
1720 *
1721 * @param message used as message if SecurityException is thrown
1722 * @throws SecurityException if the caller is not system or root
1723 */
1724 private static void checkSystemOrRoot(String message) {
1725 final int uid = Binder.getCallingUid();
1726 if (!UserHandle.isSameApp(uid, Process.SYSTEM_UID) && uid != Process.ROOT_UID) {
1727 throw new SecurityException("Only system may: " + message);
1728 }
1729 }
1730
Fyodor Kupolov82402752015-10-28 14:54:51 -07001731 private void writeBitmapLP(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001732 try {
1733 File dir = new File(mUsersDir, Integer.toString(info.id));
1734 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +01001735 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001736 if (!dir.exists()) {
1737 dir.mkdir();
1738 FileUtils.setPermissions(
1739 dir.getPath(),
1740 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
1741 -1, -1);
1742 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001743 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +01001744 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001745 && tmp.renameTo(file) && SELinux.restorecon(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -07001746 info.iconPath = file.getAbsolutePath();
1747 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001748 try {
1749 os.close();
1750 } catch (IOException ioe) {
1751 // What the ... !
1752 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001753 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001754 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001755 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001756 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001757 }
1758
Amith Yamasani0b285492011-04-14 17:35:23 -07001759 /**
1760 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
1761 * cache it elsewhere.
1762 * @return the array of user ids.
1763 */
Dianne Hackborn1676c852012-09-10 14:52:30 -07001764 public int[] getUserIds() {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001765 synchronized (mUsersLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001766 return mUserIds;
1767 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001768 }
1769
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001770 private void readUserListLP() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001771 if (!mUserListFile.exists()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001772 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001773 return;
1774 }
1775 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001776 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001777 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001778 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001779 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001780 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001781 int type;
1782 while ((type = parser.next()) != XmlPullParser.START_TAG
1783 && type != XmlPullParser.END_DOCUMENT) {
Amith Yamasani12747872015-12-07 14:19:49 -08001784 // Skip
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001785 }
1786
1787 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001788 Slog.e(LOG_TAG, "Unable to read user list");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001789 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001790 return;
1791 }
1792
Amith Yamasani2a003292012-08-14 18:25:45 -07001793 mNextSerialNumber = -1;
1794 if (parser.getName().equals(TAG_USERS)) {
1795 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
1796 if (lastSerialNumber != null) {
1797 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
1798 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001799 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
1800 if (versionNumber != null) {
1801 mUserVersion = Integer.parseInt(versionNumber);
1802 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001803 }
1804
Pavel Grafov6a40f092016-10-25 15:46:51 +01001805 // Pre-O global user restriction were stored as a single bundle (as opposed to per-user
1806 // currently), take care of it in case of upgrade.
1807 Bundle oldDevicePolicyGlobalUserRestrictions = null;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001808
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001809 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301810 if (type == XmlPullParser.START_TAG) {
1811 final String name = parser.getName();
1812 if (name.equals(TAG_USER)) {
1813 String id = parser.getAttributeValue(null, ATTR_ID);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001814
Amith Yamasani12747872015-12-07 14:19:49 -08001815 UserData userData = readUserLP(Integer.parseInt(id));
1816
1817 if (userData != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001818 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001819 mUsers.put(userData.info.id, userData);
1820 if (mNextSerialNumber < 0
1821 || mNextSerialNumber <= userData.info.id) {
1822 mNextSerialNumber = userData.info.id + 1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001823 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301824 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001825 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301826 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -08001827 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1828 && type != XmlPullParser.END_TAG) {
1829 if (type == XmlPullParser.START_TAG) {
1830 if (parser.getName().equals(TAG_RESTRICTIONS)) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001831 synchronized (mGuestRestrictions) {
Fyodor Kupoloveafee022017-03-15 17:09:04 -07001832 UserRestrictionsUtils
1833 .readRestrictions(parser, mGuestRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001834 }
Amith Yamasanida0b1682014-11-21 12:58:17 -08001835 }
1836 break;
1837 }
1838 }
Pavel Grafov6a40f092016-10-25 15:46:51 +01001839 } else if (name.equals(TAG_DEVICE_OWNER_USER_ID)
1840 // Legacy name, should only be encountered when upgrading from pre-O.
1841 || name.equals(TAG_GLOBAL_RESTRICTION_OWNER_ID)) {
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001842 String ownerUserId = parser.getAttributeValue(null, ATTR_ID);
1843 if (ownerUserId != null) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001844 mDeviceOwnerUserId = Integer.parseInt(ownerUserId);
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001845 }
Pavel Grafov6a40f092016-10-25 15:46:51 +01001846 } else if (name.equals(TAG_DEVICE_POLICY_RESTRICTIONS)) {
1847 // Should only happen when upgrading from pre-O (version < 7).
1848 oldDevicePolicyGlobalUserRestrictions =
1849 UserRestrictionsUtils.readRestrictions(parser);
Amith Yamasani258848d2012-08-10 17:06:33 -07001850 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001851 }
1852 }
Pavel Grafov6a40f092016-10-25 15:46:51 +01001853
Fyodor Kupolov82402752015-10-28 14:54:51 -07001854 updateUserIds();
Pavel Grafov6a40f092016-10-25 15:46:51 +01001855 upgradeIfNecessaryLP(oldDevicePolicyGlobalUserRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001856 } catch (IOException | XmlPullParserException e) {
1857 fallbackToSingleUserLP();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001858 } finally {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001859 IoUtils.closeQuietly(fis);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001860 }
1861 }
1862
Amith Yamasani6f34b412012-10-22 18:19:27 -07001863 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -08001864 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Pavel Grafov6a40f092016-10-25 15:46:51 +01001865 * @param oldGlobalUserRestrictions Pre-O global device policy restrictions.
Amith Yamasani6f34b412012-10-22 18:19:27 -07001866 */
Pavel Grafov6a40f092016-10-25 15:46:51 +01001867 private void upgradeIfNecessaryLP(Bundle oldGlobalUserRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001868 final int originalVersion = mUserVersion;
Amith Yamasani6f34b412012-10-22 18:19:27 -07001869 int userVersion = mUserVersion;
1870 if (userVersion < 1) {
1871 // Assign a proper name for the owner, if not initialized correctly before
Amith Yamasani12747872015-12-07 14:19:49 -08001872 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
1873 if ("Primary".equals(userData.info.name)) {
1874 userData.info.name =
1875 mContext.getResources().getString(com.android.internal.R.string.owner_name);
1876 scheduleWriteUser(userData);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001877 }
1878 userVersion = 1;
1879 }
1880
Amith Yamasanibc9625052012-11-15 14:39:18 -08001881 if (userVersion < 2) {
1882 // Owner should be marked as initialized
Amith Yamasani12747872015-12-07 14:19:49 -08001883 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
1884 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1885 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
1886 scheduleWriteUser(userData);
Amith Yamasanibc9625052012-11-15 14:39:18 -08001887 }
1888 userVersion = 2;
1889 }
1890
Amith Yamasani350962c2013-08-06 11:18:53 -07001891
Amith Yamasani5e486f52013-08-07 11:06:44 -07001892 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -07001893 userVersion = 4;
1894 }
1895
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001896 if (userVersion < 5) {
1897 initDefaultGuestRestrictions();
1898 userVersion = 5;
1899 }
1900
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001901 if (userVersion < 6) {
1902 final boolean splitSystemUser = UserManager.isSplitSystemUser();
Fyodor Kupolov82402752015-10-28 14:54:51 -07001903 synchronized (mUsersLock) {
1904 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001905 UserData userData = mUsers.valueAt(i);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001906 // In non-split mode, only user 0 can have restricted profiles
Amith Yamasani12747872015-12-07 14:19:49 -08001907 if (!splitSystemUser && userData.info.isRestricted()
1908 && (userData.info.restrictedProfileParentId
1909 == UserInfo.NO_PROFILE_GROUP_ID)) {
1910 userData.info.restrictedProfileParentId = UserHandle.USER_SYSTEM;
1911 scheduleWriteUser(userData);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001912 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001913 }
1914 }
1915 userVersion = 6;
1916 }
1917
Pavel Grafov6a40f092016-10-25 15:46:51 +01001918 if (userVersion < 7) {
1919 // Previously only one user could enforce global restrictions, now it is per-user.
1920 synchronized (mRestrictionsLock) {
1921 if (!UserRestrictionsUtils.isEmpty(oldGlobalUserRestrictions)
1922 && mDeviceOwnerUserId != UserHandle.USER_NULL) {
1923 mDevicePolicyGlobalUserRestrictions.put(
1924 mDeviceOwnerUserId, oldGlobalUserRestrictions);
1925 }
1926 // ENSURE_VERIFY_APPS is now enforced globally even if put by profile owner, so move
1927 // it from local to global bundle for all users who set it.
1928 UserRestrictionsUtils.moveRestriction(UserManager.ENSURE_VERIFY_APPS,
1929 mDevicePolicyLocalUserRestrictions, mDevicePolicyGlobalUserRestrictions
1930 );
1931 }
1932 userVersion = 7;
1933 }
1934
Amith Yamasani6f34b412012-10-22 18:19:27 -07001935 if (userVersion < USER_VERSION) {
1936 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
1937 + USER_VERSION);
1938 } else {
1939 mUserVersion = userVersion;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001940
1941 if (originalVersion < mUserVersion) {
1942 writeUserListLP();
1943 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001944 }
1945 }
1946
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001947 private void fallbackToSingleUserLP() {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001948 int flags = UserInfo.FLAG_INITIALIZED;
1949 // In split system user mode, the admin and primary flags are assigned to the first human
1950 // user.
1951 if (!UserManager.isSplitSystemUser()) {
1952 flags |= UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY;
1953 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001954 // Create the system user
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001955 UserInfo system = new UserInfo(UserHandle.USER_SYSTEM, null, null, flags);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07001956 UserData userData = putUserInfo(system);
Amith Yamasani634cf312012-10-04 17:34:21 -07001957 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -04001958 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -08001959
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001960 Bundle restrictions = new Bundle();
Mahaver Chopra3d9805d2016-07-07 16:25:05 +01001961 try {
1962 final String[] defaultFirstUserRestrictions = mContext.getResources().getStringArray(
1963 com.android.internal.R.array.config_defaultFirstUserRestrictions);
1964 for (String userRestriction : defaultFirstUserRestrictions) {
1965 if (UserRestrictionsUtils.isValidRestriction(userRestriction)) {
1966 restrictions.putBoolean(userRestriction, true);
1967 }
1968 }
1969 } catch (Resources.NotFoundException e) {
1970 Log.e(LOG_TAG, "Couldn't find resource: config_defaultFirstUserRestrictions", e);
1971 }
1972
Pavel Grafov6a40f092016-10-25 15:46:51 +01001973 if (!restrictions.isEmpty()) {
1974 synchronized (mRestrictionsLock) {
1975 mBaseUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions);
1976 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001977 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001978
Fyodor Kupolov82402752015-10-28 14:54:51 -07001979 updateUserIds();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001980 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001981
Amith Yamasani12747872015-12-07 14:19:49 -08001982 writeUserLP(userData);
Jeff Sharkeycd575992016-03-29 14:12:49 -06001983 writeUserListLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001984 }
1985
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001986 private String getOwnerName() {
1987 return mContext.getResources().getString(com.android.internal.R.string.owner_name);
1988 }
1989
Amith Yamasani12747872015-12-07 14:19:49 -08001990 private void scheduleWriteUser(UserData UserData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001991 if (DBG) {
1992 debug("scheduleWriteUser");
1993 }
Makoto Onuki9e935a32015-11-06 14:24:24 -08001994 // No need to wrap it within a lock -- worst case, we'll just post the same message
1995 // twice.
Amith Yamasani12747872015-12-07 14:19:49 -08001996 if (!mHandler.hasMessages(WRITE_USER_MSG, UserData)) {
1997 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, UserData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001998 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
1999 }
2000 }
2001
Amith Yamasani12747872015-12-07 14:19:49 -08002002 private void writeUserLP(UserData userData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002003 if (DBG) {
Amith Yamasani12747872015-12-07 14:19:49 -08002004 debug("writeUserLP " + userData);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002005 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002006 FileOutputStream fos = null;
Amith Yamasani12747872015-12-07 14:19:49 -08002007 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userData.info.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002008 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07002009 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002010 final BufferedOutputStream bos = new BufferedOutputStream(fos);
Kenny Guy02c89902016-11-15 19:36:38 +00002011 writeUserLP(userData, bos);
Amith Yamasani2a003292012-08-14 18:25:45 -07002012 userFile.finishWrite(fos);
2013 } catch (Exception ioe) {
Jeff Sharkeycd575992016-03-29 14:12:49 -06002014 Slog.e(LOG_TAG, "Error writing user info " + userData.info.id, ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -07002015 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002016 }
2017 }
2018
2019 /*
Kenny Guy02c89902016-11-15 19:36:38 +00002020 * Writes the user file in this format:
2021 *
2022 * <user flags="20039023" id="0">
2023 * <name>Primary</name>
2024 * </user>
2025 */
2026 @VisibleForTesting
2027 void writeUserLP(UserData userData, OutputStream os)
2028 throws IOException, XmlPullParserException {
2029 // XmlSerializer serializer = XmlUtils.serializerInstance();
2030 final XmlSerializer serializer = new FastXmlSerializer();
2031 serializer.setOutput(os, StandardCharsets.UTF_8.name());
2032 serializer.startDocument(null, true);
2033 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2034
2035 final UserInfo userInfo = userData.info;
2036 serializer.startTag(null, TAG_USER);
2037 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
2038 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
2039 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
2040 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
2041 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
2042 Long.toString(userInfo.lastLoggedInTime));
2043 if (userInfo.lastLoggedInFingerprint != null) {
2044 serializer.attribute(null, ATTR_LAST_LOGGED_IN_FINGERPRINT,
2045 userInfo.lastLoggedInFingerprint);
2046 }
2047 if (userInfo.iconPath != null) {
2048 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
2049 }
2050 if (userInfo.partial) {
2051 serializer.attribute(null, ATTR_PARTIAL, "true");
2052 }
2053 if (userInfo.guestToRemove) {
2054 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
2055 }
2056 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
2057 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
2058 Integer.toString(userInfo.profileGroupId));
2059 }
2060 serializer.attribute(null, ATTR_PROFILE_BADGE,
2061 Integer.toString(userInfo.profileBadge));
2062 if (userInfo.restrictedProfileParentId != UserInfo.NO_PROFILE_GROUP_ID) {
2063 serializer.attribute(null, ATTR_RESTRICTED_PROFILE_PARENT_ID,
2064 Integer.toString(userInfo.restrictedProfileParentId));
2065 }
2066 // Write seed data
2067 if (userData.persistSeedData) {
2068 if (userData.seedAccountName != null) {
2069 serializer.attribute(null, ATTR_SEED_ACCOUNT_NAME, userData.seedAccountName);
2070 }
2071 if (userData.seedAccountType != null) {
2072 serializer.attribute(null, ATTR_SEED_ACCOUNT_TYPE, userData.seedAccountType);
2073 }
2074 }
2075 if (userInfo.name != null) {
2076 serializer.startTag(null, TAG_NAME);
2077 serializer.text(userInfo.name);
2078 serializer.endTag(null, TAG_NAME);
2079 }
2080 synchronized (mRestrictionsLock) {
2081 UserRestrictionsUtils.writeRestrictions(serializer,
2082 mBaseUserRestrictions.get(userInfo.id), TAG_RESTRICTIONS);
2083 UserRestrictionsUtils.writeRestrictions(serializer,
2084 mDevicePolicyLocalUserRestrictions.get(userInfo.id),
2085 TAG_DEVICE_POLICY_RESTRICTIONS);
Pavel Grafov6a40f092016-10-25 15:46:51 +01002086 UserRestrictionsUtils.writeRestrictions(serializer,
2087 mDevicePolicyGlobalUserRestrictions.get(userInfo.id),
2088 TAG_DEVICE_POLICY_GLOBAL_RESTRICTIONS);
Kenny Guy02c89902016-11-15 19:36:38 +00002089 }
2090
2091 if (userData.account != null) {
2092 serializer.startTag(null, TAG_ACCOUNT);
2093 serializer.text(userData.account);
2094 serializer.endTag(null, TAG_ACCOUNT);
2095 }
2096
2097 if (userData.persistSeedData && userData.seedAccountOptions != null) {
2098 serializer.startTag(null, TAG_SEED_ACCOUNT_OPTIONS);
2099 userData.seedAccountOptions.saveToXml(serializer);
2100 serializer.endTag(null, TAG_SEED_ACCOUNT_OPTIONS);
2101 }
2102
2103 serializer.endTag(null, TAG_USER);
2104
2105 serializer.endDocument();
2106 }
2107
2108 /*
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002109 * Writes the user list file in this format:
2110 *
Amith Yamasani2a003292012-08-14 18:25:45 -07002111 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002112 * <user id="0"></user>
2113 * <user id="2"></user>
2114 * </users>
2115 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002116 private void writeUserListLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002117 if (DBG) {
2118 debug("writeUserList");
2119 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002120 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07002121 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002122 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07002123 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002124 final BufferedOutputStream bos = new BufferedOutputStream(fos);
2125
2126 // XmlSerializer serializer = XmlUtils.serializerInstance();
2127 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002128 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002129 serializer.startDocument(null, true);
2130 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2131
2132 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -07002133 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -07002134 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002135
Adam Lesinskieddeb492014-09-08 17:50:03 -07002136 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002137 synchronized (mGuestRestrictions) {
2138 UserRestrictionsUtils
2139 .writeRestrictions(serializer, mGuestRestrictions, TAG_RESTRICTIONS);
2140 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05302141 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Pavel Grafov6a40f092016-10-25 15:46:51 +01002142 serializer.startTag(null, TAG_DEVICE_OWNER_USER_ID);
2143 serializer.attribute(null, ATTR_ID, Integer.toString(mDeviceOwnerUserId));
2144 serializer.endTag(null, TAG_DEVICE_OWNER_USER_ID);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002145 int[] userIdsToWrite;
2146 synchronized (mUsersLock) {
2147 userIdsToWrite = new int[mUsers.size()];
2148 for (int i = 0; i < userIdsToWrite.length; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002149 UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002150 userIdsToWrite[i] = user.id;
2151 }
2152 }
2153 for (int id : userIdsToWrite) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002154 serializer.startTag(null, TAG_USER);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002155 serializer.attribute(null, ATTR_ID, Integer.toString(id));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002156 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002157 }
2158
2159 serializer.endTag(null, TAG_USERS);
2160
2161 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07002162 userListFile.finishWrite(fos);
2163 } catch (Exception e) {
2164 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -07002165 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002166 }
2167 }
2168
Amith Yamasani12747872015-12-07 14:19:49 -08002169 private UserData readUserLP(int id) {
Kenny Guy02c89902016-11-15 19:36:38 +00002170 FileInputStream fis = null;
2171 try {
2172 AtomicFile userFile =
2173 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
2174 fis = userFile.openRead();
2175 return readUserLP(id, fis);
2176 } catch (IOException ioe) {
2177 Slog.e(LOG_TAG, "Error reading user list");
2178 } catch (XmlPullParserException pe) {
2179 Slog.e(LOG_TAG, "Error reading user list");
2180 } finally {
2181 IoUtils.closeQuietly(fis);
2182 }
2183 return null;
2184 }
2185
2186 @VisibleForTesting
2187 UserData readUserLP(int id, InputStream is) throws IOException,
2188 XmlPullParserException {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002189 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -07002190 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002191 String name = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -08002192 String account = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002193 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -07002194 long creationTime = 0L;
2195 long lastLoggedInTime = 0L;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002196 String lastLoggedInFingerprint = null;
Kenny Guy2a764942014-04-02 13:29:20 +01002197 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Kenny Guy02c89902016-11-15 19:36:38 +00002198 int profileBadge = 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002199 int restrictedProfileParentId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002200 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -07002201 boolean guestToRemove = false;
Amith Yamasani12747872015-12-07 14:19:49 -08002202 boolean persistSeedData = false;
2203 String seedAccountName = null;
2204 String seedAccountType = null;
2205 PersistableBundle seedAccountOptions = null;
Pavel Grafov6a40f092016-10-25 15:46:51 +01002206 Bundle baseRestrictions = null;
2207 Bundle localRestrictions = null;
2208 Bundle globalRestrictions = null;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002209
Kenny Guy02c89902016-11-15 19:36:38 +00002210 XmlPullParser parser = Xml.newPullParser();
2211 parser.setInput(is, StandardCharsets.UTF_8.name());
2212 int type;
2213 while ((type = parser.next()) != XmlPullParser.START_TAG
2214 && type != XmlPullParser.END_DOCUMENT) {
2215 // Skip
2216 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002217
Kenny Guy02c89902016-11-15 19:36:38 +00002218 if (type != XmlPullParser.START_TAG) {
2219 Slog.e(LOG_TAG, "Unable to read user " + id);
2220 return null;
2221 }
2222
2223 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
2224 int storedId = readIntAttribute(parser, ATTR_ID, -1);
2225 if (storedId != id) {
2226 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002227 return null;
2228 }
Kenny Guy02c89902016-11-15 19:36:38 +00002229 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
2230 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
2231 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
2232 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
2233 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
2234 lastLoggedInFingerprint = parser.getAttributeValue(null,
2235 ATTR_LAST_LOGGED_IN_FINGERPRINT);
2236 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
2237 UserInfo.NO_PROFILE_GROUP_ID);
2238 profileBadge = readIntAttribute(parser, ATTR_PROFILE_BADGE, 0);
2239 restrictedProfileParentId = readIntAttribute(parser,
2240 ATTR_RESTRICTED_PROFILE_PARENT_ID, UserInfo.NO_PROFILE_GROUP_ID);
2241 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
2242 if ("true".equals(valueString)) {
2243 partial = true;
2244 }
2245 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
2246 if ("true".equals(valueString)) {
2247 guestToRemove = true;
2248 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002249
Kenny Guy02c89902016-11-15 19:36:38 +00002250 seedAccountName = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_NAME);
2251 seedAccountType = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_TYPE);
2252 if (seedAccountName != null || seedAccountType != null) {
2253 persistSeedData = true;
2254 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002255
Kenny Guy02c89902016-11-15 19:36:38 +00002256 int outerDepth = parser.getDepth();
2257 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2258 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2259 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2260 continue;
2261 }
2262 String tag = parser.getName();
2263 if (TAG_NAME.equals(tag)) {
2264 type = parser.next();
2265 if (type == XmlPullParser.TEXT) {
2266 name = parser.getText();
2267 }
2268 } else if (TAG_RESTRICTIONS.equals(tag)) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01002269 baseRestrictions = UserRestrictionsUtils.readRestrictions(parser);
Kenny Guy02c89902016-11-15 19:36:38 +00002270 } else if (TAG_DEVICE_POLICY_RESTRICTIONS.equals(tag)) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01002271 localRestrictions = UserRestrictionsUtils.readRestrictions(parser);
2272 } else if (TAG_DEVICE_POLICY_GLOBAL_RESTRICTIONS.equals(tag)) {
2273 globalRestrictions = UserRestrictionsUtils.readRestrictions(parser);
Kenny Guy02c89902016-11-15 19:36:38 +00002274 } else if (TAG_ACCOUNT.equals(tag)) {
2275 type = parser.next();
2276 if (type == XmlPullParser.TEXT) {
2277 account = parser.getText();
2278 }
2279 } else if (TAG_SEED_ACCOUNT_OPTIONS.equals(tag)) {
2280 seedAccountOptions = PersistableBundle.restoreFromXml(parser);
Amith Yamasani12747872015-12-07 14:19:49 -08002281 persistSeedData = true;
2282 }
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08002283 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002284 }
Kenny Guy02c89902016-11-15 19:36:38 +00002285
2286 // Create the UserInfo object that gets passed around
2287 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
2288 userInfo.serialNumber = serialNumber;
2289 userInfo.creationTime = creationTime;
2290 userInfo.lastLoggedInTime = lastLoggedInTime;
2291 userInfo.lastLoggedInFingerprint = lastLoggedInFingerprint;
2292 userInfo.partial = partial;
2293 userInfo.guestToRemove = guestToRemove;
2294 userInfo.profileGroupId = profileGroupId;
2295 userInfo.profileBadge = profileBadge;
2296 userInfo.restrictedProfileParentId = restrictedProfileParentId;
2297
2298 // Create the UserData object that's internal to this class
2299 UserData userData = new UserData();
2300 userData.info = userInfo;
2301 userData.account = account;
2302 userData.seedAccountName = seedAccountName;
2303 userData.seedAccountType = seedAccountType;
2304 userData.persistSeedData = persistSeedData;
2305 userData.seedAccountOptions = seedAccountOptions;
2306
2307 synchronized (mRestrictionsLock) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01002308 if (baseRestrictions != null) {
2309 mBaseUserRestrictions.put(id, baseRestrictions);
2310 }
2311 if (localRestrictions != null) {
2312 mDevicePolicyLocalUserRestrictions.put(id, localRestrictions);
2313 }
2314 if (globalRestrictions != null) {
2315 mDevicePolicyGlobalUserRestrictions.put(id, globalRestrictions);
2316 }
Kenny Guy02c89902016-11-15 19:36:38 +00002317 }
2318 return userData;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002319 }
2320
Amith Yamasani920ace02012-09-20 22:15:37 -07002321 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
2322 String valueString = parser.getAttributeValue(null, attr);
2323 if (valueString == null) return defaultValue;
2324 try {
2325 return Integer.parseInt(valueString);
2326 } catch (NumberFormatException nfe) {
2327 return defaultValue;
2328 }
2329 }
2330
2331 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
2332 String valueString = parser.getAttributeValue(null, attr);
2333 if (valueString == null) return defaultValue;
2334 try {
2335 return Long.parseLong(valueString);
2336 } catch (NumberFormatException nfe) {
2337 return defaultValue;
2338 }
2339 }
2340
Amith Yamasanib82add22013-07-09 11:24:44 -07002341 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002342 * Removes the app restrictions file for a specific package and user id, if it exists.
2343 */
2344 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
2345 synchronized (mPackagesLock) {
2346 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07002347 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002348 if (resFile.exists()) {
2349 resFile.delete();
2350 }
2351 }
2352 }
2353
Kenny Guya52dc3e2014-02-11 15:33:14 +00002354 @Override
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002355 public UserInfo createProfileForUser(String name, int flags, int userId,
2356 String[] disallowedPackages) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002357 checkManageOrCreateUsersPermission(flags);
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002358 return createUserInternal(name, flags, userId, disallowedPackages);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002359 }
2360
Amith Yamasani258848d2012-08-10 17:06:33 -07002361 @Override
Tony Mak6dc428f2016-10-10 15:48:27 +01002362 public UserInfo createProfileForUserEvenWhenDisallowed(String name, int flags, int userId,
2363 String[] disallowedPackages) {
2364 checkManageOrCreateUsersPermission(flags);
2365 return createUserInternalUnchecked(name, flags, userId, disallowedPackages);
2366 }
2367
2368 @Override
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00002369 public boolean removeUserEvenWhenDisallowed(@UserIdInt int userHandle) {
2370 checkManageOrCreateUsersPermission("Only the system can remove users");
2371 return removeUserUnchecked(userHandle);
2372 }
2373
2374 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07002375 public UserInfo createUser(String name, int flags) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002376 checkManageOrCreateUsersPermission(flags);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00002377 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002378 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07002379
Jessica Hummelbe81c802014-04-22 15:49:22 +01002380 private UserInfo createUserInternal(String name, int flags, int parentId) {
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002381 return createUserInternal(name, flags, parentId, null);
2382 }
2383
2384 private UserInfo createUserInternal(String name, int flags, int parentId,
2385 String[] disallowedPackages) {
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002386 String restriction = ((flags & UserInfo.FLAG_MANAGED_PROFILE) != 0)
2387 ? UserManager.DISALLOW_ADD_MANAGED_PROFILE
2388 : UserManager.DISALLOW_ADD_USER;
2389 if (hasUserRestriction(restriction, UserHandle.getCallingUserId())) {
2390 Log.w(LOG_TAG, "Cannot add user. " + restriction + " is enabled.");
Julia Reynolds75175022014-06-26 16:35:00 -04002391 return null;
2392 }
Tony Mak6dc428f2016-10-10 15:48:27 +01002393 return createUserInternalUnchecked(name, flags, parentId, disallowedPackages);
2394 }
2395
2396 private UserInfo createUserInternalUnchecked(String name, int flags, int parentId,
2397 String[] disallowedPackages) {
Suprabh Shuklac5e057c2016-08-08 16:22:44 -07002398 DeviceStorageMonitorInternal dsm = LocalServices
2399 .getService(DeviceStorageMonitorInternal.class);
2400 if (dsm.isMemoryLow()) {
2401 Log.w(LOG_TAG, "Cannot add user. Not enough space on disk.");
2402 return null;
2403 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07002404 if (ActivityManager.isLowRamDeviceStatic()) {
2405 return null;
2406 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07002407 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Nicolas Prevot12678a92015-05-13 12:15:03 -07002408 final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002409 final boolean isRestricted = (flags & UserInfo.FLAG_RESTRICTED) != 0;
Amith Yamasani52c21e32016-05-31 09:12:20 -07002410 final boolean isDemo = (flags & UserInfo.FLAG_DEMO) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002411 final long ident = Binder.clearCallingIdentity();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002412 UserInfo userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08002413 UserData userData;
Amith Yamasanibb054c92015-07-09 14:16:27 -07002414 final int userId;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002415 try {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002416 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002417 UserData parent = null;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002418 if (parentId != UserHandle.USER_NULL) {
2419 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002420 parent = getUserDataLU(parentId);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00002421 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002422 if (parent == null) return null;
2423 }
2424 if (isManagedProfile && !canAddMoreManagedProfiles(parentId, false)) {
2425 Log.e(LOG_TAG, "Cannot add more managed profiles for user " + parentId);
2426 return null;
2427 }
Amith Yamasani52c21e32016-05-31 09:12:20 -07002428 if (!isGuest && !isManagedProfile && !isDemo && isUserLimitReached()) {
2429 // If we're not adding a guest/demo user or a managed profile and the limit has
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002430 // been reached, cannot add a user.
2431 return null;
2432 }
2433 // If we're adding a guest and there already exists one, bail.
2434 if (isGuest && findCurrentGuestUser() != null) {
2435 return null;
2436 }
2437 // In legacy mode, restricted profile's parent can only be the owner user
2438 if (isRestricted && !UserManager.isSplitSystemUser()
2439 && (parentId != UserHandle.USER_SYSTEM)) {
2440 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
2441 return null;
2442 }
2443 if (isRestricted && UserManager.isSplitSystemUser()) {
2444 if (parent == null) {
2445 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be "
2446 + "specified");
Nicolas Prevot12678a92015-05-13 12:15:03 -07002447 return null;
2448 }
Amith Yamasani12747872015-12-07 14:19:49 -08002449 if (!parent.info.canHaveProfile()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002450 Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be "
2451 + "created for the specified parent user id " + parentId);
Amith Yamasani95ab7842014-08-11 17:09:26 -07002452 return null;
2453 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002454 }
Suprabh Shuklacc30b0e72016-05-20 14:41:22 -07002455 if (!UserManager.isSplitSystemUser() && (flags & UserInfo.FLAG_EPHEMERAL) != 0
2456 && (flags & UserInfo.FLAG_DEMO) == 0) {
Lenka Trochtova024f9792016-02-17 13:55:17 +01002457 Log.e(LOG_TAG,
2458 "Ephemeral users are supported on split-system-user systems only.");
2459 return null;
2460 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002461 // In split system user mode, we assign the first human user the primary flag.
2462 // And if there is no device owner, we also assign the admin flag to primary user.
2463 if (UserManager.isSplitSystemUser()
2464 && !isGuest && !isManagedProfile && getPrimaryUser() == null) {
2465 flags |= UserInfo.FLAG_PRIMARY;
Makoto Onukie7927da2015-11-25 10:05:17 -08002466 synchronized (mUsersLock) {
2467 if (!mIsDeviceManaged) {
2468 flags |= UserInfo.FLAG_ADMIN;
2469 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07002470 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002471 }
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002472
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002473 userId = getNextAvailableId();
2474 Environment.getUserSystemDirectory(userId).mkdirs();
Lenka Trochtova02fee152015-12-22 14:26:18 +01002475 boolean ephemeralGuests = Resources.getSystem()
2476 .getBoolean(com.android.internal.R.bool.config_guestUserEphemeral);
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002477
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002478 synchronized (mUsersLock) {
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002479 // Add ephemeral flag to guests/users if required. Also inherit it from parent.
2480 if ((isGuest && ephemeralGuests) || mForceEphemeralUsers
2481 || (parent != null && parent.info.isEphemeral())) {
2482 flags |= UserInfo.FLAG_EPHEMERAL;
2483 }
2484
2485 userInfo = new UserInfo(userId, name, null, flags);
2486 userInfo.serialNumber = mNextSerialNumber++;
2487 long now = System.currentTimeMillis();
2488 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
2489 userInfo.partial = true;
Fyodor Kupolov83c24242016-03-31 13:30:42 -07002490 userInfo.lastLoggedInFingerprint = Build.FINGERPRINT;
Kenny Guy02c89902016-11-15 19:36:38 +00002491 if (isManagedProfile && parentId != UserHandle.USER_NULL) {
2492 userInfo.profileBadge = getFreeProfileBadgeLU(parentId);
2493 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002494 userData = new UserData();
2495 userData.info = userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08002496 mUsers.put(userId, userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002497 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06002498 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002499 writeUserListLP();
2500 if (parent != null) {
2501 if (isManagedProfile) {
Amith Yamasani12747872015-12-07 14:19:49 -08002502 if (parent.info.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
2503 parent.info.profileGroupId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002504 writeUserLP(parent);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002505 }
Amith Yamasani12747872015-12-07 14:19:49 -08002506 userInfo.profileGroupId = parent.info.profileGroupId;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002507 } else if (isRestricted) {
Amith Yamasani12747872015-12-07 14:19:49 -08002508 if (parent.info.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) {
2509 parent.info.restrictedProfileParentId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002510 writeUserLP(parent);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002511 }
Amith Yamasani12747872015-12-07 14:19:49 -08002512 userInfo.restrictedProfileParentId = parent.info.restrictedProfileParentId;
Makoto Onuki068c54a2015-10-13 14:34:03 -07002513 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002514 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07002515 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002516 final StorageManager storage = mContext.getSystemService(StorageManager.class);
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002517 storage.createUserKey(userId, userInfo.serialNumber, userInfo.isEphemeral());
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -08002518 mUserDataPreparer.prepareUserData(userId, userInfo.serialNumber,
Jeff Sharkey47f71082016-02-01 17:03:54 -07002519 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002520 mPm.createNewUser(userId, disallowedPackages);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002521 userInfo.partial = false;
2522 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002523 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002524 }
2525 updateUserIds();
2526 Bundle restrictions = new Bundle();
Fyodor Kupolove04462c2015-11-30 15:02:53 -08002527 if (isGuest) {
2528 synchronized (mGuestRestrictions) {
2529 restrictions.putAll(mGuestRestrictions);
2530 }
2531 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002532 synchronized (mRestrictionsLock) {
2533 mBaseUserRestrictions.append(userId, restrictions);
2534 }
Fyodor Kupolov5fd967d2016-07-12 14:46:19 -07002535 mPm.onNewUserCreated(userId);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002536 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
2537 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
2538 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
2539 android.Manifest.permission.MANAGE_USERS);
Christine Franks88220562017-05-24 11:11:21 -07002540 MetricsLogger.count(mContext, isGuest ? TRON_GUEST_CREATED
2541 : (isDemo ? TRON_DEMO_CREATED : TRON_USER_CREATED), 1);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002542 } finally {
2543 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07002544 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002545 return userInfo;
2546 }
2547
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002548 @VisibleForTesting
2549 UserData putUserInfo(UserInfo userInfo) {
2550 final UserData userData = new UserData();
2551 userData.info = userInfo;
2552 synchronized (mUsers) {
2553 mUsers.put(userInfo.id, userData);
2554 }
2555 return userData;
2556 }
2557
2558 @VisibleForTesting
2559 void removeUserInfo(int userId) {
2560 synchronized (mUsers) {
2561 mUsers.remove(userId);
2562 }
2563 }
2564
Amith Yamasani0b285492011-04-14 17:35:23 -07002565 /**
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002566 * @hide
2567 */
Amith Yamasani12747872015-12-07 14:19:49 -08002568 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002569 public UserInfo createRestrictedProfile(String name, int parentUserId) {
Sudheer Shanka53d41472016-06-16 09:11:08 -07002570 checkManageOrCreateUsersPermission("setupRestrictedProfile");
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002571 final UserInfo user = createProfileForUser(
2572 name, UserInfo.FLAG_RESTRICTED, parentUserId, null);
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002573 if (user == null) {
2574 return null;
2575 }
Fyodor Kupolov9e912ba2016-02-09 18:29:43 -08002576 long identity = Binder.clearCallingIdentity();
2577 try {
2578 setUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, true, user.id);
2579 // Change the setting before applying the DISALLOW_SHARE_LOCATION restriction, otherwise
2580 // the putIntForUser() will fail.
2581 android.provider.Settings.Secure.putIntForUser(mContext.getContentResolver(),
2582 android.provider.Settings.Secure.LOCATION_MODE,
2583 android.provider.Settings.Secure.LOCATION_MODE_OFF, user.id);
2584 setUserRestriction(UserManager.DISALLOW_SHARE_LOCATION, true, user.id);
2585 } finally {
2586 Binder.restoreCallingIdentity(identity);
2587 }
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002588 return user;
2589 }
2590
2591 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07002592 * Find the current guest user. If the Guest user is partial,
2593 * then do not include it in the results as it is about to die.
Adam Lesinskieddeb492014-09-08 17:50:03 -07002594 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002595 private UserInfo findCurrentGuestUser() {
2596 synchronized (mUsersLock) {
2597 final int size = mUsers.size();
2598 for (int i = 0; i < size; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002599 final UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002600 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
2601 return user;
2602 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002603 }
2604 }
2605 return null;
2606 }
2607
2608 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07002609 * Mark this guest user for deletion to allow us to create another guest
2610 * and switch to that user before actually removing this guest.
2611 * @param userHandle the userid of the current guest
2612 * @return whether the user could be marked for deletion
2613 */
Amith Yamasani12747872015-12-07 14:19:49 -08002614 @Override
Amith Yamasani1df14732014-08-29 21:37:27 -07002615 public boolean markGuestForDeletion(int userHandle) {
2616 checkManageUsersPermission("Only the system can remove users");
2617 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
2618 UserManager.DISALLOW_REMOVE_USER, false)) {
2619 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
2620 return false;
2621 }
2622
2623 long ident = Binder.clearCallingIdentity();
2624 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002625 final UserData userData;
Amith Yamasani1df14732014-08-29 21:37:27 -07002626 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002627 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002628 userData = mUsers.get(userHandle);
2629 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002630 return false;
2631 }
Amith Yamasani1df14732014-08-29 21:37:27 -07002632 }
Amith Yamasani12747872015-12-07 14:19:49 -08002633 if (!userData.info.isGuest()) {
Amith Yamasani1df14732014-08-29 21:37:27 -07002634 return false;
2635 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002636 // We set this to a guest user that is to be removed. This is a temporary state
2637 // where we are allowed to add new Guest users, even if this one is still not
2638 // removed. This user will still show up in getUserInfo() calls.
2639 // If we don't get around to removing this Guest user, it will be purged on next
2640 // startup.
Amith Yamasani12747872015-12-07 14:19:49 -08002641 userData.info.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07002642 // Mark it as disabled, so that it isn't returned any more when
2643 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002644 userData.info.flags |= UserInfo.FLAG_DISABLED;
2645 writeUserLP(userData);
Amith Yamasani1df14732014-08-29 21:37:27 -07002646 }
2647 } finally {
2648 Binder.restoreCallingIdentity(ident);
2649 }
2650 return true;
2651 }
2652
2653 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002654 * Removes a user and all data directories created for that user. This method should be called
2655 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07002656 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07002657 */
Amith Yamasani12747872015-12-07 14:19:49 -08002658 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -07002659 public boolean removeUser(int userHandle) {
Fyodor Kupolov4593e422016-10-27 11:00:29 -07002660 Slog.i(LOG_TAG, "removeUser u" + userHandle);
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002661 checkManageOrCreateUsersPermission("Only the system can remove users");
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002662
2663 final boolean isManagedProfile;
2664 synchronized (mUsersLock) {
2665 UserInfo userInfo = getUserInfoLU(userHandle);
2666 isManagedProfile = userInfo != null && userInfo.isManagedProfile();
2667 }
2668 String restriction = isManagedProfile
2669 ? UserManager.DISALLOW_REMOVE_MANAGED_PROFILE : UserManager.DISALLOW_REMOVE_USER;
2670 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(restriction, false)) {
2671 Log.w(LOG_TAG, "Cannot remove user. " + restriction + " is enabled.");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04002672 return false;
2673 }
Nicolas Prevotdf1b87d2016-10-25 13:57:08 +01002674 return removeUserUnchecked(userHandle);
2675 }
Julia Reynolds4ac5f852014-06-23 17:38:51 -04002676
Nicolas Prevotdf1b87d2016-10-25 13:57:08 +01002677 private boolean removeUserUnchecked(int userHandle) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002678 long ident = Binder.clearCallingIdentity();
2679 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002680 final UserData userData;
Fyodor Kupolov0df68cd2015-10-01 13:54:22 -07002681 int currentUser = ActivityManager.getCurrentUser();
2682 if (currentUser == userHandle) {
2683 Log.w(LOG_TAG, "Current user cannot be removed");
2684 return false;
2685 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002686 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002687 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002688 userData = mUsers.get(userHandle);
2689 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002690 return false;
2691 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002692
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002693 addRemovingUserIdLocked(userHandle);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002694 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002695
Kenny Guyee58b4f2014-05-23 15:19:53 +01002696 try {
2697 mAppOpsService.removeUser(userHandle);
2698 } catch (RemoteException e) {
2699 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
2700 }
2701 // Set this to a partially created user, so that the user will be purged
2702 // on next startup, in case the runtime stops now before stopping and
2703 // removing the user completely.
Amith Yamasani12747872015-12-07 14:19:49 -08002704 userData.info.partial = true;
Kenny Guyee58b4f2014-05-23 15:19:53 +01002705 // Mark it as disabled, so that it isn't returned any more when
2706 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002707 userData.info.flags |= UserInfo.FLAG_DISABLED;
2708 writeUserLP(userData);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002709 }
2710
Amith Yamasani12747872015-12-07 14:19:49 -08002711 if (userData.info.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
2712 && userData.info.isManagedProfile()) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002713 // Send broadcast to notify system that the user removed was a
2714 // managed user.
Amith Yamasani12747872015-12-07 14:19:49 -08002715 sendProfileRemovedBroadcast(userData.info.profileGroupId, userData.info.id);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002716 }
2717
2718 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
2719 int res;
2720 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08002721 res = ActivityManager.getService().stopUser(userHandle, /* force= */ true,
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07002722 new IStopUserCallback.Stub() {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002723 @Override
2724 public void userStopped(int userId) {
2725 finishRemoveUser(userId);
2726 }
2727 @Override
2728 public void userStopAborted(int userId) {
2729 }
2730 });
2731 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002732 return false;
2733 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002734 return res == ActivityManager.USER_OP_SUCCESS;
2735 } finally {
2736 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002737 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002738 }
2739
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002740 @VisibleForTesting
2741 void addRemovingUserIdLocked(int userId) {
2742 // We remember deleted user IDs to prevent them from being
2743 // reused during the current boot; they can still be reused
2744 // after a reboot or recycling of userIds.
2745 mRemovingUserIds.put(userId, true);
2746 mRecentlyRemovedIds.add(userId);
2747 // Keep LRU queue of recently removed IDs for recycling
2748 if (mRecentlyRemovedIds.size() > MAX_RECENTLY_REMOVED_IDS_SIZE) {
2749 mRecentlyRemovedIds.removeFirst();
2750 }
2751 }
2752
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002753 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07002754 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002755 // Let other services shutdown any activity and clean up their state before completely
2756 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002757 long ident = Binder.clearCallingIdentity();
2758 try {
2759 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
2760 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002761 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
2762 android.Manifest.permission.MANAGE_USERS,
2763
2764 new BroadcastReceiver() {
2765 @Override
2766 public void onReceive(Context context, Intent intent) {
2767 if (DBG) {
2768 Slog.i(LOG_TAG,
2769 "USER_REMOVED broadcast sent, cleaning up user data "
2770 + userHandle);
2771 }
2772 new Thread() {
Amith Yamasani12747872015-12-07 14:19:49 -08002773 @Override
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002774 public void run() {
Amith Yamasani515d4062015-09-28 11:30:06 -07002775 // Clean up any ActivityManager state
2776 LocalServices.getService(ActivityManagerInternal.class)
2777 .onUserRemoved(userHandle);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002778 removeUserState(userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002779 }
2780 }.start();
2781 }
2782 },
2783
2784 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002785 } finally {
2786 Binder.restoreCallingIdentity(ident);
2787 }
Amith Yamasani2a003292012-08-14 18:25:45 -07002788 }
2789
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002790 private void removeUserState(final int userHandle) {
Paul Crowley91293792016-03-25 15:23:07 -07002791 try {
2792 mContext.getSystemService(StorageManager.class).destroyUserKey(userHandle);
2793 } catch (IllegalStateException e) {
2794 // This may be simply because the user was partially created.
2795 Slog.i(LOG_TAG,
2796 "Destroying key for user " + userHandle + " failed, continuing anyway", e);
2797 }
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002798
Amith Yamasanid04aaa32016-06-13 12:09:36 -07002799 // Cleanup gatekeeper secure user id
2800 try {
2801 final IGateKeeperService gk = GateKeeper.getService();
2802 if (gk != null) {
2803 gk.clearSecureUserId(userHandle);
2804 }
2805 } catch (Exception ex) {
2806 Slog.w(LOG_TAG, "unable to clear GK secure user id");
2807 }
2808
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002809 // Cleanup package manager settings
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002810 mPm.cleanUpUser(this, userHandle);
Amith Yamasanid04aaa32016-06-13 12:09:36 -07002811
2812 // Clean up all data before removing metadata
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -08002813 mUserDataPreparer.destroyUserData(userHandle,
Amith Yamasanid04aaa32016-06-13 12:09:36 -07002814 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2815
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002816 // Remove this user from the list
Fyodor Kupolov82402752015-10-28 14:54:51 -07002817 synchronized (mUsersLock) {
2818 mUsers.remove(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08002819 mIsUserManaged.delete(userHandle);
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00002820 }
2821 synchronized (mUserStates) {
2822 mUserStates.delete(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08002823 }
2824 synchronized (mRestrictionsLock) {
2825 mBaseUserRestrictions.remove(userHandle);
2826 mAppliedUserRestrictions.remove(userHandle);
2827 mCachedEffectiveUserRestrictions.remove(userHandle);
2828 mDevicePolicyLocalUserRestrictions.remove(userHandle);
Pavel Grafov6a40f092016-10-25 15:46:51 +01002829 if (mDevicePolicyGlobalUserRestrictions.get(userHandle) != null) {
2830 mDevicePolicyGlobalUserRestrictions.remove(userHandle);
2831 applyUserRestrictionsForAllUsersLR();
2832 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002833 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002834 // Update the user list
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002835 synchronized (mPackagesLock) {
2836 writeUserListLP();
2837 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06002838 // Remove user file
2839 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
2840 userFile.delete();
Fyodor Kupolov82402752015-10-28 14:54:51 -07002841 updateUserIds();
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002842 if (RELEASE_DELETED_USER_ID) {
2843 synchronized (mUsers) {
2844 mRemovingUserIds.delete(userHandle);
2845 }
2846 }
Amith Yamasani61f57372012-08-31 12:12:28 -07002847 }
2848
Kenny Guyf8d3a232014-05-15 16:09:52 +01002849 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01002850 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01002851 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
2852 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002853 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
Jeff Sharkeyaf6ec292015-12-17 11:19:00 -07002854 managedProfileIntent.putExtra(Intent.EXTRA_USER_HANDLE, removedUserId);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002855 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01002856 }
2857
Amith Yamasani2a003292012-08-14 18:25:45 -07002858 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002859 public Bundle getApplicationRestrictions(String packageName) {
2860 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
2861 }
2862
2863 @Override
2864 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002865 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07002866 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07002867 checkSystemOrRoot("get application restrictions for other user/app " + packageName);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002868 }
2869 synchronized (mPackagesLock) {
2870 // Read the restrictions from XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07002871 return readApplicationRestrictionsLP(packageName, userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002872 }
2873 }
2874
2875 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002876 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002877 int userId) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00002878 checkSystemOrRoot("set application restrictions");
Fyodor Kupolov0d88d542016-04-19 11:37:22 -07002879 if (restrictions != null) {
2880 restrictions.setDefusable(true);
2881 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002882 synchronized (mPackagesLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01002883 if (restrictions == null || restrictions.isEmpty()) {
2884 cleanAppRestrictionsForPackage(packageName, userId);
2885 } else {
2886 // Write the restrictions to XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07002887 writeApplicationRestrictionsLP(packageName, restrictions, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01002888 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002889 }
Robin Lee66e5d962014-04-09 16:44:21 +01002890
Fyodor Kupolovd2846122016-02-11 18:06:34 -08002891 // Notify package of changes via an intent - only sent to explicitly registered receivers.
2892 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
2893 changeIntent.setPackage(packageName);
2894 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
2895 mContext.sendBroadcastAsUser(changeIntent, UserHandle.of(userId));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002896 }
2897
2898 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07002899 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002900 try {
2901 return mContext.getPackageManager().getApplicationInfo(packageName,
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07002902 PackageManager.MATCH_ANY_USER).uid;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002903 } catch (NameNotFoundException nnfe) {
2904 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07002905 } finally {
2906 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002907 }
2908 }
2909
Fyodor Kupolov82402752015-10-28 14:54:51 -07002910 private Bundle readApplicationRestrictionsLP(String packageName, int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002911 AtomicFile restrictionsFile =
2912 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
2913 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002914 return readApplicationRestrictionsLP(restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002915 }
2916
2917 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002918 static Bundle readApplicationRestrictionsLP(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002919 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002920 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002921 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07002922 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002923 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002924
2925 FileInputStream fis = null;
2926 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002927 fis = restrictionsFile.openRead();
2928 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002929 parser.setInput(fis, StandardCharsets.UTF_8.name());
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002930 XmlUtils.nextElement(parser);
2931 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002932 Slog.e(LOG_TAG, "Unable to read restrictions file "
2933 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002934 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002935 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002936 while (parser.next() != XmlPullParser.END_DOCUMENT) {
2937 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002938 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002939 } catch (IOException|XmlPullParserException e) {
2940 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002941 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002942 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002943 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002944 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002945 }
2946
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002947 private static void readEntry(Bundle restrictions, ArrayList<String> values,
2948 XmlPullParser parser) throws XmlPullParserException, IOException {
2949 int type = parser.getEventType();
2950 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
2951 String key = parser.getAttributeValue(null, ATTR_KEY);
2952 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
2953 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
2954 if (multiple != null) {
2955 values.clear();
2956 int count = Integer.parseInt(multiple);
2957 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
2958 if (type == XmlPullParser.START_TAG
2959 && parser.getName().equals(TAG_VALUE)) {
2960 values.add(parser.nextText().trim());
2961 count--;
2962 }
2963 }
2964 String [] valueStrings = new String[values.size()];
2965 values.toArray(valueStrings);
2966 restrictions.putStringArray(key, valueStrings);
2967 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
2968 restrictions.putBundle(key, readBundleEntry(parser, values));
2969 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
2970 final int outerDepth = parser.getDepth();
2971 ArrayList<Bundle> bundleList = new ArrayList<>();
2972 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2973 Bundle childBundle = readBundleEntry(parser, values);
2974 bundleList.add(childBundle);
2975 }
2976 restrictions.putParcelableArray(key,
2977 bundleList.toArray(new Bundle[bundleList.size()]));
2978 } else {
2979 String value = parser.nextText().trim();
2980 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
2981 restrictions.putBoolean(key, Boolean.parseBoolean(value));
2982 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
2983 restrictions.putInt(key, Integer.parseInt(value));
2984 } else {
2985 restrictions.putString(key, value);
2986 }
2987 }
2988 }
2989 }
2990
2991 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
2992 throws IOException, XmlPullParserException {
2993 Bundle childBundle = new Bundle();
2994 final int outerDepth = parser.getDepth();
2995 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2996 readEntry(childBundle, values, parser);
2997 }
2998 return childBundle;
2999 }
3000
Fyodor Kupolov82402752015-10-28 14:54:51 -07003001 private void writeApplicationRestrictionsLP(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07003002 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003003 AtomicFile restrictionsFile = new AtomicFile(
3004 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07003005 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003006 writeApplicationRestrictionsLP(restrictions, restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003007 }
3008
3009 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07003010 static void writeApplicationRestrictionsLP(Bundle restrictions, AtomicFile restrictionsFile) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003011 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003012 try {
3013 fos = restrictionsFile.startWrite();
3014 final BufferedOutputStream bos = new BufferedOutputStream(fos);
3015
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003016 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01003017 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003018 serializer.startDocument(null, true);
3019 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
3020
3021 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003022 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003023 serializer.endTag(null, TAG_RESTRICTIONS);
3024
3025 serializer.endDocument();
3026 restrictionsFile.finishWrite(fos);
3027 } catch (Exception e) {
3028 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003029 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
3030 }
3031 }
3032
3033 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
3034 throws IOException {
3035 for (String key : restrictions.keySet()) {
3036 Object value = restrictions.get(key);
3037 serializer.startTag(null, TAG_ENTRY);
3038 serializer.attribute(null, ATTR_KEY, key);
3039
3040 if (value instanceof Boolean) {
3041 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
3042 serializer.text(value.toString());
3043 } else if (value instanceof Integer) {
3044 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
3045 serializer.text(value.toString());
3046 } else if (value == null || value instanceof String) {
3047 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
3048 serializer.text(value != null ? (String) value : "");
3049 } else if (value instanceof Bundle) {
3050 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
3051 writeBundle((Bundle) value, serializer);
3052 } else if (value instanceof Parcelable[]) {
3053 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
3054 Parcelable[] array = (Parcelable[]) value;
3055 for (Parcelable parcelable : array) {
3056 if (!(parcelable instanceof Bundle)) {
3057 throw new IllegalArgumentException("bundle-array can only hold Bundles");
3058 }
3059 serializer.startTag(null, TAG_ENTRY);
3060 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
3061 writeBundle((Bundle) parcelable, serializer);
3062 serializer.endTag(null, TAG_ENTRY);
3063 }
3064 } else {
3065 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
3066 String[] values = (String[]) value;
3067 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
3068 for (String choice : values) {
3069 serializer.startTag(null, TAG_VALUE);
3070 serializer.text(choice != null ? choice : "");
3071 serializer.endTag(null, TAG_VALUE);
3072 }
3073 }
3074 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003075 }
3076 }
3077
3078 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07003079 public int getUserSerialNumber(int userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003080 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07003081 if (!exists(userHandle)) return -1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003082 return getUserInfoLU(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07003083 }
3084 }
3085
3086 @Override
Fyodor Kupolov605b12a2017-05-10 15:58:09 -07003087 public boolean isUserNameSet(int userHandle) {
3088 synchronized (mUsersLock) {
3089 UserInfo userInfo = getUserInfoLU(userHandle);
3090 return userInfo != null && userInfo.name != null;
3091 }
3092 }
3093
3094 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07003095 public int getUserHandle(int userSerialNumber) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003096 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07003097 for (int userId : mUserIds) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003098 UserInfo info = getUserInfoLU(userId);
Kenny Guy945f8832015-02-10 15:17:26 +00003099 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07003100 }
3101 // Not found
3102 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07003103 }
3104 }
3105
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003106 @Override
3107 public long getUserCreationTime(int userHandle) {
3108 int callingUserId = UserHandle.getCallingUserId();
3109 UserInfo userInfo = null;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003110 synchronized (mUsersLock) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003111 if (callingUserId == userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003112 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003113 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003114 UserInfo parent = getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003115 if (parent != null && parent.id == callingUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003116 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003117 }
3118 }
3119 }
3120 if (userInfo == null) {
3121 throw new SecurityException("userHandle can only be the calling user or a managed "
3122 + "profile associated with this user");
3123 }
3124 return userInfo.creationTime;
3125 }
3126
Amith Yamasani0b285492011-04-14 17:35:23 -07003127 /**
3128 * Caches the list of user ids in an array, adjusting the array size when necessary.
3129 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07003130 private void updateUserIds() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003131 int num = 0;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003132 synchronized (mUsersLock) {
3133 final int userSize = mUsers.size();
3134 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003135 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003136 num++;
3137 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003138 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07003139 final int[] newUsers = new int[num];
3140 int n = 0;
3141 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003142 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003143 newUsers[n++] = mUsers.keyAt(i);
3144 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003145 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07003146 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07003147 }
3148 }
3149
3150 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003151 * Called right before a user is started. This gives us a chance to prepare
3152 * app storage and apply any user restrictions.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003153 */
3154 public void onBeforeStartUser(int userId) {
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003155 UserInfo userInfo = getUserInfo(userId);
3156 if (userInfo == null) {
3157 return;
3158 }
3159 final int userSerial = userInfo.serialNumber;
3160 // Migrate only if build fingerprints mismatch
3161 boolean migrateAppsData = !Build.FINGERPRINT.equals(userInfo.lastLoggedInFingerprint);
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -08003162 mUserDataPreparer.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_DE);
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003163 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_DE, migrateAppsData);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003164
3165 if (userId != UserHandle.USER_SYSTEM) {
3166 synchronized (mRestrictionsLock) {
3167 applyUserRestrictionsLR(userId);
3168 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003169 }
3170 }
3171
3172 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003173 * Called right before a user is unlocked. This gives us a chance to prepare
3174 * app storage.
3175 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003176 public void onBeforeUnlockUser(@UserIdInt int userId) {
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003177 UserInfo userInfo = getUserInfo(userId);
3178 if (userInfo == null) {
3179 return;
3180 }
3181 final int userSerial = userInfo.serialNumber;
3182 // Migrate only if build fingerprints mismatch
3183 boolean migrateAppsData = !Build.FINGERPRINT.equals(userInfo.lastLoggedInFingerprint);
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -08003184 mUserDataPreparer.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_CE);
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003185 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_CE, migrateAppsData);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003186 }
3187
3188 /**
Fyodor Kupolov50979d12017-01-27 17:36:32 -08003189 * Examine all users present on given mounted volume, and destroy data
3190 * belonging to users that are no longer valid, or whose user ID has been
3191 * recycled.
3192 */
3193 void reconcileUsers(String volumeUuid) {
3194 mUserDataPreparer.reconcileUsers(volumeUuid, getUsers(true /* excludeDying */));
3195 }
3196
3197 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07003198 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasanieb437d42016-04-29 09:31:25 -07003199 * This is called with ActivityManagerService lock held.
Amith Yamasani920ace02012-09-20 22:15:37 -07003200 * @param userId the user that was just foregrounded
3201 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003202 public void onUserLoggedIn(@UserIdInt int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -08003203 UserData userData = getUserDataNoChecks(userId);
3204 if (userData == null || userData.info.partial) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003205 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
3206 return;
3207 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003208
3209 final long now = System.currentTimeMillis();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003210 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani12747872015-12-07 14:19:49 -08003211 userData.info.lastLoggedInTime = now;
Amith Yamasani920ace02012-09-20 22:15:37 -07003212 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003213 userData.info.lastLoggedInFingerprint = Build.FINGERPRINT;
3214 scheduleWriteUser(userData);
Amith Yamasani920ace02012-09-20 22:15:37 -07003215 }
3216
3217 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07003218 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani0b285492011-04-14 17:35:23 -07003219 */
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003220 @VisibleForTesting
3221 int getNextAvailableId() {
3222 int nextId;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003223 synchronized (mUsersLock) {
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003224 nextId = scanNextAvailableIdLocked();
3225 if (nextId >= 0) {
3226 return nextId;
3227 }
3228 // All ids up to MAX_USER_ID were used. Remove all mRemovingUserIds,
3229 // except most recently removed
3230 if (mRemovingUserIds.size() > 0) {
3231 Slog.i(LOG_TAG, "All available IDs are used. Recycling LRU ids.");
3232 mRemovingUserIds.clear();
3233 for (Integer recentlyRemovedId : mRecentlyRemovedIds) {
3234 mRemovingUserIds.put(recentlyRemovedId, true);
Amith Yamasani195263742012-08-21 15:40:12 -07003235 }
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003236 nextId = scanNextAvailableIdLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003237 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003238 }
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003239 if (nextId < 0) {
3240 throw new IllegalStateException("No user id available!");
3241 }
3242 return nextId;
3243 }
3244
3245 private int scanNextAvailableIdLocked() {
3246 for (int i = MIN_USER_ID; i < MAX_USER_ID; i++) {
3247 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
3248 return i;
3249 }
3250 }
3251 return -1;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003252 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003253
Amith Yamasanifc95e702013-09-26 13:20:17 -07003254 private String packageToRestrictionsFileName(String packageName) {
3255 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
3256 }
3257
Amith Yamasani920ace02012-09-20 22:15:37 -07003258 @Override
Amith Yamasani12747872015-12-07 14:19:49 -08003259 public void setSeedAccountData(int userId, String accountName, String accountType,
3260 PersistableBundle accountOptions, boolean persist) {
3261 checkManageUsersPermission("Require MANAGE_USERS permission to set user seed data");
3262 synchronized (mPackagesLock) {
3263 final UserData userData;
3264 synchronized (mUsersLock) {
3265 userData = getUserDataLU(userId);
3266 if (userData == null) {
3267 Slog.e(LOG_TAG, "No such user for settings seed data u=" + userId);
3268 return;
3269 }
3270 userData.seedAccountName = accountName;
3271 userData.seedAccountType = accountType;
3272 userData.seedAccountOptions = accountOptions;
3273 userData.persistSeedData = persist;
3274 }
3275 if (persist) {
3276 writeUserLP(userData);
3277 }
3278 }
3279 }
3280
3281 @Override
3282 public String getSeedAccountName() throws RemoteException {
3283 checkManageUsersPermission("Cannot get seed account information");
3284 synchronized (mUsersLock) {
3285 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3286 return userData.seedAccountName;
3287 }
3288 }
3289
3290 @Override
3291 public String getSeedAccountType() throws RemoteException {
3292 checkManageUsersPermission("Cannot get seed account information");
3293 synchronized (mUsersLock) {
3294 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3295 return userData.seedAccountType;
3296 }
3297 }
3298
3299 @Override
3300 public PersistableBundle getSeedAccountOptions() throws RemoteException {
3301 checkManageUsersPermission("Cannot get seed account information");
3302 synchronized (mUsersLock) {
3303 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3304 return userData.seedAccountOptions;
3305 }
3306 }
3307
3308 @Override
3309 public void clearSeedAccountData() throws RemoteException {
3310 checkManageUsersPermission("Cannot clear seed account information");
3311 synchronized (mPackagesLock) {
3312 UserData userData;
3313 synchronized (mUsersLock) {
3314 userData = getUserDataLU(UserHandle.getCallingUserId());
3315 if (userData == null) return;
3316 userData.clearSeedAccountData();
3317 }
3318 writeUserLP(userData);
3319 }
3320 }
3321
3322 @Override
3323 public boolean someUserHasSeedAccount(String accountName, String accountType)
3324 throws RemoteException {
3325 checkManageUsersPermission("Cannot check seed account information");
3326 synchronized (mUsersLock) {
3327 final int userSize = mUsers.size();
3328 for (int i = 0; i < userSize; i++) {
3329 final UserData data = mUsers.valueAt(i);
3330 if (data.info.isInitialized()) continue;
3331 if (data.seedAccountName == null || !data.seedAccountName.equals(accountName)) {
3332 continue;
3333 }
3334 if (data.seedAccountType == null || !data.seedAccountType.equals(accountType)) {
3335 continue;
3336 }
3337 return true;
3338 }
3339 }
3340 return false;
3341 }
3342
3343 @Override
Todd Kennedy60459ab2015-10-30 11:32:16 -07003344 public void onShellCommand(FileDescriptor in, FileDescriptor out,
Dianne Hackborn354736e2016-08-22 17:00:05 -07003345 FileDescriptor err, String[] args, ShellCallback callback,
3346 ResultReceiver resultReceiver) {
3347 (new Shell()).exec(this, in, out, err, args, callback, resultReceiver);
Todd Kennedy60459ab2015-10-30 11:32:16 -07003348 }
3349
3350 int onShellCommand(Shell shell, String cmd) {
3351 if (cmd == null) {
3352 return shell.handleDefaultCommands(cmd);
3353 }
3354
3355 final PrintWriter pw = shell.getOutPrintWriter();
3356 try {
3357 switch(cmd) {
3358 case "list":
3359 return runList(pw);
3360 }
3361 } catch (RemoteException e) {
3362 pw.println("Remote exception: " + e);
3363 }
3364 return -1;
3365 }
3366
3367 private int runList(PrintWriter pw) throws RemoteException {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003368 final IActivityManager am = ActivityManager.getService();
Todd Kennedy60459ab2015-10-30 11:32:16 -07003369 final List<UserInfo> users = getUsers(false);
3370 if (users == null) {
3371 pw.println("Error: couldn't get users");
3372 return 1;
3373 } else {
3374 pw.println("Users:");
3375 for (int i = 0; i < users.size(); i++) {
Jeff Sharkeye17ac152015-11-06 22:40:29 -08003376 String running = am.isUserRunning(users.get(i).id, 0) ? " running" : "";
Todd Kennedy60459ab2015-10-30 11:32:16 -07003377 pw.println("\t" + users.get(i).toString() + running);
3378 }
3379 return 0;
3380 }
3381 }
3382
3383 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -07003384 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06003385 if (!DumpUtils.checkDumpPermission(mContext, LOG_TAG, pw)) return;
Amith Yamasani920ace02012-09-20 22:15:37 -07003386
3387 long now = System.currentTimeMillis();
3388 StringBuilder sb = new StringBuilder();
3389 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003390 synchronized (mUsersLock) {
3391 pw.println("Users:");
3392 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003393 UserData userData = mUsers.valueAt(i);
3394 if (userData == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003395 continue;
3396 }
Amith Yamasani12747872015-12-07 14:19:49 -08003397 UserInfo userInfo = userData.info;
3398 final int userId = userInfo.id;
3399 pw.print(" "); pw.print(userInfo);
3400 pw.print(" serialNo="); pw.print(userInfo.serialNumber);
Makoto Onukie7927da2015-11-25 10:05:17 -08003401 if (mRemovingUserIds.get(userId)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003402 pw.print(" <removing> ");
3403 }
Amith Yamasani12747872015-12-07 14:19:49 -08003404 if (userInfo.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003405 pw.print(" <partial>");
3406 }
3407 pw.println();
Makoto Onuki88aef752017-03-29 16:52:03 -07003408 pw.print(" State: ");
3409 final int state;
3410 synchronized (mUserStates) {
3411 state = mUserStates.get(userId, -1);
3412 }
3413 pw.println(UserState.stateToString(state));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003414 pw.print(" Created: ");
Amith Yamasani12747872015-12-07 14:19:49 -08003415 if (userInfo.creationTime == 0) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003416 pw.println("<unknown>");
3417 } else {
3418 sb.setLength(0);
Amith Yamasani12747872015-12-07 14:19:49 -08003419 TimeUtils.formatDuration(now - userInfo.creationTime, sb);
Fyodor Kupolov82402752015-10-28 14:54:51 -07003420 sb.append(" ago");
3421 pw.println(sb);
3422 }
3423 pw.print(" Last logged in: ");
Amith Yamasani12747872015-12-07 14:19:49 -08003424 if (userInfo.lastLoggedInTime == 0) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003425 pw.println("<unknown>");
3426 } else {
3427 sb.setLength(0);
Amith Yamasani12747872015-12-07 14:19:49 -08003428 TimeUtils.formatDuration(now - userInfo.lastLoggedInTime, sb);
Fyodor Kupolov82402752015-10-28 14:54:51 -07003429 sb.append(" ago");
3430 pw.println(sb);
3431 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003432 pw.print(" Last logged in fingerprint: ");
3433 pw.println(userInfo.lastLoggedInFingerprint);
Makoto Onukie7927da2015-11-25 10:05:17 -08003434 pw.print(" Has profile owner: ");
3435 pw.println(mIsUserManaged.get(userId));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003436 pw.println(" Restrictions:");
3437 synchronized (mRestrictionsLock) {
3438 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003439 pw, " ", mBaseUserRestrictions.get(userInfo.id));
Pavel Grafov6a40f092016-10-25 15:46:51 +01003440 pw.println(" Device policy global restrictions:");
3441 UserRestrictionsUtils.dumpRestrictions(
3442 pw, " ", mDevicePolicyGlobalUserRestrictions.get(userInfo.id));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003443 pw.println(" Device policy local restrictions:");
3444 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003445 pw, " ", mDevicePolicyLocalUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003446 pw.println(" Effective restrictions:");
3447 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003448 pw, " ", mCachedEffectiveUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003449 }
Amith Yamasani12747872015-12-07 14:19:49 -08003450
3451 if (userData.account != null) {
3452 pw.print(" Account name: " + userData.account);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08003453 pw.println();
3454 }
Amith Yamasani12747872015-12-07 14:19:49 -08003455
3456 if (userData.seedAccountName != null) {
3457 pw.print(" Seed account name: " + userData.seedAccountName);
3458 pw.println();
3459 if (userData.seedAccountType != null) {
3460 pw.print(" account type: " + userData.seedAccountType);
3461 pw.println();
3462 }
3463 if (userData.seedAccountOptions != null) {
3464 pw.print(" account options exist");
3465 pw.println();
3466 }
3467 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003468 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003469 }
Amith Yamasani12747872015-12-07 14:19:49 -08003470 pw.println();
Pavel Grafov6a40f092016-10-25 15:46:51 +01003471 pw.println(" Device owner id:" + mDeviceOwnerUserId);
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01003472 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003473 pw.println(" Guest restrictions:");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003474 synchronized (mGuestRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003475 UserRestrictionsUtils.dumpRestrictions(pw, " ", mGuestRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003476 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003477 synchronized (mUsersLock) {
3478 pw.println();
3479 pw.println(" Device managed: " + mIsDeviceManaged);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003480 if (mRemovingUserIds.size() > 0) {
3481 pw.println();
3482 pw.println(" Recently removed userIds: " + mRecentlyRemovedIds);
3483 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003484 }
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003485 synchronized (mUserStates) {
3486 pw.println(" Started users state: " + mUserStates);
3487 }
Amith Yamasani12747872015-12-07 14:19:49 -08003488 // Dump some capabilities
3489 pw.println();
3490 pw.println(" Max users: " + UserManager.getMaxSupportedUsers());
3491 pw.println(" Supports switchable users: " + UserManager.supportsMultipleUsers());
Lenka Trochtova02fee152015-12-22 14:26:18 +01003492 pw.println(" All guests ephemeral: " + Resources.getSystem().getBoolean(
3493 com.android.internal.R.bool.config_guestUserEphemeral));
Amith Yamasani920ace02012-09-20 22:15:37 -07003494 }
3495 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08003496
3497 final class MainHandler extends Handler {
3498
3499 @Override
3500 public void handleMessage(Message msg) {
3501 switch (msg.what) {
3502 case WRITE_USER_MSG:
3503 removeMessages(WRITE_USER_MSG, msg.obj);
3504 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08003505 int userId = ((UserData) msg.obj).info.id;
3506 UserData userData = getUserDataNoChecks(userId);
3507 if (userData != null) {
3508 writeUserLP(userData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08003509 }
3510 }
3511 }
3512 }
3513 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07003514
3515 /**
3516 * @param userId
3517 * @return whether the user has been initialized yet
3518 */
3519 boolean isInitialized(int userId) {
3520 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
3521 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003522
3523 private class LocalService extends UserManagerInternal {
Makoto Onuki068c54a2015-10-13 14:34:03 -07003524 @Override
Pavel Grafov6a40f092016-10-25 15:46:51 +01003525 public void setDevicePolicyUserRestrictions(int userId, @Nullable Bundle restrictions,
3526 boolean isDeviceOwner, int cameraRestrictionScope) {
3527 UserManagerService.this.setDevicePolicyUserRestrictionsInner(userId, restrictions,
3528 isDeviceOwner, cameraRestrictionScope);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003529 }
3530
3531 @Override
3532 public Bundle getBaseUserRestrictions(int userId) {
3533 synchronized (mRestrictionsLock) {
3534 return mBaseUserRestrictions.get(userId);
3535 }
3536 }
3537
3538 @Override
3539 public void setBaseUserRestrictionsByDpmsForMigration(
3540 int userId, Bundle baseRestrictions) {
3541 synchronized (mRestrictionsLock) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01003542 if (updateRestrictionsIfNeededLR(
3543 userId, new Bundle(baseRestrictions), mBaseUserRestrictions)) {
3544 invalidateEffectiveUserRestrictionsLR(userId);
3545 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003546 }
3547
Amith Yamasani12747872015-12-07 14:19:49 -08003548 final UserData userData = getUserDataNoChecks(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003549 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08003550 if (userData != null) {
3551 writeUserLP(userData);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003552 } else {
3553 Slog.w(LOG_TAG, "UserInfo not found for " + userId);
3554 }
3555 }
3556 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08003557
3558 @Override
3559 public boolean getUserRestriction(int userId, String key) {
3560 return getUserRestrictions(userId).getBoolean(key);
3561 }
3562
3563 @Override
3564 public void addUserRestrictionsListener(UserRestrictionsListener listener) {
3565 synchronized (mUserRestrictionsListeners) {
3566 mUserRestrictionsListeners.add(listener);
3567 }
3568 }
3569
3570 @Override
3571 public void removeUserRestrictionsListener(UserRestrictionsListener listener) {
3572 synchronized (mUserRestrictionsListeners) {
3573 mUserRestrictionsListeners.remove(listener);
3574 }
3575 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003576
3577 @Override
3578 public void setDeviceManaged(boolean isManaged) {
3579 synchronized (mUsersLock) {
3580 mIsDeviceManaged = isManaged;
3581 }
3582 }
3583
3584 @Override
3585 public void setUserManaged(int userId, boolean isManaged) {
3586 synchronized (mUsersLock) {
3587 mIsUserManaged.put(userId, isManaged);
3588 }
3589 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01003590
3591 @Override
3592 public void setUserIcon(int userId, Bitmap bitmap) {
3593 long ident = Binder.clearCallingIdentity();
3594 try {
3595 synchronized (mPackagesLock) {
3596 UserData userData = getUserDataNoChecks(userId);
3597 if (userData == null || userData.info.partial) {
3598 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
3599 return;
3600 }
3601 writeBitmapLP(userData.info, bitmap);
3602 writeUserLP(userData);
3603 }
3604 sendUserInfoChangedBroadcast(userId);
3605 } finally {
3606 Binder.restoreCallingIdentity(ident);
3607 }
3608 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01003609
3610 @Override
3611 public void setForceEphemeralUsers(boolean forceEphemeralUsers) {
3612 synchronized (mUsersLock) {
3613 mForceEphemeralUsers = forceEphemeralUsers;
3614 }
3615 }
3616
3617 @Override
3618 public void removeAllUsers() {
3619 if (UserHandle.USER_SYSTEM == ActivityManager.getCurrentUser()) {
3620 // Remove the non-system users straight away.
3621 removeNonSystemUsers();
3622 } else {
3623 // Switch to the system user first and then remove the other users.
3624 BroadcastReceiver userSwitchedReceiver = new BroadcastReceiver() {
3625 @Override
3626 public void onReceive(Context context, Intent intent) {
3627 int userId =
3628 intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3629 if (userId != UserHandle.USER_SYSTEM) {
3630 return;
3631 }
3632 mContext.unregisterReceiver(this);
3633 removeNonSystemUsers();
3634 }
3635 };
3636 IntentFilter userSwitchedFilter = new IntentFilter();
3637 userSwitchedFilter.addAction(Intent.ACTION_USER_SWITCHED);
3638 mContext.registerReceiver(
3639 userSwitchedReceiver, userSwitchedFilter, null, mHandler);
3640
3641 // Switch to the system user.
3642 ActivityManager am =
3643 (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
3644 am.switchUser(UserHandle.USER_SYSTEM);
3645 }
3646 }
phweisse9c44062016-02-10 12:57:38 +01003647
3648 @Override
Lenka Trochtova1ddda472016-02-12 10:42:12 +01003649 public void onEphemeralUserStop(int userId) {
3650 synchronized (mUsersLock) {
3651 UserInfo userInfo = getUserInfoLU(userId);
3652 if (userInfo != null && userInfo.isEphemeral()) {
3653 // Do not allow switching back to the ephemeral user again as the user is going
3654 // to be deleted.
3655 userInfo.flags |= UserInfo.FLAG_DISABLED;
3656 if (userInfo.isGuest()) {
3657 // Indicate that the guest will be deleted after it stops.
3658 userInfo.guestToRemove = true;
3659 }
3660 }
3661 }
3662 }
3663
3664 @Override
phweisse9c44062016-02-10 12:57:38 +01003665 public UserInfo createUserEvenWhenDisallowed(String name, int flags) {
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07003666 UserInfo user = createUserInternalUnchecked(name, flags, UserHandle.USER_NULL, null);
phweisse9c44062016-02-10 12:57:38 +01003667 // Keep this in sync with UserManager.createUser
Christine Franks97a54802017-08-09 10:06:43 -07003668 if (user != null && !user.isAdmin() && !user.isDemo()) {
phweisse9c44062016-02-10 12:57:38 +01003669 setUserRestriction(UserManager.DISALLOW_SMS, true, user.id);
3670 setUserRestriction(UserManager.DISALLOW_OUTGOING_CALLS, true, user.id);
3671 }
3672 return user;
3673 }
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003674
3675 @Override
Nicolas Prevotdf1b87d2016-10-25 13:57:08 +01003676 public boolean removeUserEvenWhenDisallowed(int userId) {
3677 return removeUserUnchecked(userId);
3678 }
3679
3680 @Override
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003681 public boolean isUserRunning(int userId) {
3682 synchronized (mUserStates) {
3683 return mUserStates.get(userId, -1) >= 0;
3684 }
3685 }
3686
3687 @Override
3688 public void setUserState(int userId, int userState) {
3689 synchronized (mUserStates) {
3690 mUserStates.put(userId, userState);
3691 }
3692 }
3693
3694 @Override
3695 public void removeUserState(int userId) {
3696 synchronized (mUserStates) {
3697 mUserStates.delete(userId);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003698 }
3699 }
3700
3701 @Override
Michael Wachenschwanz3f2b6552017-05-15 13:53:09 -07003702 public int[] getUserIds() {
3703 return UserManagerService.this.getUserIds();
3704 }
3705
3706 @Override
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003707 public boolean isUserUnlockingOrUnlocked(int userId) {
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003708 synchronized (mUserStates) {
3709 int state = mUserStates.get(userId, -1);
3710 return (state == UserState.STATE_RUNNING_UNLOCKING)
3711 || (state == UserState.STATE_RUNNING_UNLOCKED);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003712 }
3713 }
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08003714
3715 @Override
3716 public boolean isUserUnlocked(int userId) {
3717 synchronized (mUserStates) {
3718 int state = mUserStates.get(userId, -1);
3719 return state == UserState.STATE_RUNNING_UNLOCKED;
3720 }
3721 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01003722 }
3723
3724 /* Remove all the users except of the system one. */
3725 private void removeNonSystemUsers() {
3726 ArrayList<UserInfo> usersToRemove = new ArrayList<>();
3727 synchronized (mUsersLock) {
3728 final int userSize = mUsers.size();
3729 for (int i = 0; i < userSize; i++) {
3730 UserInfo ui = mUsers.valueAt(i).info;
3731 if (ui.id != UserHandle.USER_SYSTEM) {
3732 usersToRemove.add(ui);
3733 }
3734 }
3735 }
3736 for (UserInfo ui: usersToRemove) {
3737 removeUser(ui.id);
3738 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003739 }
Todd Kennedy60459ab2015-10-30 11:32:16 -07003740
3741 private class Shell extends ShellCommand {
3742 @Override
3743 public int onCommand(String cmd) {
3744 return onShellCommand(this, cmd);
3745 }
3746
3747 @Override
3748 public void onHelp() {
3749 final PrintWriter pw = getOutPrintWriter();
3750 pw.println("User manager (user) commands:");
3751 pw.println(" help");
3752 pw.println(" Print this help text.");
3753 pw.println("");
3754 pw.println(" list");
3755 pw.println(" Prints all users on the system.");
3756 }
3757 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003758
3759 private static void debug(String message) {
3760 Log.d(LOG_TAG, message +
3761 (DBG_WITH_STACKTRACE ? " called at\n" + Debug.getCallers(10, " ") : ""));
3762 }
Kenny Guy02c89902016-11-15 19:36:38 +00003763
3764 @VisibleForTesting
3765 static int getMaxManagedProfiles() {
3766 // Allow overriding max managed profiles on debuggable builds for testing
3767 // of multiple profiles.
3768 if (!Build.IS_DEBUGGABLE) {
3769 return MAX_MANAGED_PROFILES;
3770 } else {
3771 return SystemProperties.getInt("persist.sys.max_profiles",
3772 MAX_MANAGED_PROFILES);
3773 }
3774 }
3775
3776 @VisibleForTesting
3777 int getFreeProfileBadgeLU(int parentUserId) {
3778 int maxManagedProfiles = getMaxManagedProfiles();
3779 boolean[] usedBadges = new boolean[maxManagedProfiles];
3780 final int userSize = mUsers.size();
3781 for (int i = 0; i < userSize; i++) {
3782 UserInfo ui = mUsers.valueAt(i).info;
3783 // Check which badge indexes are already used by this profile group.
3784 if (ui.isManagedProfile()
3785 && ui.profileGroupId == parentUserId
3786 && !mRemovingUserIds.get(ui.id)
3787 && ui.profileBadge < maxManagedProfiles) {
3788 usedBadges[ui.profileBadge] = true;
3789 }
3790 }
3791 for (int i = 0; i < maxManagedProfiles; i++) {
3792 if (!usedBadges[i]) {
3793 return i;
3794 }
3795 }
3796 return 0;
3797 }
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07003798
3799 /**
3800 * Checks if the given user has a managed profile associated with it.
3801 * @param userId The parent user
3802 * @return
3803 */
3804 boolean hasManagedProfile(int userId) {
3805 synchronized (mUsersLock) {
3806 UserInfo userInfo = getUserInfoLU(userId);
3807 final int userSize = mUsers.size();
3808 for (int i = 0; i < userSize; i++) {
3809 UserInfo profile = mUsers.valueAt(i).info;
3810 if (userId != profile.id && isProfileOf(userInfo, profile)) {
3811 return true;
3812 }
3813 }
3814 return false;
3815 }
3816 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003817}