blob: afa7a24ec4a80dc67ab11dba42b94a22e06b2a8c [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
Fyodor Kupolov82402752015-10-28 14:54:51 -0700717 private UserInfo getProfileParentLU(int userHandle) {
718 UserInfo profile = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700719 if (profile == null) {
720 return null;
721 }
722 int parentUserId = profile.profileGroupId;
Amith Yamasani801e3422017-01-25 11:35:44 -0800723 if (parentUserId == userHandle || parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700724 return null;
725 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700726 return getUserInfoLU(parentUserId);
Jessica Hummelbe81c802014-04-22 15:49:22 +0100727 }
728 }
729
Fyodor Kupolov82402752015-10-28 14:54:51 -0700730 private static boolean isProfileOf(UserInfo user, UserInfo profile) {
Kenny Guy2a764942014-04-02 13:29:20 +0100731 return user.id == profile.id ||
732 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
733 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000734 }
735
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000736 private void broadcastProfileAvailabilityChanges(UserHandle profileHandle,
Rubin Xuf13c9802016-01-21 18:06:00 +0000737 UserHandle parentHandle, boolean inQuietMode) {
Rubin Xue95057a2016-04-01 16:49:25 +0100738 Intent intent = new Intent();
739 if (inQuietMode) {
740 intent.setAction(Intent.ACTION_MANAGED_PROFILE_UNAVAILABLE);
741 } else {
742 intent.setAction(Intent.ACTION_MANAGED_PROFILE_AVAILABLE);
743 }
Rubin Xuf13c9802016-01-21 18:06:00 +0000744 intent.putExtra(Intent.EXTRA_QUIET_MODE, inQuietMode);
745 intent.putExtra(Intent.EXTRA_USER, profileHandle);
746 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileHandle.getIdentifier());
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000747 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Rubin Xuf13c9802016-01-21 18:06:00 +0000748 mContext.sendBroadcastAsUser(intent, parentHandle);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000749 }
750
751 @Override
752 public void setQuietModeEnabled(int userHandle, boolean enableQuietMode) {
753 checkManageUsersPermission("silence profile");
754 boolean changed = false;
755 UserInfo profile, parent;
756 synchronized (mPackagesLock) {
757 synchronized (mUsersLock) {
758 profile = getUserInfoLU(userHandle);
759 parent = getProfileParentLU(userHandle);
760
761 }
762 if (profile == null || !profile.isManagedProfile()) {
763 throw new IllegalArgumentException("User " + userHandle + " is not a profile");
764 }
765 if (profile.isQuietModeEnabled() != enableQuietMode) {
766 profile.flags ^= UserInfo.FLAG_QUIET_MODE;
Amith Yamasani12747872015-12-07 14:19:49 -0800767 writeUserLP(getUserDataLU(profile.id));
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000768 changed = true;
769 }
770 }
771 if (changed) {
Rubin Xuf13c9802016-01-21 18:06:00 +0000772 long identity = Binder.clearCallingIdentity();
773 try {
774 if (enableQuietMode) {
Sudheer Shankadc589ac2016-11-10 15:30:17 -0800775 ActivityManager.getService().stopUser(userHandle, /* force */true, null);
Rubin Xuf8451b92016-04-01 15:50:58 +0100776 LocalServices.getService(ActivityManagerInternal.class)
777 .killForegroundAppsForUser(userHandle);
Rubin Xuf13c9802016-01-21 18:06:00 +0000778 } else {
Sudheer Shankadc589ac2016-11-10 15:30:17 -0800779 ActivityManager.getService().startUserInBackground(userHandle);
Rubin Xuf13c9802016-01-21 18:06:00 +0000780 }
781 } catch (RemoteException e) {
782 Slog.e(LOG_TAG, "fail to start/stop user for quiet mode", e);
783 } finally {
784 Binder.restoreCallingIdentity(identity);
785 }
786
787 broadcastProfileAvailabilityChanges(profile.getUserHandle(), parent.getUserHandle(),
788 enableQuietMode);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000789 }
790 }
791
792 @Override
793 public boolean isQuietModeEnabled(int userHandle) {
794 synchronized (mPackagesLock) {
795 UserInfo info;
796 synchronized (mUsersLock) {
797 info = getUserInfoLU(userHandle);
798 }
799 if (info == null || !info.isManagedProfile()) {
Rubin Xuf13c9802016-01-21 18:06:00 +0000800 return false;
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000801 }
802 return info.isQuietModeEnabled();
803 }
804 }
805
Kenny Guya52dc3e2014-02-11 15:33:14 +0000806 @Override
Benjamin Franzf02420c2016-04-04 18:52:21 +0100807 public boolean trySetQuietModeDisabled(int userHandle, IntentSender target) {
Ricky Waib1dd80b2016-06-07 18:00:55 +0100808 checkManageUsersPermission("silence profile");
Jeff Sharkeyce18c812016-04-27 16:00:41 -0600809 if (StorageManager.isUserKeyUnlocked(userHandle)
Ricky Wai9cc7ad62016-05-11 18:00:20 +0100810 || !mLockPatternUtils.isSecure(userHandle)) {
Benjamin Franzf02420c2016-04-04 18:52:21 +0100811 // if the user is already unlocked, no need to show a profile challenge
812 setQuietModeEnabled(userHandle, false);
813 return true;
814 }
815
816 long identity = Binder.clearCallingIdentity();
817 try {
818 // otherwise, we show a profile challenge to trigger decryption of the user
819 final KeyguardManager km = (KeyguardManager) mContext.getSystemService(
820 Context.KEYGUARD_SERVICE);
Ricky Wai7881cf82016-04-15 17:20:12 +0100821 // We should use userHandle not credentialOwnerUserId here, as even if it is unified
822 // lock, confirm screenlock page will know and show personal challenge, and unlock
823 // work profile when personal challenge is correct
Benjamin Franzf02420c2016-04-04 18:52:21 +0100824 final Intent unlockIntent = km.createConfirmDeviceCredentialIntent(null, null,
825 userHandle);
826 if (unlockIntent == null) {
827 return false;
828 }
Ricky Waib1dd80b2016-06-07 18:00:55 +0100829 final Intent callBackIntent = new Intent(
830 ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK);
Benjamin Franzf02420c2016-04-04 18:52:21 +0100831 if (target != null) {
Ricky Waib1dd80b2016-06-07 18:00:55 +0100832 callBackIntent.putExtra(Intent.EXTRA_INTENT, target);
Benjamin Franzf02420c2016-04-04 18:52:21 +0100833 }
Ricky Waib1dd80b2016-06-07 18:00:55 +0100834 callBackIntent.putExtra(Intent.EXTRA_USER_ID, userHandle);
835 callBackIntent.setPackage(mContext.getPackageName());
836 callBackIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
837 final PendingIntent pendingIntent = PendingIntent.getBroadcast(
838 mContext,
839 0,
840 callBackIntent,
841 PendingIntent.FLAG_CANCEL_CURRENT |
842 PendingIntent.FLAG_ONE_SHOT |
843 PendingIntent.FLAG_IMMUTABLE);
844 // After unlocking the challenge, it will disable quiet mode and run the original
845 // intentSender
846 unlockIntent.putExtra(Intent.EXTRA_INTENT, pendingIntent.getIntentSender());
Benjamin Franzf02420c2016-04-04 18:52:21 +0100847 unlockIntent.setFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
848 mContext.startActivity(unlockIntent);
849 } finally {
850 Binder.restoreCallingIdentity(identity);
851 }
852 return false;
853 }
854
855 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100856 public void setUserEnabled(int userId) {
857 checkManageUsersPermission("enable user");
858 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700859 UserInfo info;
860 synchronized (mUsersLock) {
861 info = getUserInfoLU(userId);
862 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100863 if (info != null && !info.isEnabled()) {
864 info.flags ^= UserInfo.FLAG_DISABLED;
Amith Yamasani12747872015-12-07 14:19:49 -0800865 writeUserLP(getUserDataLU(info.id));
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100866 }
867 }
868 }
869
Andrew Scull85a63bc2016-10-24 13:47:47 +0100870 /**
871 * Evicts a user's CE key by stopping and restarting the user.
872 *
873 * The key is evicted automatically by the user controller when the user has stopped.
874 */
875 @Override
876 public void evictCredentialEncryptionKey(@UserIdInt int userId) {
877 checkManageUsersPermission("evict CE key");
878 final IActivityManager am = ActivityManagerNative.getDefault();
879 final long identity = Binder.clearCallingIdentity();
880 try {
881 am.restartUserInBackground(userId);
882 } catch (RemoteException re) {
883 throw re.rethrowAsRuntimeException();
884 } finally {
885 Binder.restoreCallingIdentity(identity);
886 }
887 }
888
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100889 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700890 public UserInfo getUserInfo(int userId) {
Sudheer Shankaaccaa082016-06-14 16:22:57 -0700891 checkManageOrCreateUsersPermission("query user");
Tony Mak8673b282016-03-21 21:10:59 +0000892 synchronized (mUsersLock) {
Amith Yamasani6f48d6e2016-03-23 14:28:25 -0700893 return userWithName(getUserInfoLU(userId));
894 }
895 }
896
897 /**
898 * Returns a UserInfo object with the name filled in, for Owner, or the original
899 * if the name is already set.
900 */
901 private UserInfo userWithName(UserInfo orig) {
902 if (orig != null && orig.name == null && orig.id == UserHandle.USER_SYSTEM) {
903 UserInfo withName = new UserInfo(orig);
904 withName.name = getOwnerName();
905 return withName;
906 } else {
907 return orig;
Tony Mak8673b282016-03-21 21:10:59 +0000908 }
909 }
910
911 @Override
Kenny Guy02c89902016-11-15 19:36:38 +0000912 public int getManagedProfileBadge(@UserIdInt int userId) {
913 int callingUserId = UserHandle.getCallingUserId();
914 if (callingUserId != userId && !hasManageUsersPermission()) {
915 if (!isSameProfileGroupNoChecks(callingUserId, userId)) {
916 throw new SecurityException(
917 "You need MANAGE_USERS permission to: check if specified user a " +
918 "managed profile outside your profile group");
919 }
920 }
921 synchronized (mUsersLock) {
922 UserInfo userInfo = getUserInfoLU(userId);
923 return userInfo != null ? userInfo.profileBadge : 0;
924 }
925 }
926
927 @Override
Tony Mak8673b282016-03-21 21:10:59 +0000928 public boolean isManagedProfile(int userId) {
Tony Makb531d082016-03-16 14:49:52 +0000929 int callingUserId = UserHandle.getCallingUserId();
930 if (callingUserId != userId && !hasManageUsersPermission()) {
Fyodor Kupolov0fb772e2016-10-13 16:27:34 -0700931 if (!isSameProfileGroupNoChecks(callingUserId, userId)) {
Fyodor Kupolovc413f702016-10-06 17:11:14 -0700932 throw new SecurityException(
933 "You need MANAGE_USERS permission to: check if specified user a " +
934 "managed profile outside your profile group");
Tony Makb531d082016-03-16 14:49:52 +0000935 }
Tony Mak4dc008c2016-03-16 10:46:49 +0000936 }
Fyodor Kupolov82402752015-10-28 14:54:51 -0700937 synchronized (mUsersLock) {
Amith Yamasani1c41dc82016-06-28 16:13:15 -0700938 UserInfo userInfo = getUserInfoLU(userId);
Tony Mak8673b282016-03-21 21:10:59 +0000939 return userInfo != null && userInfo.isManagedProfile();
Amith Yamasani13593602012-03-22 16:16:17 -0700940 }
941 }
942
Amith Yamasani71e6c692013-03-24 17:39:28 -0700943 @Override
Fyodor Kupolovc413f702016-10-06 17:11:14 -0700944 public boolean isUserUnlockingOrUnlocked(int userId) {
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -0800945 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isUserUnlockingOrUnlocked");
Fyodor Kupolovc413f702016-10-06 17:11:14 -0700946 return mLocalService.isUserUnlockingOrUnlocked(userId);
947 }
948
949 @Override
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -0800950 public boolean isUserUnlocked(int userId) {
951 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isUserUnlocked");
Fyodor Kupolov0468ee92017-05-25 17:06:17 -0700952 return mLocalService.isUserUnlocked(userId);
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -0800953 }
954
955 @Override
956 public boolean isUserRunning(int userId) {
957 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isUserRunning");
958 return mLocalService.isUserRunning(userId);
959 }
960
961 private void checkManageOrInteractPermIfCallerInOtherProfileGroup(int userId, String name) {
962 int callingUserId = UserHandle.getCallingUserId();
963 if (callingUserId == userId || isSameProfileGroupNoChecks(callingUserId, userId) ||
964 hasManageUsersPermission()) {
965 return;
966 }
967 if (ActivityManager.checkComponentPermission(Manifest.permission.INTERACT_ACROSS_USERS,
968 Binder.getCallingUid(), -1, true) != PackageManager.PERMISSION_GRANTED) {
969 throw new SecurityException("You need INTERACT_ACROSS_USERS or MANAGE_USERS permission "
970 + "to: check " + name);
971 }
972 }
973
974 @Override
Amith Yamasani1c41dc82016-06-28 16:13:15 -0700975 public boolean isDemoUser(int userId) {
976 int callingUserId = UserHandle.getCallingUserId();
977 if (callingUserId != userId && !hasManageUsersPermission()) {
978 throw new SecurityException("You need MANAGE_USERS permission to query if u=" + userId
979 + " is a demo user");
980 }
981 synchronized (mUsersLock) {
982 UserInfo userInfo = getUserInfoLU(userId);
983 return userInfo != null && userInfo.isDemo();
984 }
985 }
986
987 @Override
Amith Yamasani71e6c692013-03-24 17:39:28 -0700988 public boolean isRestricted() {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700989 synchronized (mUsersLock) {
990 return getUserInfoLU(UserHandle.getCallingUserId()).isRestricted();
Amith Yamasani71e6c692013-03-24 17:39:28 -0700991 }
992 }
993
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700994 @Override
995 public boolean canHaveRestrictedProfile(int userId) {
996 checkManageUsersPermission("canHaveRestrictedProfile");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700997 synchronized (mUsersLock) {
998 final UserInfo userInfo = getUserInfoLU(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700999 if (userInfo == null || !userInfo.canHaveProfile()) {
1000 return false;
1001 }
1002 if (!userInfo.isAdmin()) {
1003 return false;
1004 }
Makoto Onukie7927da2015-11-25 10:05:17 -08001005 // restricted profile can be created if there is no DO set and the admin user has no PO;
1006 return !mIsDeviceManaged && !mIsUserManaged.get(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001007 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001008 }
1009
Amith Yamasani195263742012-08-21 15:40:12 -07001010 /*
1011 * Should be locked on mUsers before calling this.
1012 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001013 private UserInfo getUserInfoLU(int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -08001014 final UserData userData = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -07001015 // If it is partial and not in the process of being removed, return as unknown user.
Amith Yamasani12747872015-12-07 14:19:49 -08001016 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001017 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
1018 return null;
1019 }
Amith Yamasani12747872015-12-07 14:19:49 -08001020 return userData != null ? userData.info : null;
1021 }
1022
1023 private UserData getUserDataLU(int userId) {
1024 final UserData userData = mUsers.get(userId);
1025 // If it is partial and not in the process of being removed, return as unknown user.
1026 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
1027 return null;
1028 }
1029 return userData;
Amith Yamasani195263742012-08-21 15:40:12 -07001030 }
1031
Fyodor Kupolov82402752015-10-28 14:54:51 -07001032 /**
1033 * Obtains {@link #mUsersLock} and return UserInfo from mUsers.
1034 * <p>No permissions checking or any addition checks are made</p>
1035 */
1036 private UserInfo getUserInfoNoChecks(int userId) {
1037 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001038 final UserData userData = mUsers.get(userId);
1039 return userData != null ? userData.info : null;
1040 }
1041 }
1042
1043 /**
1044 * Obtains {@link #mUsersLock} and return UserData from mUsers.
1045 * <p>No permissions checking or any addition checks are made</p>
1046 */
1047 private UserData getUserDataNoChecks(int userId) {
1048 synchronized (mUsersLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001049 return mUsers.get(userId);
1050 }
1051 }
1052
Amith Yamasani236b2b52015-08-18 14:32:14 -07001053 /** Called by PackageManagerService */
Amith Yamasani13593602012-03-22 16:16:17 -07001054 public boolean exists(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001055 return getUserInfoNoChecks(userId) != null;
Amith Yamasani13593602012-03-22 16:16:17 -07001056 }
1057
Amith Yamasani258848d2012-08-10 17:06:33 -07001058 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001059 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001060 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001061 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -07001062 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001063 UserData userData = getUserDataNoChecks(userId);
1064 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001065 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
1066 return;
1067 }
Amith Yamasani12747872015-12-07 14:19:49 -08001068 if (name != null && !name.equals(userData.info.name)) {
1069 userData.info.name = name;
1070 writeUserLP(userData);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001071 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -07001072 }
1073 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001074 if (changed) {
1075 sendUserInfoChangedBroadcast(userId);
1076 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001077 }
1078
Amith Yamasani258848d2012-08-10 17:06:33 -07001079 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001080 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001081 checkManageUsersPermission("update users");
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01001082 if (hasUserRestriction(UserManager.DISALLOW_SET_USER_ICON, userId)) {
1083 Log.w(LOG_TAG, "Cannot set user icon. DISALLOW_SET_USER_ICON is enabled.");
1084 return;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001085 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01001086 mLocalService.setUserIcon(userId, bitmap);
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001087 }
1088
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01001089
1090
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001091 private void sendUserInfoChangedBroadcast(int userId) {
1092 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
1093 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
1094 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -07001095 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001096 }
1097
Amith Yamasani258848d2012-08-10 17:06:33 -07001098 @Override
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001099 public ParcelFileDescriptor getUserIcon(int targetUserId) {
Adrian Roos1bdff912015-02-17 15:51:35 +01001100 String iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001101 synchronized (mPackagesLock) {
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001102 UserInfo targetUserInfo = getUserInfoNoChecks(targetUserId);
1103 if (targetUserInfo == null || targetUserInfo.partial) {
1104 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + targetUserId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001105 return null;
1106 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001107
1108 final int callingUserId = UserHandle.getCallingUserId();
1109 final int callingGroupId = getUserInfoNoChecks(callingUserId).profileGroupId;
1110 final int targetGroupId = targetUserInfo.profileGroupId;
1111 final boolean sameGroup = (callingGroupId != UserInfo.NO_PROFILE_GROUP_ID
1112 && callingGroupId == targetGroupId);
1113 if ((callingUserId != targetUserId) && !sameGroup) {
Nicolas Prevot88cc3462014-05-14 14:51:48 +01001114 checkManageUsersPermission("get the icon of a user who is not related");
1115 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001116
1117 if (targetUserInfo.iconPath == null) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001118 return null;
1119 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001120 iconPath = targetUserInfo.iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001121 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001122
1123 try {
1124 return ParcelFileDescriptor.open(
1125 new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
1126 } catch (FileNotFoundException e) {
1127 Log.e(LOG_TAG, "Couldn't find icon file", e);
1128 }
1129 return null;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001130 }
1131
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001132 public void makeInitialized(int userId) {
1133 checkManageUsersPermission("makeInitialized");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001134 boolean scheduleWriteUser = false;
Amith Yamasani12747872015-12-07 14:19:49 -08001135 UserData userData;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001136 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001137 userData = mUsers.get(userId);
1138 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001139 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001140 return;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001141 }
Amith Yamasani12747872015-12-07 14:19:49 -08001142 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1143 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001144 scheduleWriteUser = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001145 }
1146 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001147 if (scheduleWriteUser) {
Amith Yamasani12747872015-12-07 14:19:49 -08001148 scheduleWriteUser(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001149 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001150 }
1151
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001152 /**
1153 * If default guest restrictions haven't been initialized yet, add the basic
1154 * restrictions.
1155 */
1156 private void initDefaultGuestRestrictions() {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001157 synchronized (mGuestRestrictions) {
1158 if (mGuestRestrictions.isEmpty()) {
Samuel Tand9453b82016-03-14 15:57:02 -07001159 mGuestRestrictions.putBoolean(UserManager.DISALLOW_CONFIG_WIFI, true);
Fyodor Kupolove04462c2015-11-30 15:02:53 -08001160 mGuestRestrictions.putBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, true);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001161 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
1162 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
1163 }
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001164 }
1165 }
1166
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001167 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301168 public Bundle getDefaultGuestRestrictions() {
1169 checkManageUsersPermission("getDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001170 synchronized (mGuestRestrictions) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301171 return new Bundle(mGuestRestrictions);
1172 }
1173 }
1174
1175 @Override
1176 public void setDefaultGuestRestrictions(Bundle restrictions) {
1177 checkManageUsersPermission("setDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001178 synchronized (mGuestRestrictions) {
1179 mGuestRestrictions.clear();
1180 mGuestRestrictions.putAll(restrictions);
1181 }
1182 synchronized (mPackagesLock) {
1183 writeUserListLP();
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301184 }
1185 }
1186
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001187 /**
Pavel Grafov6a40f092016-10-25 15:46:51 +01001188 * See {@link UserManagerInternal#setDevicePolicyUserRestrictions}
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001189 */
Pavel Grafov6a40f092016-10-25 15:46:51 +01001190 private void setDevicePolicyUserRestrictionsInner(int userId, @Nullable Bundle restrictions,
1191 boolean isDeviceOwner, int cameraRestrictionScope) {
1192 final Bundle global = new Bundle();
1193 final Bundle local = new Bundle();
1194
1195 // Sort restrictions into local and global ensuring they don't overlap.
1196 UserRestrictionsUtils.sortToGlobalAndLocal(restrictions, isDeviceOwner,
1197 cameraRestrictionScope, global, local);
1198
1199 boolean globalChanged, localChanged;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001200 synchronized (mRestrictionsLock) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001201 // Update global and local restrictions if they were changed.
1202 globalChanged = updateRestrictionsIfNeededLR(
1203 userId, global, mDevicePolicyGlobalUserRestrictions);
1204 localChanged = updateRestrictionsIfNeededLR(
1205 userId, local, mDevicePolicyLocalUserRestrictions);
1206
1207 if (isDeviceOwner) {
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001208 // Remember the global restriction owner userId to be able to make a distinction
1209 // in getUserRestrictionSource on who set local policies.
Pavel Grafov6a40f092016-10-25 15:46:51 +01001210 mDeviceOwnerUserId = userId;
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001211 } else {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001212 if (mDeviceOwnerUserId == userId) {
Zoltan Szatmary-Ban8a5536d2016-05-27 17:56:44 +01001213 // When profile owner sets restrictions it passes null global bundle and we
1214 // reset global restriction owner userId.
1215 // This means this user used to have DO, but now the DO is gone and the user
1216 // instead has PO.
Pavel Grafov6a40f092016-10-25 15:46:51 +01001217 mDeviceOwnerUserId = UserHandle.USER_NULL;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001218 }
1219 }
1220 }
1221 if (DBG) {
1222 Log.d(LOG_TAG, "setDevicePolicyUserRestrictions: userId=" + userId
1223 + " global=" + global + (globalChanged ? " (changed)" : "")
1224 + " local=" + local + (localChanged ? " (changed)" : "")
1225 );
1226 }
1227 // Don't call them within the mRestrictionsLock.
1228 synchronized (mPackagesLock) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001229 if (localChanged || globalChanged) {
Amith Yamasani12747872015-12-07 14:19:49 -08001230 writeUserLP(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001231 }
1232 }
1233
1234 synchronized (mRestrictionsLock) {
1235 if (globalChanged) {
1236 applyUserRestrictionsForAllUsersLR();
1237 } else if (localChanged) {
1238 applyUserRestrictionsLR(userId);
1239 }
1240 }
1241 }
1242
Pavel Grafov6a40f092016-10-25 15:46:51 +01001243 /**
1244 * Updates restriction bundle for a given user in a given restriction array. If new bundle is
1245 * empty, record is removed from the array.
1246 * @return whether restrictions bundle is different from the old one.
1247 */
1248 private boolean updateRestrictionsIfNeededLR(int userId, @Nullable Bundle restrictions,
1249 SparseArray<Bundle> restrictionsArray) {
1250 final boolean changed =
1251 !UserRestrictionsUtils.areEqual(restrictionsArray.get(userId), restrictions);
1252 if (changed) {
1253 if (!UserRestrictionsUtils.isEmpty(restrictions)) {
1254 restrictionsArray.put(userId, restrictions);
1255 } else {
1256 restrictionsArray.delete(userId);
1257 }
1258 }
1259 return changed;
1260 }
1261
Makoto Onuki068c54a2015-10-13 14:34:03 -07001262 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001263 private Bundle computeEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001264 final Bundle baseRestrictions =
1265 UserRestrictionsUtils.nonNull(mBaseUserRestrictions.get(userId));
Pavel Grafov6a40f092016-10-25 15:46:51 +01001266 final Bundle global = UserRestrictionsUtils.mergeAll(mDevicePolicyGlobalUserRestrictions);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001267 final Bundle local = mDevicePolicyLocalUserRestrictions.get(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001268
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001269 if (UserRestrictionsUtils.isEmpty(global) && UserRestrictionsUtils.isEmpty(local)) {
1270 // Common case first.
1271 return baseRestrictions;
Makoto Onuki068c54a2015-10-13 14:34:03 -07001272 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001273 final Bundle effective = UserRestrictionsUtils.clone(baseRestrictions);
1274 UserRestrictionsUtils.merge(effective, global);
1275 UserRestrictionsUtils.merge(effective, local);
1276
Makoto Onuki068c54a2015-10-13 14:34:03 -07001277 return effective;
1278 }
1279
1280 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001281 private void invalidateEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki068c54a2015-10-13 14:34:03 -07001282 if (DBG) {
1283 Log.d(LOG_TAG, "invalidateEffectiveUserRestrictions userId=" + userId);
1284 }
1285 mCachedEffectiveUserRestrictions.remove(userId);
1286 }
1287
1288 private Bundle getEffectiveUserRestrictions(int userId) {
1289 synchronized (mRestrictionsLock) {
1290 Bundle restrictions = mCachedEffectiveUserRestrictions.get(userId);
1291 if (restrictions == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001292 restrictions = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001293 mCachedEffectiveUserRestrictions.put(userId, restrictions);
1294 }
1295 return restrictions;
Amith Yamasani8cd28b52014-06-08 17:54:27 -07001296 }
1297 }
1298
Makoto Onuki068c54a2015-10-13 14:34:03 -07001299 /** @return a specific user restriction that's in effect currently. */
1300 @Override
1301 public boolean hasUserRestriction(String restrictionKey, int userId) {
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001302 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1303 return false;
1304 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001305 Bundle restrictions = getEffectiveUserRestrictions(userId);
1306 return restrictions != null && restrictions.getBoolean(restrictionKey);
1307 }
1308
1309 /**
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001310 * @hide
1311 *
1312 * Returns who set a user restriction on a user.
1313 * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
1314 * @param restrictionKey the string key representing the restriction
1315 * @param userId the id of the user for whom to retrieve the restrictions.
1316 * @return The source of user restriction. Any combination of
1317 * {@link UserManager#RESTRICTION_NOT_SET},
1318 * {@link UserManager#RESTRICTION_SOURCE_SYSTEM},
1319 * {@link UserManager#RESTRICTION_SOURCE_DEVICE_OWNER}
1320 * and {@link UserManager#RESTRICTION_SOURCE_PROFILE_OWNER}
1321 */
1322 @Override
1323 public int getUserRestrictionSource(String restrictionKey, int userId) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001324 List<EnforcingUser> enforcingUsers = getUserRestrictionSources(restrictionKey, userId);
1325 // Get "bitwise or" of restriction sources for all enforcing users.
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001326 int result = UserManager.RESTRICTION_NOT_SET;
Pavel Grafov6a40f092016-10-25 15:46:51 +01001327 for (int i = enforcingUsers.size() - 1; i >= 0; i--) {
1328 result |= enforcingUsers.get(i).getUserRestrictionSource();
1329 }
1330 return result;
1331 }
1332
1333 @Override
1334 public List<EnforcingUser> getUserRestrictionSources(
1335 String restrictionKey, @UserIdInt int userId) {
1336 checkManageUsersPermission("getUserRestrictionSource");
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001337
1338 // Shortcut for the most common case
1339 if (!hasUserRestriction(restrictionKey, userId)) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001340 return Collections.emptyList();
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001341 }
1342
Pavel Grafov6a40f092016-10-25 15:46:51 +01001343 final List<EnforcingUser> result = new ArrayList<>();
1344
1345 // Check if it is base restriction.
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001346 if (hasBaseUserRestriction(restrictionKey, userId)) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001347 result.add(new EnforcingUser(
1348 UserHandle.USER_NULL, UserManager.RESTRICTION_SOURCE_SYSTEM));
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001349 }
1350
Pavel Grafov6a40f092016-10-25 15:46:51 +01001351 synchronized (mRestrictionsLock) {
1352 // Check if it is set by profile owner.
1353 Bundle profileOwnerRestrictions = mDevicePolicyLocalUserRestrictions.get(userId);
1354 if (UserRestrictionsUtils.contains(profileOwnerRestrictions, restrictionKey)) {
1355 result.add(getEnforcingUserLocked(userId));
1356 }
1357
1358 // Iterate over all users who enforce global restrictions.
1359 for (int i = mDevicePolicyGlobalUserRestrictions.size() - 1; i >= 0; i--) {
1360 Bundle globalRestrictions = mDevicePolicyGlobalUserRestrictions.valueAt(i);
1361 int profileUserId = mDevicePolicyGlobalUserRestrictions.keyAt(i);
1362 if (UserRestrictionsUtils.contains(globalRestrictions, restrictionKey)) {
1363 result.add(getEnforcingUserLocked(profileUserId));
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001364 }
1365 }
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001366 }
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001367 return result;
1368 }
1369
Pavel Grafov6a40f092016-10-25 15:46:51 +01001370 private EnforcingUser getEnforcingUserLocked(@UserIdInt int userId) {
1371 int source = mDeviceOwnerUserId == userId ? UserManager.RESTRICTION_SOURCE_DEVICE_OWNER
1372 : UserManager.RESTRICTION_SOURCE_PROFILE_OWNER;
1373 return new EnforcingUser(userId, source);
1374 }
1375
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001376 /**
Makoto Onuki068c54a2015-10-13 14:34:03 -07001377 * @return UserRestrictions that are in effect currently. This always returns a new
1378 * {@link Bundle}.
1379 */
Amith Yamasani8cd28b52014-06-08 17:54:27 -07001380 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001381 public Bundle getUserRestrictions(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001382 return UserRestrictionsUtils.clone(getEffectiveUserRestrictions(userId));
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001383 }
1384
1385 @Override
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +00001386 public boolean hasBaseUserRestriction(String restrictionKey, int userId) {
1387 checkManageUsersPermission("hasBaseUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001388 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1389 return false;
1390 }
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +00001391 synchronized (mRestrictionsLock) {
1392 Bundle bundle = mBaseUserRestrictions.get(userId);
1393 return (bundle != null && bundle.getBoolean(restrictionKey, false));
1394 }
1395 }
1396
1397 @Override
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001398 public void setUserRestriction(String key, boolean value, int userId) {
Fyodor Kupolovd4b26042015-07-27 14:30:59 -07001399 checkManageUsersPermission("setUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001400 if (!UserRestrictionsUtils.isValidRestriction(key)) {
1401 return;
1402 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001403 synchronized (mRestrictionsLock) {
1404 // Note we can't modify Bundles stored in mBaseUserRestrictions directly, so create
1405 // a copy.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001406 final Bundle newRestrictions = UserRestrictionsUtils.clone(
1407 mBaseUserRestrictions.get(userId));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001408 newRestrictions.putBoolean(key, value);
1409
Fyodor Kupolov82402752015-10-28 14:54:51 -07001410 updateUserRestrictionsInternalLR(newRestrictions, userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001411 }
1412 }
1413
Makoto Onuki068c54a2015-10-13 14:34:03 -07001414 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001415 * Optionally updating user restrictions, calculate the effective user restrictions and also
1416 * propagate to other services and system settings.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001417 *
Pavel Grafov6a40f092016-10-25 15:46:51 +01001418 * @param newBaseRestrictions User restrictions to set.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001419 * If null, will not update user restrictions and only does the propagation.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001420 * @param userId target user ID.
1421 */
1422 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001423 private void updateUserRestrictionsInternalLR(
Pavel Grafov6a40f092016-10-25 15:46:51 +01001424 @Nullable Bundle newBaseRestrictions, int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001425 final Bundle prevAppliedRestrictions = UserRestrictionsUtils.nonNull(
1426 mAppliedUserRestrictions.get(userId));
1427
1428 // Update base restrictions.
Pavel Grafov6a40f092016-10-25 15:46:51 +01001429 if (newBaseRestrictions != null) {
1430 // If newBaseRestrictions == the current one, it's probably a bug.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001431 final Bundle prevBaseRestrictions = mBaseUserRestrictions.get(userId);
1432
Pavel Grafov6a40f092016-10-25 15:46:51 +01001433 Preconditions.checkState(prevBaseRestrictions != newBaseRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001434 Preconditions.checkState(mCachedEffectiveUserRestrictions.get(userId)
Pavel Grafov6a40f092016-10-25 15:46:51 +01001435 != newBaseRestrictions);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001436
Pavel Grafov6a40f092016-10-25 15:46:51 +01001437 if (updateRestrictionsIfNeededLR(userId, newBaseRestrictions, mBaseUserRestrictions)) {
Amith Yamasani12747872015-12-07 14:19:49 -08001438 scheduleWriteUser(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001439 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001440 }
1441
Fyodor Kupolov82402752015-10-28 14:54:51 -07001442 final Bundle effective = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001443
Makoto Onuki759a7632015-10-28 16:43:10 -07001444 mCachedEffectiveUserRestrictions.put(userId, effective);
1445
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001446 // Apply the new restrictions.
Makoto Onuki4f160732015-10-27 17:15:38 -07001447 if (DBG) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001448 debug("Applying user restrictions: userId=" + userId
1449 + " new=" + effective + " prev=" + prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001450 }
1451
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001452 if (mAppOpsService != null) { // We skip it until system-ready.
Fyodor Kupolovec30ca32016-06-16 15:09:29 -07001453 mHandler.post(new Runnable() {
1454 @Override
1455 public void run() {
1456 try {
1457 mAppOpsService.setUserRestrictions(effective, mUserRestriconToken, userId);
1458 } catch (RemoteException e) {
1459 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
1460 }
1461 }
1462 });
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001463 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001464
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001465 propagateUserRestrictionsLR(userId, effective, prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001466
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001467 mAppliedUserRestrictions.put(userId, new Bundle(effective));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001468 }
1469
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001470 private void propagateUserRestrictionsLR(final int userId,
Makoto Onukid45a4a22015-11-02 17:17:38 -08001471 Bundle newRestrictions, Bundle prevRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001472 // Note this method doesn't touch any state, meaning it doesn't require mRestrictionsLock
1473 // actually, but we still need some kind of synchronization otherwise we might end up
1474 // calling listeners out-of-order, thus "LR".
1475
1476 if (UserRestrictionsUtils.areEqual(newRestrictions, prevRestrictions)) {
1477 return;
1478 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08001479
1480 final Bundle newRestrictionsFinal = new Bundle(newRestrictions);
1481 final Bundle prevRestrictionsFinal = new Bundle(prevRestrictions);
1482
1483 mHandler.post(new Runnable() {
1484 @Override
1485 public void run() {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07001486 UserRestrictionsUtils.applyUserRestrictions(
1487 mContext, userId, newRestrictionsFinal, prevRestrictionsFinal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001488
Makoto Onukid45a4a22015-11-02 17:17:38 -08001489 final UserRestrictionsListener[] listeners;
1490 synchronized (mUserRestrictionsListeners) {
1491 listeners = new UserRestrictionsListener[mUserRestrictionsListeners.size()];
1492 mUserRestrictionsListeners.toArray(listeners);
1493 }
1494 for (int i = 0; i < listeners.length; i++) {
1495 listeners[i].onUserRestrictionsChanged(userId,
1496 newRestrictionsFinal, prevRestrictionsFinal);
1497 }
Makoto Onukie72f81b2017-03-16 14:08:19 -07001498
1499 final Intent broadcast = new Intent(UserManager.ACTION_USER_RESTRICTIONS_CHANGED)
1500 .setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
1501 mContext.sendBroadcastAsUser(broadcast, UserHandle.of(userId));
Makoto Onukid45a4a22015-11-02 17:17:38 -08001502 }
1503 });
1504 }
1505
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001506 // Package private for the inner class.
1507 void applyUserRestrictionsLR(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001508 updateUserRestrictionsInternalLR(null, userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001509 }
1510
1511 @GuardedBy("mRestrictionsLock")
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001512 // Package private for the inner class.
1513 void applyUserRestrictionsForAllUsersLR() {
1514 if (DBG) {
1515 debug("applyUserRestrictionsForAllUsersLR");
1516 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001517 // First, invalidate all cached values.
Makoto Onuki4f160732015-10-27 17:15:38 -07001518 mCachedEffectiveUserRestrictions.clear();
1519
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001520 // We don't want to call into ActivityManagerService while taking a lock, so we'll call
Makoto Onuki068c54a2015-10-13 14:34:03 -07001521 // it on a handler.
1522 final Runnable r = new Runnable() {
1523 @Override
1524 public void run() {
1525 // Then get the list of running users.
1526 final int[] runningUsers;
1527 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001528 runningUsers = ActivityManager.getService().getRunningUserIds();
Makoto Onuki068c54a2015-10-13 14:34:03 -07001529 } catch (RemoteException e) {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001530 Log.w(LOG_TAG, "Unable to access ActivityManagerService");
Makoto Onuki068c54a2015-10-13 14:34:03 -07001531 return;
1532 }
1533 // Then re-calculate the effective restrictions and apply, only for running users.
1534 // It's okay if a new user has started after the getRunningUserIds() call,
1535 // because we'll do the same thing (re-calculate the restrictions and apply)
1536 // when we start a user.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001537 synchronized (mRestrictionsLock) {
1538 for (int i = 0; i < runningUsers.length; i++) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001539 applyUserRestrictionsLR(runningUsers[i]);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001540 }
1541 }
1542 }
1543 };
1544 mHandler.post(r);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001545 }
1546
Amith Yamasani258848d2012-08-10 17:06:33 -07001547 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001548 * Check if we've hit the limit of how many users can be created.
1549 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001550 private boolean isUserLimitReached() {
1551 int count;
1552 synchronized (mUsersLock) {
1553 count = getAliveUsersExcludingGuestsCountLU();
1554 }
1555 return count >= UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001556 }
1557
1558 @Override
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001559 public boolean canAddMoreManagedProfiles(int userId, boolean allowedToRemoveOne) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001560 checkManageUsersPermission("check if more managed profiles can be added.");
1561 if (ActivityManager.isLowRamDeviceStatic()) {
1562 return false;
1563 }
Fyodor Kupolovb6157992015-06-05 15:32:28 -07001564 if (!mContext.getPackageManager().hasSystemFeature(
1565 PackageManager.FEATURE_MANAGED_USERS)) {
1566 return false;
1567 }
Nicolas Prevotb8186812015-08-06 15:00:03 +01001568 // Limit number of managed profiles that can be created
Benjamin Franzc8776152017-01-06 14:16:41 +00001569 final int managedProfilesCount = getProfiles(userId, false).size() - 1;
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001570 final int profilesRemovedCount = managedProfilesCount > 0 && allowedToRemoveOne ? 1 : 0;
Kenny Guy02c89902016-11-15 19:36:38 +00001571 if (managedProfilesCount - profilesRemovedCount >= getMaxManagedProfiles()) {
Nicolas Prevotb8186812015-08-06 15:00:03 +01001572 return false;
1573 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001574 synchronized(mUsersLock) {
1575 UserInfo userInfo = getUserInfoLU(userId);
yuanhao47f9f7c2017-01-18 09:54:45 +08001576 if (userInfo == null || !userInfo.canHaveProfile()) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001577 return false;
1578 }
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001579 int usersCountAfterRemoving = getAliveUsersExcludingGuestsCountLU()
1580 - profilesRemovedCount;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001581 // We allow creating a managed profile in the special case where there is only one user.
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001582 return usersCountAfterRemoving == 1
1583 || usersCountAfterRemoving < UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001584 }
1585 }
1586
Fyodor Kupolov82402752015-10-28 14:54:51 -07001587 private int getAliveUsersExcludingGuestsCountLU() {
Amith Yamasanif584f012014-05-19 17:57:25 -07001588 int aliveUserCount = 0;
1589 final int totalUserCount = mUsers.size();
1590 // Skip over users being removed
1591 for (int i = 0; i < totalUserCount; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001592 UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov6e99d3f2016-11-01 17:18:41 -07001593 if (!mRemovingUserIds.get(user.id) && !user.isGuest()) {
Amith Yamasanif584f012014-05-19 17:57:25 -07001594 aliveUserCount++;
1595 }
1596 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001597 return aliveUserCount;
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001598 }
1599
1600 /**
Amith Yamasani195263742012-08-21 15:40:12 -07001601 * Enforces that only the system UID or root's UID or apps that have the
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001602 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} and
1603 * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL INTERACT_ACROSS_USERS_FULL}
1604 * permissions can make certain calls to the UserManager.
1605 *
1606 * @param message used as message if SecurityException is thrown
1607 * @throws SecurityException if the caller does not have enough privilege.
1608 */
1609 private static final void checkManageUserAndAcrossUsersFullPermission(String message) {
1610 final int uid = Binder.getCallingUid();
1611 if (uid != Process.SYSTEM_UID && uid != 0
1612 && ActivityManager.checkComponentPermission(
1613 Manifest.permission.MANAGE_USERS,
1614 uid, -1, true) != PackageManager.PERMISSION_GRANTED
1615 && ActivityManager.checkComponentPermission(
1616 Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1617 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
1618 throw new SecurityException(
1619 "You need MANAGE_USERS and INTERACT_ACROSS_USERS_FULL permission to: "
1620 + message);
1621 }
1622 }
1623
1624 /**
1625 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001626 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -07001627 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -07001628 *
1629 * @param message used as message if SecurityException is thrown
1630 * @throws SecurityException if the caller is not system or root
Tony Mak4dc008c2016-03-16 10:46:49 +00001631 * @see #hasManageUsersPermission()
Amith Yamasani258848d2012-08-10 17:06:33 -07001632 */
Amith Yamasanibe465322014-04-24 13:45:17 -07001633 private static final void checkManageUsersPermission(String message) {
Tony Mak4dc008c2016-03-16 10:46:49 +00001634 if (!hasManageUsersPermission()) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001635 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
1636 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -04001637 }
1638
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001639 /**
Sudheer Shankaf5cea032016-06-08 17:13:24 -07001640 * Enforces that only the system UID or root's UID or apps that have the
1641 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or
1642 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS}
1643 * can make certain calls to the UserManager.
1644 *
1645 * @param message used as message if SecurityException is thrown
1646 * @throws SecurityException if the caller is not system or root
1647 * @see #hasManageOrCreateUsersPermission()
1648 */
1649 private static final void checkManageOrCreateUsersPermission(String message) {
1650 if (!hasManageOrCreateUsersPermission()) {
1651 throw new SecurityException(
1652 "You either need MANAGE_USERS or CREATE_USERS permission to: " + message);
1653 }
1654 }
1655
1656 /**
1657 * Similar to {@link #checkManageOrCreateUsersPermission(String)} but when the caller is tries
1658 * to create user/profiles other than what is allowed for
1659 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS} permission, then it will only
1660 * allow callers with {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} permission.
1661 */
1662 private static final void checkManageOrCreateUsersPermission(int creationFlags) {
1663 if ((creationFlags & ~ALLOWED_FLAGS_FOR_CREATE_USERS_PERMISSION) == 0) {
1664 if (!hasManageOrCreateUsersPermission()) {
1665 throw new SecurityException("You either need MANAGE_USERS or CREATE_USERS "
1666 + "permission to create an user with flags: " + creationFlags);
1667 }
1668 } else if (!hasManageUsersPermission()) {
1669 throw new SecurityException("You need MANAGE_USERS permission to create an user "
1670 + " with flags: " + creationFlags);
1671 }
1672 }
1673
1674 /**
Tony Mak4dc008c2016-03-16 10:46:49 +00001675 * @return whether the calling UID is system UID or root's UID or the calling app has the
1676 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}.
1677 */
1678 private static final boolean hasManageUsersPermission() {
1679 final int callingUid = Binder.getCallingUid();
1680 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
1681 || callingUid == Process.ROOT_UID
1682 || ActivityManager.checkComponentPermission(
1683 android.Manifest.permission.MANAGE_USERS,
1684 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED;
1685 }
1686
1687 /**
Sudheer Shankaf5cea032016-06-08 17:13:24 -07001688 * @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} or
1690 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS}.
1691 */
1692 private static final boolean hasManageOrCreateUsersPermission() {
1693 final int callingUid = Binder.getCallingUid();
1694 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
1695 || callingUid == Process.ROOT_UID
1696 || ActivityManager.checkComponentPermission(
1697 android.Manifest.permission.MANAGE_USERS,
1698 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED
1699 || ActivityManager.checkComponentPermission(
1700 android.Manifest.permission.CREATE_USERS,
1701 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED;
1702 }
1703
1704 /**
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001705 * Enforces that only the system UID or root's UID (on any user) can make certain calls to the
1706 * UserManager.
1707 *
1708 * @param message used as message if SecurityException is thrown
1709 * @throws SecurityException if the caller is not system or root
1710 */
1711 private static void checkSystemOrRoot(String message) {
1712 final int uid = Binder.getCallingUid();
1713 if (!UserHandle.isSameApp(uid, Process.SYSTEM_UID) && uid != Process.ROOT_UID) {
1714 throw new SecurityException("Only system may: " + message);
1715 }
1716 }
1717
Fyodor Kupolov82402752015-10-28 14:54:51 -07001718 private void writeBitmapLP(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001719 try {
1720 File dir = new File(mUsersDir, Integer.toString(info.id));
1721 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +01001722 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001723 if (!dir.exists()) {
1724 dir.mkdir();
1725 FileUtils.setPermissions(
1726 dir.getPath(),
1727 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
1728 -1, -1);
1729 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001730 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +01001731 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001732 && tmp.renameTo(file) && SELinux.restorecon(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -07001733 info.iconPath = file.getAbsolutePath();
1734 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001735 try {
1736 os.close();
1737 } catch (IOException ioe) {
1738 // What the ... !
1739 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001740 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001741 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001742 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001743 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001744 }
1745
Amith Yamasani0b285492011-04-14 17:35:23 -07001746 /**
1747 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
1748 * cache it elsewhere.
1749 * @return the array of user ids.
1750 */
Dianne Hackborn1676c852012-09-10 14:52:30 -07001751 public int[] getUserIds() {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001752 synchronized (mUsersLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001753 return mUserIds;
1754 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001755 }
1756
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001757 private void readUserListLP() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001758 if (!mUserListFile.exists()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001759 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001760 return;
1761 }
1762 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001763 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001764 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001765 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001766 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001767 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001768 int type;
1769 while ((type = parser.next()) != XmlPullParser.START_TAG
1770 && type != XmlPullParser.END_DOCUMENT) {
Amith Yamasani12747872015-12-07 14:19:49 -08001771 // Skip
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001772 }
1773
1774 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001775 Slog.e(LOG_TAG, "Unable to read user list");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001776 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001777 return;
1778 }
1779
Amith Yamasani2a003292012-08-14 18:25:45 -07001780 mNextSerialNumber = -1;
1781 if (parser.getName().equals(TAG_USERS)) {
1782 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
1783 if (lastSerialNumber != null) {
1784 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
1785 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001786 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
1787 if (versionNumber != null) {
1788 mUserVersion = Integer.parseInt(versionNumber);
1789 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001790 }
1791
Pavel Grafov6a40f092016-10-25 15:46:51 +01001792 // Pre-O global user restriction were stored as a single bundle (as opposed to per-user
1793 // currently), take care of it in case of upgrade.
1794 Bundle oldDevicePolicyGlobalUserRestrictions = null;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001795
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001796 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301797 if (type == XmlPullParser.START_TAG) {
1798 final String name = parser.getName();
1799 if (name.equals(TAG_USER)) {
1800 String id = parser.getAttributeValue(null, ATTR_ID);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001801
Amith Yamasani12747872015-12-07 14:19:49 -08001802 UserData userData = readUserLP(Integer.parseInt(id));
1803
1804 if (userData != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001805 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001806 mUsers.put(userData.info.id, userData);
1807 if (mNextSerialNumber < 0
1808 || mNextSerialNumber <= userData.info.id) {
1809 mNextSerialNumber = userData.info.id + 1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001810 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301811 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001812 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301813 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -08001814 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1815 && type != XmlPullParser.END_TAG) {
1816 if (type == XmlPullParser.START_TAG) {
1817 if (parser.getName().equals(TAG_RESTRICTIONS)) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001818 synchronized (mGuestRestrictions) {
Fyodor Kupoloveafee022017-03-15 17:09:04 -07001819 UserRestrictionsUtils
1820 .readRestrictions(parser, mGuestRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001821 }
Amith Yamasanida0b1682014-11-21 12:58:17 -08001822 }
1823 break;
1824 }
1825 }
Pavel Grafov6a40f092016-10-25 15:46:51 +01001826 } else if (name.equals(TAG_DEVICE_OWNER_USER_ID)
1827 // Legacy name, should only be encountered when upgrading from pre-O.
1828 || name.equals(TAG_GLOBAL_RESTRICTION_OWNER_ID)) {
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001829 String ownerUserId = parser.getAttributeValue(null, ATTR_ID);
1830 if (ownerUserId != null) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001831 mDeviceOwnerUserId = Integer.parseInt(ownerUserId);
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001832 }
Pavel Grafov6a40f092016-10-25 15:46:51 +01001833 } else if (name.equals(TAG_DEVICE_POLICY_RESTRICTIONS)) {
1834 // Should only happen when upgrading from pre-O (version < 7).
1835 oldDevicePolicyGlobalUserRestrictions =
1836 UserRestrictionsUtils.readRestrictions(parser);
Amith Yamasani258848d2012-08-10 17:06:33 -07001837 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001838 }
1839 }
Pavel Grafov6a40f092016-10-25 15:46:51 +01001840
Fyodor Kupolov82402752015-10-28 14:54:51 -07001841 updateUserIds();
Pavel Grafov6a40f092016-10-25 15:46:51 +01001842 upgradeIfNecessaryLP(oldDevicePolicyGlobalUserRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001843 } catch (IOException | XmlPullParserException e) {
1844 fallbackToSingleUserLP();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001845 } finally {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001846 IoUtils.closeQuietly(fis);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001847 }
1848 }
1849
Amith Yamasani6f34b412012-10-22 18:19:27 -07001850 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -08001851 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Pavel Grafov6a40f092016-10-25 15:46:51 +01001852 * @param oldGlobalUserRestrictions Pre-O global device policy restrictions.
Amith Yamasani6f34b412012-10-22 18:19:27 -07001853 */
Pavel Grafov6a40f092016-10-25 15:46:51 +01001854 private void upgradeIfNecessaryLP(Bundle oldGlobalUserRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001855 final int originalVersion = mUserVersion;
Amith Yamasani6f34b412012-10-22 18:19:27 -07001856 int userVersion = mUserVersion;
1857 if (userVersion < 1) {
1858 // Assign a proper name for the owner, if not initialized correctly before
Amith Yamasani12747872015-12-07 14:19:49 -08001859 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
1860 if ("Primary".equals(userData.info.name)) {
1861 userData.info.name =
1862 mContext.getResources().getString(com.android.internal.R.string.owner_name);
1863 scheduleWriteUser(userData);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001864 }
1865 userVersion = 1;
1866 }
1867
Amith Yamasanibc9625052012-11-15 14:39:18 -08001868 if (userVersion < 2) {
1869 // Owner should be marked as initialized
Amith Yamasani12747872015-12-07 14:19:49 -08001870 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
1871 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1872 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
1873 scheduleWriteUser(userData);
Amith Yamasanibc9625052012-11-15 14:39:18 -08001874 }
1875 userVersion = 2;
1876 }
1877
Amith Yamasani350962c2013-08-06 11:18:53 -07001878
Amith Yamasani5e486f52013-08-07 11:06:44 -07001879 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -07001880 userVersion = 4;
1881 }
1882
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001883 if (userVersion < 5) {
1884 initDefaultGuestRestrictions();
1885 userVersion = 5;
1886 }
1887
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001888 if (userVersion < 6) {
1889 final boolean splitSystemUser = UserManager.isSplitSystemUser();
Fyodor Kupolov82402752015-10-28 14:54:51 -07001890 synchronized (mUsersLock) {
1891 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001892 UserData userData = mUsers.valueAt(i);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001893 // In non-split mode, only user 0 can have restricted profiles
Amith Yamasani12747872015-12-07 14:19:49 -08001894 if (!splitSystemUser && userData.info.isRestricted()
1895 && (userData.info.restrictedProfileParentId
1896 == UserInfo.NO_PROFILE_GROUP_ID)) {
1897 userData.info.restrictedProfileParentId = UserHandle.USER_SYSTEM;
1898 scheduleWriteUser(userData);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001899 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001900 }
1901 }
1902 userVersion = 6;
1903 }
1904
Pavel Grafov6a40f092016-10-25 15:46:51 +01001905 if (userVersion < 7) {
1906 // Previously only one user could enforce global restrictions, now it is per-user.
1907 synchronized (mRestrictionsLock) {
1908 if (!UserRestrictionsUtils.isEmpty(oldGlobalUserRestrictions)
1909 && mDeviceOwnerUserId != UserHandle.USER_NULL) {
1910 mDevicePolicyGlobalUserRestrictions.put(
1911 mDeviceOwnerUserId, oldGlobalUserRestrictions);
1912 }
1913 // ENSURE_VERIFY_APPS is now enforced globally even if put by profile owner, so move
1914 // it from local to global bundle for all users who set it.
1915 UserRestrictionsUtils.moveRestriction(UserManager.ENSURE_VERIFY_APPS,
1916 mDevicePolicyLocalUserRestrictions, mDevicePolicyGlobalUserRestrictions
1917 );
1918 }
1919 userVersion = 7;
1920 }
1921
Amith Yamasani6f34b412012-10-22 18:19:27 -07001922 if (userVersion < USER_VERSION) {
1923 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
1924 + USER_VERSION);
1925 } else {
1926 mUserVersion = userVersion;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001927
1928 if (originalVersion < mUserVersion) {
1929 writeUserListLP();
1930 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001931 }
1932 }
1933
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001934 private void fallbackToSingleUserLP() {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001935 int flags = UserInfo.FLAG_INITIALIZED;
1936 // In split system user mode, the admin and primary flags are assigned to the first human
1937 // user.
1938 if (!UserManager.isSplitSystemUser()) {
1939 flags |= UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY;
1940 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001941 // Create the system user
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001942 UserInfo system = new UserInfo(UserHandle.USER_SYSTEM, null, null, flags);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07001943 UserData userData = putUserInfo(system);
Amith Yamasani634cf312012-10-04 17:34:21 -07001944 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -04001945 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -08001946
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001947 Bundle restrictions = new Bundle();
Mahaver Chopra3d9805d2016-07-07 16:25:05 +01001948 try {
1949 final String[] defaultFirstUserRestrictions = mContext.getResources().getStringArray(
1950 com.android.internal.R.array.config_defaultFirstUserRestrictions);
1951 for (String userRestriction : defaultFirstUserRestrictions) {
1952 if (UserRestrictionsUtils.isValidRestriction(userRestriction)) {
1953 restrictions.putBoolean(userRestriction, true);
1954 }
1955 }
1956 } catch (Resources.NotFoundException e) {
1957 Log.e(LOG_TAG, "Couldn't find resource: config_defaultFirstUserRestrictions", e);
1958 }
1959
Pavel Grafov6a40f092016-10-25 15:46:51 +01001960 if (!restrictions.isEmpty()) {
1961 synchronized (mRestrictionsLock) {
1962 mBaseUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions);
1963 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001964 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001965
Fyodor Kupolov82402752015-10-28 14:54:51 -07001966 updateUserIds();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001967 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001968
Amith Yamasani12747872015-12-07 14:19:49 -08001969 writeUserLP(userData);
Jeff Sharkeycd575992016-03-29 14:12:49 -06001970 writeUserListLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001971 }
1972
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001973 private String getOwnerName() {
1974 return mContext.getResources().getString(com.android.internal.R.string.owner_name);
1975 }
1976
Amith Yamasani12747872015-12-07 14:19:49 -08001977 private void scheduleWriteUser(UserData UserData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001978 if (DBG) {
1979 debug("scheduleWriteUser");
1980 }
Makoto Onuki9e935a32015-11-06 14:24:24 -08001981 // No need to wrap it within a lock -- worst case, we'll just post the same message
1982 // twice.
Amith Yamasani12747872015-12-07 14:19:49 -08001983 if (!mHandler.hasMessages(WRITE_USER_MSG, UserData)) {
1984 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, UserData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001985 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
1986 }
1987 }
1988
Amith Yamasani12747872015-12-07 14:19:49 -08001989 private void writeUserLP(UserData userData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001990 if (DBG) {
Amith Yamasani12747872015-12-07 14:19:49 -08001991 debug("writeUserLP " + userData);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001992 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001993 FileOutputStream fos = null;
Amith Yamasani12747872015-12-07 14:19:49 -08001994 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userData.info.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001995 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001996 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001997 final BufferedOutputStream bos = new BufferedOutputStream(fos);
Kenny Guy02c89902016-11-15 19:36:38 +00001998 writeUserLP(userData, bos);
Amith Yamasani2a003292012-08-14 18:25:45 -07001999 userFile.finishWrite(fos);
2000 } catch (Exception ioe) {
Jeff Sharkeycd575992016-03-29 14:12:49 -06002001 Slog.e(LOG_TAG, "Error writing user info " + userData.info.id, ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -07002002 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002003 }
2004 }
2005
2006 /*
Kenny Guy02c89902016-11-15 19:36:38 +00002007 * Writes the user file in this format:
2008 *
2009 * <user flags="20039023" id="0">
2010 * <name>Primary</name>
2011 * </user>
2012 */
2013 @VisibleForTesting
2014 void writeUserLP(UserData userData, OutputStream os)
2015 throws IOException, XmlPullParserException {
2016 // XmlSerializer serializer = XmlUtils.serializerInstance();
2017 final XmlSerializer serializer = new FastXmlSerializer();
2018 serializer.setOutput(os, StandardCharsets.UTF_8.name());
2019 serializer.startDocument(null, true);
2020 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2021
2022 final UserInfo userInfo = userData.info;
2023 serializer.startTag(null, TAG_USER);
2024 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
2025 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
2026 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
2027 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
2028 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
2029 Long.toString(userInfo.lastLoggedInTime));
2030 if (userInfo.lastLoggedInFingerprint != null) {
2031 serializer.attribute(null, ATTR_LAST_LOGGED_IN_FINGERPRINT,
2032 userInfo.lastLoggedInFingerprint);
2033 }
2034 if (userInfo.iconPath != null) {
2035 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
2036 }
2037 if (userInfo.partial) {
2038 serializer.attribute(null, ATTR_PARTIAL, "true");
2039 }
2040 if (userInfo.guestToRemove) {
2041 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
2042 }
2043 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
2044 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
2045 Integer.toString(userInfo.profileGroupId));
2046 }
2047 serializer.attribute(null, ATTR_PROFILE_BADGE,
2048 Integer.toString(userInfo.profileBadge));
2049 if (userInfo.restrictedProfileParentId != UserInfo.NO_PROFILE_GROUP_ID) {
2050 serializer.attribute(null, ATTR_RESTRICTED_PROFILE_PARENT_ID,
2051 Integer.toString(userInfo.restrictedProfileParentId));
2052 }
2053 // Write seed data
2054 if (userData.persistSeedData) {
2055 if (userData.seedAccountName != null) {
2056 serializer.attribute(null, ATTR_SEED_ACCOUNT_NAME, userData.seedAccountName);
2057 }
2058 if (userData.seedAccountType != null) {
2059 serializer.attribute(null, ATTR_SEED_ACCOUNT_TYPE, userData.seedAccountType);
2060 }
2061 }
2062 if (userInfo.name != null) {
2063 serializer.startTag(null, TAG_NAME);
2064 serializer.text(userInfo.name);
2065 serializer.endTag(null, TAG_NAME);
2066 }
2067 synchronized (mRestrictionsLock) {
2068 UserRestrictionsUtils.writeRestrictions(serializer,
2069 mBaseUserRestrictions.get(userInfo.id), TAG_RESTRICTIONS);
2070 UserRestrictionsUtils.writeRestrictions(serializer,
2071 mDevicePolicyLocalUserRestrictions.get(userInfo.id),
2072 TAG_DEVICE_POLICY_RESTRICTIONS);
Pavel Grafov6a40f092016-10-25 15:46:51 +01002073 UserRestrictionsUtils.writeRestrictions(serializer,
2074 mDevicePolicyGlobalUserRestrictions.get(userInfo.id),
2075 TAG_DEVICE_POLICY_GLOBAL_RESTRICTIONS);
Kenny Guy02c89902016-11-15 19:36:38 +00002076 }
2077
2078 if (userData.account != null) {
2079 serializer.startTag(null, TAG_ACCOUNT);
2080 serializer.text(userData.account);
2081 serializer.endTag(null, TAG_ACCOUNT);
2082 }
2083
2084 if (userData.persistSeedData && userData.seedAccountOptions != null) {
2085 serializer.startTag(null, TAG_SEED_ACCOUNT_OPTIONS);
2086 userData.seedAccountOptions.saveToXml(serializer);
2087 serializer.endTag(null, TAG_SEED_ACCOUNT_OPTIONS);
2088 }
2089
2090 serializer.endTag(null, TAG_USER);
2091
2092 serializer.endDocument();
2093 }
2094
2095 /*
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002096 * Writes the user list file in this format:
2097 *
Amith Yamasani2a003292012-08-14 18:25:45 -07002098 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002099 * <user id="0"></user>
2100 * <user id="2"></user>
2101 * </users>
2102 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002103 private void writeUserListLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002104 if (DBG) {
2105 debug("writeUserList");
2106 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002107 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07002108 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002109 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07002110 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002111 final BufferedOutputStream bos = new BufferedOutputStream(fos);
2112
2113 // XmlSerializer serializer = XmlUtils.serializerInstance();
2114 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002115 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002116 serializer.startDocument(null, true);
2117 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2118
2119 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -07002120 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -07002121 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002122
Adam Lesinskieddeb492014-09-08 17:50:03 -07002123 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002124 synchronized (mGuestRestrictions) {
2125 UserRestrictionsUtils
2126 .writeRestrictions(serializer, mGuestRestrictions, TAG_RESTRICTIONS);
2127 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05302128 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Pavel Grafov6a40f092016-10-25 15:46:51 +01002129 serializer.startTag(null, TAG_DEVICE_OWNER_USER_ID);
2130 serializer.attribute(null, ATTR_ID, Integer.toString(mDeviceOwnerUserId));
2131 serializer.endTag(null, TAG_DEVICE_OWNER_USER_ID);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002132 int[] userIdsToWrite;
2133 synchronized (mUsersLock) {
2134 userIdsToWrite = new int[mUsers.size()];
2135 for (int i = 0; i < userIdsToWrite.length; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002136 UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002137 userIdsToWrite[i] = user.id;
2138 }
2139 }
2140 for (int id : userIdsToWrite) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002141 serializer.startTag(null, TAG_USER);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002142 serializer.attribute(null, ATTR_ID, Integer.toString(id));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002143 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002144 }
2145
2146 serializer.endTag(null, TAG_USERS);
2147
2148 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07002149 userListFile.finishWrite(fos);
2150 } catch (Exception e) {
2151 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -07002152 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002153 }
2154 }
2155
Amith Yamasani12747872015-12-07 14:19:49 -08002156 private UserData readUserLP(int id) {
Kenny Guy02c89902016-11-15 19:36:38 +00002157 FileInputStream fis = null;
2158 try {
2159 AtomicFile userFile =
2160 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
2161 fis = userFile.openRead();
2162 return readUserLP(id, fis);
2163 } catch (IOException ioe) {
2164 Slog.e(LOG_TAG, "Error reading user list");
2165 } catch (XmlPullParserException pe) {
2166 Slog.e(LOG_TAG, "Error reading user list");
2167 } finally {
2168 IoUtils.closeQuietly(fis);
2169 }
2170 return null;
2171 }
2172
2173 @VisibleForTesting
2174 UserData readUserLP(int id, InputStream is) throws IOException,
2175 XmlPullParserException {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002176 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -07002177 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002178 String name = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -08002179 String account = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002180 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -07002181 long creationTime = 0L;
2182 long lastLoggedInTime = 0L;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002183 String lastLoggedInFingerprint = null;
Kenny Guy2a764942014-04-02 13:29:20 +01002184 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Kenny Guy02c89902016-11-15 19:36:38 +00002185 int profileBadge = 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002186 int restrictedProfileParentId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002187 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -07002188 boolean guestToRemove = false;
Amith Yamasani12747872015-12-07 14:19:49 -08002189 boolean persistSeedData = false;
2190 String seedAccountName = null;
2191 String seedAccountType = null;
2192 PersistableBundle seedAccountOptions = null;
Pavel Grafov6a40f092016-10-25 15:46:51 +01002193 Bundle baseRestrictions = null;
2194 Bundle localRestrictions = null;
2195 Bundle globalRestrictions = null;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002196
Kenny Guy02c89902016-11-15 19:36:38 +00002197 XmlPullParser parser = Xml.newPullParser();
2198 parser.setInput(is, StandardCharsets.UTF_8.name());
2199 int type;
2200 while ((type = parser.next()) != XmlPullParser.START_TAG
2201 && type != XmlPullParser.END_DOCUMENT) {
2202 // Skip
2203 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002204
Kenny Guy02c89902016-11-15 19:36:38 +00002205 if (type != XmlPullParser.START_TAG) {
2206 Slog.e(LOG_TAG, "Unable to read user " + id);
2207 return null;
2208 }
2209
2210 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
2211 int storedId = readIntAttribute(parser, ATTR_ID, -1);
2212 if (storedId != id) {
2213 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002214 return null;
2215 }
Kenny Guy02c89902016-11-15 19:36:38 +00002216 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
2217 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
2218 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
2219 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
2220 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
2221 lastLoggedInFingerprint = parser.getAttributeValue(null,
2222 ATTR_LAST_LOGGED_IN_FINGERPRINT);
2223 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
2224 UserInfo.NO_PROFILE_GROUP_ID);
2225 profileBadge = readIntAttribute(parser, ATTR_PROFILE_BADGE, 0);
2226 restrictedProfileParentId = readIntAttribute(parser,
2227 ATTR_RESTRICTED_PROFILE_PARENT_ID, UserInfo.NO_PROFILE_GROUP_ID);
2228 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
2229 if ("true".equals(valueString)) {
2230 partial = true;
2231 }
2232 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
2233 if ("true".equals(valueString)) {
2234 guestToRemove = true;
2235 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002236
Kenny Guy02c89902016-11-15 19:36:38 +00002237 seedAccountName = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_NAME);
2238 seedAccountType = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_TYPE);
2239 if (seedAccountName != null || seedAccountType != null) {
2240 persistSeedData = true;
2241 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002242
Kenny Guy02c89902016-11-15 19:36:38 +00002243 int outerDepth = parser.getDepth();
2244 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2245 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2246 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2247 continue;
2248 }
2249 String tag = parser.getName();
2250 if (TAG_NAME.equals(tag)) {
2251 type = parser.next();
2252 if (type == XmlPullParser.TEXT) {
2253 name = parser.getText();
2254 }
2255 } else if (TAG_RESTRICTIONS.equals(tag)) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01002256 baseRestrictions = UserRestrictionsUtils.readRestrictions(parser);
Kenny Guy02c89902016-11-15 19:36:38 +00002257 } else if (TAG_DEVICE_POLICY_RESTRICTIONS.equals(tag)) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01002258 localRestrictions = UserRestrictionsUtils.readRestrictions(parser);
2259 } else if (TAG_DEVICE_POLICY_GLOBAL_RESTRICTIONS.equals(tag)) {
2260 globalRestrictions = UserRestrictionsUtils.readRestrictions(parser);
Kenny Guy02c89902016-11-15 19:36:38 +00002261 } else if (TAG_ACCOUNT.equals(tag)) {
2262 type = parser.next();
2263 if (type == XmlPullParser.TEXT) {
2264 account = parser.getText();
2265 }
2266 } else if (TAG_SEED_ACCOUNT_OPTIONS.equals(tag)) {
2267 seedAccountOptions = PersistableBundle.restoreFromXml(parser);
Amith Yamasani12747872015-12-07 14:19:49 -08002268 persistSeedData = true;
2269 }
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08002270 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002271 }
Kenny Guy02c89902016-11-15 19:36:38 +00002272
2273 // Create the UserInfo object that gets passed around
2274 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
2275 userInfo.serialNumber = serialNumber;
2276 userInfo.creationTime = creationTime;
2277 userInfo.lastLoggedInTime = lastLoggedInTime;
2278 userInfo.lastLoggedInFingerprint = lastLoggedInFingerprint;
2279 userInfo.partial = partial;
2280 userInfo.guestToRemove = guestToRemove;
2281 userInfo.profileGroupId = profileGroupId;
2282 userInfo.profileBadge = profileBadge;
2283 userInfo.restrictedProfileParentId = restrictedProfileParentId;
2284
2285 // Create the UserData object that's internal to this class
2286 UserData userData = new UserData();
2287 userData.info = userInfo;
2288 userData.account = account;
2289 userData.seedAccountName = seedAccountName;
2290 userData.seedAccountType = seedAccountType;
2291 userData.persistSeedData = persistSeedData;
2292 userData.seedAccountOptions = seedAccountOptions;
2293
2294 synchronized (mRestrictionsLock) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01002295 if (baseRestrictions != null) {
2296 mBaseUserRestrictions.put(id, baseRestrictions);
2297 }
2298 if (localRestrictions != null) {
2299 mDevicePolicyLocalUserRestrictions.put(id, localRestrictions);
2300 }
2301 if (globalRestrictions != null) {
2302 mDevicePolicyGlobalUserRestrictions.put(id, globalRestrictions);
2303 }
Kenny Guy02c89902016-11-15 19:36:38 +00002304 }
2305 return userData;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002306 }
2307
Amith Yamasani920ace02012-09-20 22:15:37 -07002308 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
2309 String valueString = parser.getAttributeValue(null, attr);
2310 if (valueString == null) return defaultValue;
2311 try {
2312 return Integer.parseInt(valueString);
2313 } catch (NumberFormatException nfe) {
2314 return defaultValue;
2315 }
2316 }
2317
2318 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
2319 String valueString = parser.getAttributeValue(null, attr);
2320 if (valueString == null) return defaultValue;
2321 try {
2322 return Long.parseLong(valueString);
2323 } catch (NumberFormatException nfe) {
2324 return defaultValue;
2325 }
2326 }
2327
Amith Yamasanib82add22013-07-09 11:24:44 -07002328 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002329 * Removes the app restrictions file for a specific package and user id, if it exists.
2330 */
2331 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
2332 synchronized (mPackagesLock) {
2333 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07002334 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002335 if (resFile.exists()) {
2336 resFile.delete();
2337 }
2338 }
2339 }
2340
Kenny Guya52dc3e2014-02-11 15:33:14 +00002341 @Override
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002342 public UserInfo createProfileForUser(String name, int flags, int userId,
2343 String[] disallowedPackages) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002344 checkManageOrCreateUsersPermission(flags);
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002345 return createUserInternal(name, flags, userId, disallowedPackages);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002346 }
2347
Amith Yamasani258848d2012-08-10 17:06:33 -07002348 @Override
Tony Mak6dc428f2016-10-10 15:48:27 +01002349 public UserInfo createProfileForUserEvenWhenDisallowed(String name, int flags, int userId,
2350 String[] disallowedPackages) {
2351 checkManageOrCreateUsersPermission(flags);
2352 return createUserInternalUnchecked(name, flags, userId, disallowedPackages);
2353 }
2354
2355 @Override
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00002356 public boolean removeUserEvenWhenDisallowed(@UserIdInt int userHandle) {
2357 checkManageOrCreateUsersPermission("Only the system can remove users");
2358 return removeUserUnchecked(userHandle);
2359 }
2360
2361 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07002362 public UserInfo createUser(String name, int flags) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002363 checkManageOrCreateUsersPermission(flags);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00002364 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002365 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07002366
Jessica Hummelbe81c802014-04-22 15:49:22 +01002367 private UserInfo createUserInternal(String name, int flags, int parentId) {
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002368 return createUserInternal(name, flags, parentId, null);
2369 }
2370
2371 private UserInfo createUserInternal(String name, int flags, int parentId,
2372 String[] disallowedPackages) {
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002373 String restriction = ((flags & UserInfo.FLAG_MANAGED_PROFILE) != 0)
2374 ? UserManager.DISALLOW_ADD_MANAGED_PROFILE
2375 : UserManager.DISALLOW_ADD_USER;
2376 if (hasUserRestriction(restriction, UserHandle.getCallingUserId())) {
2377 Log.w(LOG_TAG, "Cannot add user. " + restriction + " is enabled.");
Julia Reynolds75175022014-06-26 16:35:00 -04002378 return null;
2379 }
Tony Mak6dc428f2016-10-10 15:48:27 +01002380 return createUserInternalUnchecked(name, flags, parentId, disallowedPackages);
2381 }
2382
2383 private UserInfo createUserInternalUnchecked(String name, int flags, int parentId,
2384 String[] disallowedPackages) {
Suprabh Shuklac5e057c2016-08-08 16:22:44 -07002385 DeviceStorageMonitorInternal dsm = LocalServices
2386 .getService(DeviceStorageMonitorInternal.class);
2387 if (dsm.isMemoryLow()) {
2388 Log.w(LOG_TAG, "Cannot add user. Not enough space on disk.");
2389 return null;
2390 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07002391 if (ActivityManager.isLowRamDeviceStatic()) {
2392 return null;
2393 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07002394 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Nicolas Prevot12678a92015-05-13 12:15:03 -07002395 final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002396 final boolean isRestricted = (flags & UserInfo.FLAG_RESTRICTED) != 0;
Amith Yamasani52c21e32016-05-31 09:12:20 -07002397 final boolean isDemo = (flags & UserInfo.FLAG_DEMO) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002398 final long ident = Binder.clearCallingIdentity();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002399 UserInfo userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08002400 UserData userData;
Amith Yamasanibb054c92015-07-09 14:16:27 -07002401 final int userId;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002402 try {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002403 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002404 UserData parent = null;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002405 if (parentId != UserHandle.USER_NULL) {
2406 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002407 parent = getUserDataLU(parentId);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00002408 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002409 if (parent == null) return null;
2410 }
2411 if (isManagedProfile && !canAddMoreManagedProfiles(parentId, false)) {
2412 Log.e(LOG_TAG, "Cannot add more managed profiles for user " + parentId);
2413 return null;
2414 }
Amith Yamasani52c21e32016-05-31 09:12:20 -07002415 if (!isGuest && !isManagedProfile && !isDemo && isUserLimitReached()) {
2416 // If we're not adding a guest/demo user or a managed profile and the limit has
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002417 // been reached, cannot add a user.
2418 return null;
2419 }
2420 // If we're adding a guest and there already exists one, bail.
2421 if (isGuest && findCurrentGuestUser() != null) {
2422 return null;
2423 }
2424 // In legacy mode, restricted profile's parent can only be the owner user
2425 if (isRestricted && !UserManager.isSplitSystemUser()
2426 && (parentId != UserHandle.USER_SYSTEM)) {
2427 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
2428 return null;
2429 }
2430 if (isRestricted && UserManager.isSplitSystemUser()) {
2431 if (parent == null) {
2432 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be "
2433 + "specified");
Nicolas Prevot12678a92015-05-13 12:15:03 -07002434 return null;
2435 }
Amith Yamasani12747872015-12-07 14:19:49 -08002436 if (!parent.info.canHaveProfile()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002437 Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be "
2438 + "created for the specified parent user id " + parentId);
Amith Yamasani95ab7842014-08-11 17:09:26 -07002439 return null;
2440 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002441 }
2442 // In split system user mode, we assign the first human user the primary flag.
2443 // And if there is no device owner, we also assign the admin flag to primary user.
2444 if (UserManager.isSplitSystemUser()
2445 && !isGuest && !isManagedProfile && getPrimaryUser() == null) {
2446 flags |= UserInfo.FLAG_PRIMARY;
Makoto Onukie7927da2015-11-25 10:05:17 -08002447 synchronized (mUsersLock) {
2448 if (!mIsDeviceManaged) {
2449 flags |= UserInfo.FLAG_ADMIN;
2450 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07002451 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002452 }
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002453
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002454 userId = getNextAvailableId();
2455 Environment.getUserSystemDirectory(userId).mkdirs();
Lenka Trochtova02fee152015-12-22 14:26:18 +01002456 boolean ephemeralGuests = Resources.getSystem()
2457 .getBoolean(com.android.internal.R.bool.config_guestUserEphemeral);
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002458
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002459 synchronized (mUsersLock) {
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002460 // Add ephemeral flag to guests/users if required. Also inherit it from parent.
2461 if ((isGuest && ephemeralGuests) || mForceEphemeralUsers
2462 || (parent != null && parent.info.isEphemeral())) {
2463 flags |= UserInfo.FLAG_EPHEMERAL;
2464 }
2465
2466 userInfo = new UserInfo(userId, name, null, flags);
2467 userInfo.serialNumber = mNextSerialNumber++;
2468 long now = System.currentTimeMillis();
2469 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
2470 userInfo.partial = true;
Fyodor Kupolov83c24242016-03-31 13:30:42 -07002471 userInfo.lastLoggedInFingerprint = Build.FINGERPRINT;
Kenny Guy02c89902016-11-15 19:36:38 +00002472 if (isManagedProfile && parentId != UserHandle.USER_NULL) {
2473 userInfo.profileBadge = getFreeProfileBadgeLU(parentId);
2474 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002475 userData = new UserData();
2476 userData.info = userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08002477 mUsers.put(userId, userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002478 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06002479 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002480 writeUserListLP();
2481 if (parent != null) {
2482 if (isManagedProfile) {
Amith Yamasani12747872015-12-07 14:19:49 -08002483 if (parent.info.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
2484 parent.info.profileGroupId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002485 writeUserLP(parent);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002486 }
Amith Yamasani12747872015-12-07 14:19:49 -08002487 userInfo.profileGroupId = parent.info.profileGroupId;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002488 } else if (isRestricted) {
Amith Yamasani12747872015-12-07 14:19:49 -08002489 if (parent.info.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) {
2490 parent.info.restrictedProfileParentId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002491 writeUserLP(parent);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002492 }
Amith Yamasani12747872015-12-07 14:19:49 -08002493 userInfo.restrictedProfileParentId = parent.info.restrictedProfileParentId;
Makoto Onuki068c54a2015-10-13 14:34:03 -07002494 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002495 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07002496 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002497 final StorageManager storage = mContext.getSystemService(StorageManager.class);
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002498 storage.createUserKey(userId, userInfo.serialNumber, userInfo.isEphemeral());
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -08002499 mUserDataPreparer.prepareUserData(userId, userInfo.serialNumber,
Jeff Sharkey47f71082016-02-01 17:03:54 -07002500 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002501 mPm.createNewUser(userId, disallowedPackages);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002502 userInfo.partial = false;
2503 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002504 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002505 }
2506 updateUserIds();
2507 Bundle restrictions = new Bundle();
Fyodor Kupolove04462c2015-11-30 15:02:53 -08002508 if (isGuest) {
2509 synchronized (mGuestRestrictions) {
2510 restrictions.putAll(mGuestRestrictions);
2511 }
2512 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002513 synchronized (mRestrictionsLock) {
2514 mBaseUserRestrictions.append(userId, restrictions);
2515 }
Fyodor Kupolov5fd967d2016-07-12 14:46:19 -07002516 mPm.onNewUserCreated(userId);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002517 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
2518 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
2519 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
2520 android.Manifest.permission.MANAGE_USERS);
Christine Franks88220562017-05-24 11:11:21 -07002521 MetricsLogger.count(mContext, isGuest ? TRON_GUEST_CREATED
2522 : (isDemo ? TRON_DEMO_CREATED : TRON_USER_CREATED), 1);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002523 } finally {
2524 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07002525 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002526 return userInfo;
2527 }
2528
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002529 @VisibleForTesting
2530 UserData putUserInfo(UserInfo userInfo) {
2531 final UserData userData = new UserData();
2532 userData.info = userInfo;
2533 synchronized (mUsers) {
2534 mUsers.put(userInfo.id, userData);
2535 }
2536 return userData;
2537 }
2538
2539 @VisibleForTesting
2540 void removeUserInfo(int userId) {
2541 synchronized (mUsers) {
2542 mUsers.remove(userId);
2543 }
2544 }
2545
Amith Yamasani0b285492011-04-14 17:35:23 -07002546 /**
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002547 * @hide
2548 */
Amith Yamasani12747872015-12-07 14:19:49 -08002549 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002550 public UserInfo createRestrictedProfile(String name, int parentUserId) {
Sudheer Shanka53d41472016-06-16 09:11:08 -07002551 checkManageOrCreateUsersPermission("setupRestrictedProfile");
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002552 final UserInfo user = createProfileForUser(
2553 name, UserInfo.FLAG_RESTRICTED, parentUserId, null);
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002554 if (user == null) {
2555 return null;
2556 }
Fyodor Kupolov9e912ba2016-02-09 18:29:43 -08002557 long identity = Binder.clearCallingIdentity();
2558 try {
2559 setUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, true, user.id);
2560 // Change the setting before applying the DISALLOW_SHARE_LOCATION restriction, otherwise
2561 // the putIntForUser() will fail.
2562 android.provider.Settings.Secure.putIntForUser(mContext.getContentResolver(),
2563 android.provider.Settings.Secure.LOCATION_MODE,
2564 android.provider.Settings.Secure.LOCATION_MODE_OFF, user.id);
2565 setUserRestriction(UserManager.DISALLOW_SHARE_LOCATION, true, user.id);
2566 } finally {
2567 Binder.restoreCallingIdentity(identity);
2568 }
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002569 return user;
2570 }
2571
2572 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07002573 * Find the current guest user. If the Guest user is partial,
2574 * then do not include it in the results as it is about to die.
Adam Lesinskieddeb492014-09-08 17:50:03 -07002575 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002576 private UserInfo findCurrentGuestUser() {
2577 synchronized (mUsersLock) {
2578 final int size = mUsers.size();
2579 for (int i = 0; i < size; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002580 final UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002581 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
2582 return user;
2583 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002584 }
2585 }
2586 return null;
2587 }
2588
2589 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07002590 * Mark this guest user for deletion to allow us to create another guest
2591 * and switch to that user before actually removing this guest.
2592 * @param userHandle the userid of the current guest
2593 * @return whether the user could be marked for deletion
2594 */
Amith Yamasani12747872015-12-07 14:19:49 -08002595 @Override
Amith Yamasani1df14732014-08-29 21:37:27 -07002596 public boolean markGuestForDeletion(int userHandle) {
2597 checkManageUsersPermission("Only the system can remove users");
2598 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
2599 UserManager.DISALLOW_REMOVE_USER, false)) {
2600 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
2601 return false;
2602 }
2603
2604 long ident = Binder.clearCallingIdentity();
2605 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002606 final UserData userData;
Amith Yamasani1df14732014-08-29 21:37:27 -07002607 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002608 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002609 userData = mUsers.get(userHandle);
2610 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002611 return false;
2612 }
Amith Yamasani1df14732014-08-29 21:37:27 -07002613 }
Amith Yamasani12747872015-12-07 14:19:49 -08002614 if (!userData.info.isGuest()) {
Amith Yamasani1df14732014-08-29 21:37:27 -07002615 return false;
2616 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002617 // We set this to a guest user that is to be removed. This is a temporary state
2618 // where we are allowed to add new Guest users, even if this one is still not
2619 // removed. This user will still show up in getUserInfo() calls.
2620 // If we don't get around to removing this Guest user, it will be purged on next
2621 // startup.
Amith Yamasani12747872015-12-07 14:19:49 -08002622 userData.info.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07002623 // Mark it as disabled, so that it isn't returned any more when
2624 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002625 userData.info.flags |= UserInfo.FLAG_DISABLED;
2626 writeUserLP(userData);
Amith Yamasani1df14732014-08-29 21:37:27 -07002627 }
2628 } finally {
2629 Binder.restoreCallingIdentity(ident);
2630 }
2631 return true;
2632 }
2633
2634 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002635 * Removes a user and all data directories created for that user. This method should be called
2636 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07002637 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07002638 */
Amith Yamasani12747872015-12-07 14:19:49 -08002639 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -07002640 public boolean removeUser(int userHandle) {
Fyodor Kupolov4593e422016-10-27 11:00:29 -07002641 Slog.i(LOG_TAG, "removeUser u" + userHandle);
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002642 checkManageOrCreateUsersPermission("Only the system can remove users");
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002643
2644 final boolean isManagedProfile;
2645 synchronized (mUsersLock) {
2646 UserInfo userInfo = getUserInfoLU(userHandle);
2647 isManagedProfile = userInfo != null && userInfo.isManagedProfile();
2648 }
2649 String restriction = isManagedProfile
2650 ? UserManager.DISALLOW_REMOVE_MANAGED_PROFILE : UserManager.DISALLOW_REMOVE_USER;
2651 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(restriction, false)) {
2652 Log.w(LOG_TAG, "Cannot remove user. " + restriction + " is enabled.");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04002653 return false;
2654 }
Nicolas Prevotdf1b87d2016-10-25 13:57:08 +01002655 return removeUserUnchecked(userHandle);
2656 }
Julia Reynolds4ac5f852014-06-23 17:38:51 -04002657
Nicolas Prevotdf1b87d2016-10-25 13:57:08 +01002658 private boolean removeUserUnchecked(int userHandle) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002659 long ident = Binder.clearCallingIdentity();
2660 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002661 final UserData userData;
Fyodor Kupolov0df68cd2015-10-01 13:54:22 -07002662 int currentUser = ActivityManager.getCurrentUser();
2663 if (currentUser == userHandle) {
2664 Log.w(LOG_TAG, "Current user cannot be removed");
2665 return false;
2666 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002667 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002668 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002669 userData = mUsers.get(userHandle);
2670 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002671 return false;
2672 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002673
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002674 addRemovingUserIdLocked(userHandle);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002675 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002676
Kenny Guyee58b4f2014-05-23 15:19:53 +01002677 // Set this to a partially created user, so that the user will be purged
2678 // on next startup, in case the runtime stops now before stopping and
2679 // removing the user completely.
Amith Yamasani12747872015-12-07 14:19:49 -08002680 userData.info.partial = true;
Kenny Guyee58b4f2014-05-23 15:19:53 +01002681 // Mark it as disabled, so that it isn't returned any more when
2682 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002683 userData.info.flags |= UserInfo.FLAG_DISABLED;
2684 writeUserLP(userData);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002685 }
Fyodor Kupolov6c96f7f2017-06-28 18:22:59 -07002686 try {
2687 mAppOpsService.removeUser(userHandle);
2688 } catch (RemoteException e) {
2689 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
2690 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002691
Amith Yamasani12747872015-12-07 14:19:49 -08002692 if (userData.info.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
2693 && userData.info.isManagedProfile()) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002694 // Send broadcast to notify system that the user removed was a
2695 // managed user.
Amith Yamasani12747872015-12-07 14:19:49 -08002696 sendProfileRemovedBroadcast(userData.info.profileGroupId, userData.info.id);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002697 }
2698
2699 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
2700 int res;
2701 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08002702 res = ActivityManager.getService().stopUser(userHandle, /* force= */ true,
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07002703 new IStopUserCallback.Stub() {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002704 @Override
2705 public void userStopped(int userId) {
2706 finishRemoveUser(userId);
2707 }
2708 @Override
2709 public void userStopAborted(int userId) {
2710 }
2711 });
2712 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002713 return false;
2714 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002715 return res == ActivityManager.USER_OP_SUCCESS;
2716 } finally {
2717 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002718 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002719 }
2720
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002721 @VisibleForTesting
2722 void addRemovingUserIdLocked(int userId) {
2723 // We remember deleted user IDs to prevent them from being
2724 // reused during the current boot; they can still be reused
2725 // after a reboot or recycling of userIds.
2726 mRemovingUserIds.put(userId, true);
2727 mRecentlyRemovedIds.add(userId);
2728 // Keep LRU queue of recently removed IDs for recycling
2729 if (mRecentlyRemovedIds.size() > MAX_RECENTLY_REMOVED_IDS_SIZE) {
2730 mRecentlyRemovedIds.removeFirst();
2731 }
2732 }
2733
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002734 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07002735 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002736 // Let other services shutdown any activity and clean up their state before completely
2737 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002738 long ident = Binder.clearCallingIdentity();
2739 try {
2740 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
2741 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002742 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
2743 android.Manifest.permission.MANAGE_USERS,
2744
2745 new BroadcastReceiver() {
2746 @Override
2747 public void onReceive(Context context, Intent intent) {
2748 if (DBG) {
2749 Slog.i(LOG_TAG,
2750 "USER_REMOVED broadcast sent, cleaning up user data "
2751 + userHandle);
2752 }
2753 new Thread() {
Amith Yamasani12747872015-12-07 14:19:49 -08002754 @Override
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002755 public void run() {
Amith Yamasani515d4062015-09-28 11:30:06 -07002756 // Clean up any ActivityManager state
2757 LocalServices.getService(ActivityManagerInternal.class)
2758 .onUserRemoved(userHandle);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002759 removeUserState(userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002760 }
2761 }.start();
2762 }
2763 },
2764
2765 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002766 } finally {
2767 Binder.restoreCallingIdentity(ident);
2768 }
Amith Yamasani2a003292012-08-14 18:25:45 -07002769 }
2770
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002771 private void removeUserState(final int userHandle) {
Paul Crowley91293792016-03-25 15:23:07 -07002772 try {
2773 mContext.getSystemService(StorageManager.class).destroyUserKey(userHandle);
2774 } catch (IllegalStateException e) {
2775 // This may be simply because the user was partially created.
2776 Slog.i(LOG_TAG,
2777 "Destroying key for user " + userHandle + " failed, continuing anyway", e);
2778 }
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002779
Amith Yamasanid04aaa32016-06-13 12:09:36 -07002780 // Cleanup gatekeeper secure user id
2781 try {
2782 final IGateKeeperService gk = GateKeeper.getService();
2783 if (gk != null) {
2784 gk.clearSecureUserId(userHandle);
2785 }
2786 } catch (Exception ex) {
2787 Slog.w(LOG_TAG, "unable to clear GK secure user id");
2788 }
2789
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002790 // Cleanup package manager settings
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002791 mPm.cleanUpUser(this, userHandle);
Amith Yamasanid04aaa32016-06-13 12:09:36 -07002792
2793 // Clean up all data before removing metadata
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -08002794 mUserDataPreparer.destroyUserData(userHandle,
Amith Yamasanid04aaa32016-06-13 12:09:36 -07002795 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2796
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002797 // Remove this user from the list
Fyodor Kupolov82402752015-10-28 14:54:51 -07002798 synchronized (mUsersLock) {
2799 mUsers.remove(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08002800 mIsUserManaged.delete(userHandle);
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00002801 }
2802 synchronized (mUserStates) {
2803 mUserStates.delete(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08002804 }
2805 synchronized (mRestrictionsLock) {
2806 mBaseUserRestrictions.remove(userHandle);
2807 mAppliedUserRestrictions.remove(userHandle);
2808 mCachedEffectiveUserRestrictions.remove(userHandle);
2809 mDevicePolicyLocalUserRestrictions.remove(userHandle);
Pavel Grafov6a40f092016-10-25 15:46:51 +01002810 if (mDevicePolicyGlobalUserRestrictions.get(userHandle) != null) {
2811 mDevicePolicyGlobalUserRestrictions.remove(userHandle);
2812 applyUserRestrictionsForAllUsersLR();
2813 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002814 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002815 // Update the user list
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002816 synchronized (mPackagesLock) {
2817 writeUserListLP();
2818 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06002819 // Remove user file
2820 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
2821 userFile.delete();
Fyodor Kupolov82402752015-10-28 14:54:51 -07002822 updateUserIds();
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002823 if (RELEASE_DELETED_USER_ID) {
2824 synchronized (mUsers) {
2825 mRemovingUserIds.delete(userHandle);
2826 }
2827 }
Amith Yamasani61f57372012-08-31 12:12:28 -07002828 }
2829
Kenny Guyf8d3a232014-05-15 16:09:52 +01002830 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01002831 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01002832 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
2833 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002834 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
Jeff Sharkeyaf6ec292015-12-17 11:19:00 -07002835 managedProfileIntent.putExtra(Intent.EXTRA_USER_HANDLE, removedUserId);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002836 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01002837 }
2838
Amith Yamasani2a003292012-08-14 18:25:45 -07002839 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002840 public Bundle getApplicationRestrictions(String packageName) {
2841 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
2842 }
2843
2844 @Override
2845 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002846 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07002847 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07002848 checkSystemOrRoot("get application restrictions for other user/app " + packageName);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002849 }
2850 synchronized (mPackagesLock) {
2851 // Read the restrictions from XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07002852 return readApplicationRestrictionsLP(packageName, userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002853 }
2854 }
2855
2856 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002857 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002858 int userId) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00002859 checkSystemOrRoot("set application restrictions");
Fyodor Kupolov0d88d542016-04-19 11:37:22 -07002860 if (restrictions != null) {
2861 restrictions.setDefusable(true);
2862 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002863 synchronized (mPackagesLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01002864 if (restrictions == null || restrictions.isEmpty()) {
2865 cleanAppRestrictionsForPackage(packageName, userId);
2866 } else {
2867 // Write the restrictions to XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07002868 writeApplicationRestrictionsLP(packageName, restrictions, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01002869 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002870 }
Robin Lee66e5d962014-04-09 16:44:21 +01002871
Fyodor Kupolovd2846122016-02-11 18:06:34 -08002872 // Notify package of changes via an intent - only sent to explicitly registered receivers.
2873 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
2874 changeIntent.setPackage(packageName);
2875 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
2876 mContext.sendBroadcastAsUser(changeIntent, UserHandle.of(userId));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002877 }
2878
2879 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07002880 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002881 try {
2882 return mContext.getPackageManager().getApplicationInfo(packageName,
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07002883 PackageManager.MATCH_ANY_USER).uid;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002884 } catch (NameNotFoundException nnfe) {
2885 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07002886 } finally {
2887 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002888 }
2889 }
2890
Fyodor Kupolov82402752015-10-28 14:54:51 -07002891 private Bundle readApplicationRestrictionsLP(String packageName, int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002892 AtomicFile restrictionsFile =
2893 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
2894 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002895 return readApplicationRestrictionsLP(restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002896 }
2897
2898 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002899 static Bundle readApplicationRestrictionsLP(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002900 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002901 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002902 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07002903 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002904 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002905
2906 FileInputStream fis = null;
2907 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002908 fis = restrictionsFile.openRead();
2909 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002910 parser.setInput(fis, StandardCharsets.UTF_8.name());
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002911 XmlUtils.nextElement(parser);
2912 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002913 Slog.e(LOG_TAG, "Unable to read restrictions file "
2914 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002915 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002916 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002917 while (parser.next() != XmlPullParser.END_DOCUMENT) {
2918 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002919 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002920 } catch (IOException|XmlPullParserException e) {
2921 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002922 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002923 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002924 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002925 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002926 }
2927
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002928 private static void readEntry(Bundle restrictions, ArrayList<String> values,
2929 XmlPullParser parser) throws XmlPullParserException, IOException {
2930 int type = parser.getEventType();
2931 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
2932 String key = parser.getAttributeValue(null, ATTR_KEY);
2933 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
2934 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
2935 if (multiple != null) {
2936 values.clear();
2937 int count = Integer.parseInt(multiple);
2938 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
2939 if (type == XmlPullParser.START_TAG
2940 && parser.getName().equals(TAG_VALUE)) {
2941 values.add(parser.nextText().trim());
2942 count--;
2943 }
2944 }
2945 String [] valueStrings = new String[values.size()];
2946 values.toArray(valueStrings);
2947 restrictions.putStringArray(key, valueStrings);
2948 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
2949 restrictions.putBundle(key, readBundleEntry(parser, values));
2950 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
2951 final int outerDepth = parser.getDepth();
2952 ArrayList<Bundle> bundleList = new ArrayList<>();
2953 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2954 Bundle childBundle = readBundleEntry(parser, values);
2955 bundleList.add(childBundle);
2956 }
2957 restrictions.putParcelableArray(key,
2958 bundleList.toArray(new Bundle[bundleList.size()]));
2959 } else {
2960 String value = parser.nextText().trim();
2961 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
2962 restrictions.putBoolean(key, Boolean.parseBoolean(value));
2963 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
2964 restrictions.putInt(key, Integer.parseInt(value));
2965 } else {
2966 restrictions.putString(key, value);
2967 }
2968 }
2969 }
2970 }
2971
2972 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
2973 throws IOException, XmlPullParserException {
2974 Bundle childBundle = new Bundle();
2975 final int outerDepth = parser.getDepth();
2976 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2977 readEntry(childBundle, values, parser);
2978 }
2979 return childBundle;
2980 }
2981
Fyodor Kupolov82402752015-10-28 14:54:51 -07002982 private void writeApplicationRestrictionsLP(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002983 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002984 AtomicFile restrictionsFile = new AtomicFile(
2985 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07002986 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002987 writeApplicationRestrictionsLP(restrictions, restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002988 }
2989
2990 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002991 static void writeApplicationRestrictionsLP(Bundle restrictions, AtomicFile restrictionsFile) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002992 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002993 try {
2994 fos = restrictionsFile.startWrite();
2995 final BufferedOutputStream bos = new BufferedOutputStream(fos);
2996
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002997 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002998 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002999 serializer.startDocument(null, true);
3000 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
3001
3002 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003003 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003004 serializer.endTag(null, TAG_RESTRICTIONS);
3005
3006 serializer.endDocument();
3007 restrictionsFile.finishWrite(fos);
3008 } catch (Exception e) {
3009 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003010 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
3011 }
3012 }
3013
3014 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
3015 throws IOException {
3016 for (String key : restrictions.keySet()) {
3017 Object value = restrictions.get(key);
3018 serializer.startTag(null, TAG_ENTRY);
3019 serializer.attribute(null, ATTR_KEY, key);
3020
3021 if (value instanceof Boolean) {
3022 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
3023 serializer.text(value.toString());
3024 } else if (value instanceof Integer) {
3025 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
3026 serializer.text(value.toString());
3027 } else if (value == null || value instanceof String) {
3028 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
3029 serializer.text(value != null ? (String) value : "");
3030 } else if (value instanceof Bundle) {
3031 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
3032 writeBundle((Bundle) value, serializer);
3033 } else if (value instanceof Parcelable[]) {
3034 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
3035 Parcelable[] array = (Parcelable[]) value;
3036 for (Parcelable parcelable : array) {
3037 if (!(parcelable instanceof Bundle)) {
3038 throw new IllegalArgumentException("bundle-array can only hold Bundles");
3039 }
3040 serializer.startTag(null, TAG_ENTRY);
3041 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
3042 writeBundle((Bundle) parcelable, serializer);
3043 serializer.endTag(null, TAG_ENTRY);
3044 }
3045 } else {
3046 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
3047 String[] values = (String[]) value;
3048 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
3049 for (String choice : values) {
3050 serializer.startTag(null, TAG_VALUE);
3051 serializer.text(choice != null ? choice : "");
3052 serializer.endTag(null, TAG_VALUE);
3053 }
3054 }
3055 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003056 }
3057 }
3058
3059 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07003060 public int getUserSerialNumber(int userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003061 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07003062 if (!exists(userHandle)) return -1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003063 return getUserInfoLU(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07003064 }
3065 }
3066
3067 @Override
Fyodor Kupolov605b12a2017-05-10 15:58:09 -07003068 public boolean isUserNameSet(int userHandle) {
3069 synchronized (mUsersLock) {
3070 UserInfo userInfo = getUserInfoLU(userHandle);
3071 return userInfo != null && userInfo.name != null;
3072 }
3073 }
3074
3075 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07003076 public int getUserHandle(int userSerialNumber) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003077 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07003078 for (int userId : mUserIds) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003079 UserInfo info = getUserInfoLU(userId);
Kenny Guy945f8832015-02-10 15:17:26 +00003080 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07003081 }
3082 // Not found
3083 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07003084 }
3085 }
3086
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003087 @Override
3088 public long getUserCreationTime(int userHandle) {
3089 int callingUserId = UserHandle.getCallingUserId();
3090 UserInfo userInfo = null;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003091 synchronized (mUsersLock) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003092 if (callingUserId == userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003093 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003094 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003095 UserInfo parent = getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003096 if (parent != null && parent.id == callingUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003097 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003098 }
3099 }
3100 }
3101 if (userInfo == null) {
3102 throw new SecurityException("userHandle can only be the calling user or a managed "
3103 + "profile associated with this user");
3104 }
3105 return userInfo.creationTime;
3106 }
3107
Amith Yamasani0b285492011-04-14 17:35:23 -07003108 /**
3109 * Caches the list of user ids in an array, adjusting the array size when necessary.
3110 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07003111 private void updateUserIds() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003112 int num = 0;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003113 synchronized (mUsersLock) {
3114 final int userSize = mUsers.size();
3115 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003116 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003117 num++;
3118 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003119 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07003120 final int[] newUsers = new int[num];
3121 int n = 0;
3122 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003123 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003124 newUsers[n++] = mUsers.keyAt(i);
3125 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003126 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07003127 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07003128 }
3129 }
3130
3131 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003132 * Called right before a user is started. This gives us a chance to prepare
3133 * app storage and apply any user restrictions.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003134 */
3135 public void onBeforeStartUser(int userId) {
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003136 UserInfo userInfo = getUserInfo(userId);
3137 if (userInfo == null) {
3138 return;
3139 }
3140 final int userSerial = userInfo.serialNumber;
3141 // Migrate only if build fingerprints mismatch
3142 boolean migrateAppsData = !Build.FINGERPRINT.equals(userInfo.lastLoggedInFingerprint);
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -08003143 mUserDataPreparer.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_DE);
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003144 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_DE, migrateAppsData);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003145
3146 if (userId != UserHandle.USER_SYSTEM) {
3147 synchronized (mRestrictionsLock) {
3148 applyUserRestrictionsLR(userId);
3149 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003150 }
3151 }
3152
3153 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003154 * Called right before a user is unlocked. This gives us a chance to prepare
3155 * app storage.
3156 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003157 public void onBeforeUnlockUser(@UserIdInt int userId) {
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003158 UserInfo userInfo = getUserInfo(userId);
3159 if (userInfo == null) {
3160 return;
3161 }
3162 final int userSerial = userInfo.serialNumber;
3163 // Migrate only if build fingerprints mismatch
3164 boolean migrateAppsData = !Build.FINGERPRINT.equals(userInfo.lastLoggedInFingerprint);
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -08003165 mUserDataPreparer.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_CE);
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003166 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_CE, migrateAppsData);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003167 }
3168
3169 /**
Fyodor Kupolov50979d12017-01-27 17:36:32 -08003170 * Examine all users present on given mounted volume, and destroy data
3171 * belonging to users that are no longer valid, or whose user ID has been
3172 * recycled.
3173 */
3174 void reconcileUsers(String volumeUuid) {
3175 mUserDataPreparer.reconcileUsers(volumeUuid, getUsers(true /* excludeDying */));
3176 }
3177
3178 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07003179 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasanieb437d42016-04-29 09:31:25 -07003180 * This is called with ActivityManagerService lock held.
Amith Yamasani920ace02012-09-20 22:15:37 -07003181 * @param userId the user that was just foregrounded
3182 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003183 public void onUserLoggedIn(@UserIdInt int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -08003184 UserData userData = getUserDataNoChecks(userId);
3185 if (userData == null || userData.info.partial) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003186 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
3187 return;
3188 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003189
3190 final long now = System.currentTimeMillis();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003191 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani12747872015-12-07 14:19:49 -08003192 userData.info.lastLoggedInTime = now;
Amith Yamasani920ace02012-09-20 22:15:37 -07003193 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003194 userData.info.lastLoggedInFingerprint = Build.FINGERPRINT;
3195 scheduleWriteUser(userData);
Amith Yamasani920ace02012-09-20 22:15:37 -07003196 }
3197
3198 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07003199 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani0b285492011-04-14 17:35:23 -07003200 */
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003201 @VisibleForTesting
3202 int getNextAvailableId() {
3203 int nextId;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003204 synchronized (mUsersLock) {
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003205 nextId = scanNextAvailableIdLocked();
3206 if (nextId >= 0) {
3207 return nextId;
3208 }
3209 // All ids up to MAX_USER_ID were used. Remove all mRemovingUserIds,
3210 // except most recently removed
3211 if (mRemovingUserIds.size() > 0) {
3212 Slog.i(LOG_TAG, "All available IDs are used. Recycling LRU ids.");
3213 mRemovingUserIds.clear();
3214 for (Integer recentlyRemovedId : mRecentlyRemovedIds) {
3215 mRemovingUserIds.put(recentlyRemovedId, true);
Amith Yamasani195263742012-08-21 15:40:12 -07003216 }
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003217 nextId = scanNextAvailableIdLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003218 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003219 }
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003220 if (nextId < 0) {
3221 throw new IllegalStateException("No user id available!");
3222 }
3223 return nextId;
3224 }
3225
3226 private int scanNextAvailableIdLocked() {
3227 for (int i = MIN_USER_ID; i < MAX_USER_ID; i++) {
3228 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
3229 return i;
3230 }
3231 }
3232 return -1;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003233 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003234
Amith Yamasanifc95e702013-09-26 13:20:17 -07003235 private String packageToRestrictionsFileName(String packageName) {
3236 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
3237 }
3238
Amith Yamasani920ace02012-09-20 22:15:37 -07003239 @Override
Amith Yamasani12747872015-12-07 14:19:49 -08003240 public void setSeedAccountData(int userId, String accountName, String accountType,
3241 PersistableBundle accountOptions, boolean persist) {
3242 checkManageUsersPermission("Require MANAGE_USERS permission to set user seed data");
3243 synchronized (mPackagesLock) {
3244 final UserData userData;
3245 synchronized (mUsersLock) {
3246 userData = getUserDataLU(userId);
3247 if (userData == null) {
3248 Slog.e(LOG_TAG, "No such user for settings seed data u=" + userId);
3249 return;
3250 }
3251 userData.seedAccountName = accountName;
3252 userData.seedAccountType = accountType;
3253 userData.seedAccountOptions = accountOptions;
3254 userData.persistSeedData = persist;
3255 }
3256 if (persist) {
3257 writeUserLP(userData);
3258 }
3259 }
3260 }
3261
3262 @Override
3263 public String getSeedAccountName() throws RemoteException {
3264 checkManageUsersPermission("Cannot get seed account information");
3265 synchronized (mUsersLock) {
3266 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3267 return userData.seedAccountName;
3268 }
3269 }
3270
3271 @Override
3272 public String getSeedAccountType() throws RemoteException {
3273 checkManageUsersPermission("Cannot get seed account information");
3274 synchronized (mUsersLock) {
3275 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3276 return userData.seedAccountType;
3277 }
3278 }
3279
3280 @Override
3281 public PersistableBundle getSeedAccountOptions() throws RemoteException {
3282 checkManageUsersPermission("Cannot get seed account information");
3283 synchronized (mUsersLock) {
3284 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3285 return userData.seedAccountOptions;
3286 }
3287 }
3288
3289 @Override
3290 public void clearSeedAccountData() throws RemoteException {
3291 checkManageUsersPermission("Cannot clear seed account information");
3292 synchronized (mPackagesLock) {
3293 UserData userData;
3294 synchronized (mUsersLock) {
3295 userData = getUserDataLU(UserHandle.getCallingUserId());
3296 if (userData == null) return;
3297 userData.clearSeedAccountData();
3298 }
3299 writeUserLP(userData);
3300 }
3301 }
3302
3303 @Override
3304 public boolean someUserHasSeedAccount(String accountName, String accountType)
3305 throws RemoteException {
3306 checkManageUsersPermission("Cannot check seed account information");
3307 synchronized (mUsersLock) {
3308 final int userSize = mUsers.size();
3309 for (int i = 0; i < userSize; i++) {
3310 final UserData data = mUsers.valueAt(i);
3311 if (data.info.isInitialized()) continue;
3312 if (data.seedAccountName == null || !data.seedAccountName.equals(accountName)) {
3313 continue;
3314 }
3315 if (data.seedAccountType == null || !data.seedAccountType.equals(accountType)) {
3316 continue;
3317 }
3318 return true;
3319 }
3320 }
3321 return false;
3322 }
3323
3324 @Override
Todd Kennedy60459ab2015-10-30 11:32:16 -07003325 public void onShellCommand(FileDescriptor in, FileDescriptor out,
Dianne Hackborn354736e2016-08-22 17:00:05 -07003326 FileDescriptor err, String[] args, ShellCallback callback,
3327 ResultReceiver resultReceiver) {
3328 (new Shell()).exec(this, in, out, err, args, callback, resultReceiver);
Todd Kennedy60459ab2015-10-30 11:32:16 -07003329 }
3330
3331 int onShellCommand(Shell shell, String cmd) {
3332 if (cmd == null) {
3333 return shell.handleDefaultCommands(cmd);
3334 }
3335
3336 final PrintWriter pw = shell.getOutPrintWriter();
3337 try {
3338 switch(cmd) {
3339 case "list":
3340 return runList(pw);
3341 }
3342 } catch (RemoteException e) {
3343 pw.println("Remote exception: " + e);
3344 }
3345 return -1;
3346 }
3347
3348 private int runList(PrintWriter pw) throws RemoteException {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003349 final IActivityManager am = ActivityManager.getService();
Todd Kennedy60459ab2015-10-30 11:32:16 -07003350 final List<UserInfo> users = getUsers(false);
3351 if (users == null) {
3352 pw.println("Error: couldn't get users");
3353 return 1;
3354 } else {
3355 pw.println("Users:");
3356 for (int i = 0; i < users.size(); i++) {
Jeff Sharkeye17ac152015-11-06 22:40:29 -08003357 String running = am.isUserRunning(users.get(i).id, 0) ? " running" : "";
Todd Kennedy60459ab2015-10-30 11:32:16 -07003358 pw.println("\t" + users.get(i).toString() + running);
3359 }
3360 return 0;
3361 }
3362 }
3363
3364 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -07003365 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06003366 if (!DumpUtils.checkDumpPermission(mContext, LOG_TAG, pw)) return;
Amith Yamasani920ace02012-09-20 22:15:37 -07003367
3368 long now = System.currentTimeMillis();
3369 StringBuilder sb = new StringBuilder();
3370 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003371 synchronized (mUsersLock) {
3372 pw.println("Users:");
3373 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003374 UserData userData = mUsers.valueAt(i);
3375 if (userData == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003376 continue;
3377 }
Amith Yamasani12747872015-12-07 14:19:49 -08003378 UserInfo userInfo = userData.info;
3379 final int userId = userInfo.id;
3380 pw.print(" "); pw.print(userInfo);
3381 pw.print(" serialNo="); pw.print(userInfo.serialNumber);
Makoto Onukie7927da2015-11-25 10:05:17 -08003382 if (mRemovingUserIds.get(userId)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003383 pw.print(" <removing> ");
3384 }
Amith Yamasani12747872015-12-07 14:19:49 -08003385 if (userInfo.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003386 pw.print(" <partial>");
3387 }
3388 pw.println();
Makoto Onuki88aef752017-03-29 16:52:03 -07003389 pw.print(" State: ");
3390 final int state;
3391 synchronized (mUserStates) {
3392 state = mUserStates.get(userId, -1);
3393 }
3394 pw.println(UserState.stateToString(state));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003395 pw.print(" Created: ");
Amith Yamasani12747872015-12-07 14:19:49 -08003396 if (userInfo.creationTime == 0) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003397 pw.println("<unknown>");
3398 } else {
3399 sb.setLength(0);
Amith Yamasani12747872015-12-07 14:19:49 -08003400 TimeUtils.formatDuration(now - userInfo.creationTime, sb);
Fyodor Kupolov82402752015-10-28 14:54:51 -07003401 sb.append(" ago");
3402 pw.println(sb);
3403 }
3404 pw.print(" Last logged in: ");
Amith Yamasani12747872015-12-07 14:19:49 -08003405 if (userInfo.lastLoggedInTime == 0) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003406 pw.println("<unknown>");
3407 } else {
3408 sb.setLength(0);
Amith Yamasani12747872015-12-07 14:19:49 -08003409 TimeUtils.formatDuration(now - userInfo.lastLoggedInTime, sb);
Fyodor Kupolov82402752015-10-28 14:54:51 -07003410 sb.append(" ago");
3411 pw.println(sb);
3412 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003413 pw.print(" Last logged in fingerprint: ");
3414 pw.println(userInfo.lastLoggedInFingerprint);
Makoto Onukie7927da2015-11-25 10:05:17 -08003415 pw.print(" Has profile owner: ");
3416 pw.println(mIsUserManaged.get(userId));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003417 pw.println(" Restrictions:");
3418 synchronized (mRestrictionsLock) {
3419 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003420 pw, " ", mBaseUserRestrictions.get(userInfo.id));
Pavel Grafov6a40f092016-10-25 15:46:51 +01003421 pw.println(" Device policy global restrictions:");
3422 UserRestrictionsUtils.dumpRestrictions(
3423 pw, " ", mDevicePolicyGlobalUserRestrictions.get(userInfo.id));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003424 pw.println(" Device policy local restrictions:");
3425 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003426 pw, " ", mDevicePolicyLocalUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003427 pw.println(" Effective restrictions:");
3428 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003429 pw, " ", mCachedEffectiveUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003430 }
Amith Yamasani12747872015-12-07 14:19:49 -08003431
3432 if (userData.account != null) {
3433 pw.print(" Account name: " + userData.account);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08003434 pw.println();
3435 }
Amith Yamasani12747872015-12-07 14:19:49 -08003436
3437 if (userData.seedAccountName != null) {
3438 pw.print(" Seed account name: " + userData.seedAccountName);
3439 pw.println();
3440 if (userData.seedAccountType != null) {
3441 pw.print(" account type: " + userData.seedAccountType);
3442 pw.println();
3443 }
3444 if (userData.seedAccountOptions != null) {
3445 pw.print(" account options exist");
3446 pw.println();
3447 }
3448 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003449 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003450 }
Amith Yamasani12747872015-12-07 14:19:49 -08003451 pw.println();
Pavel Grafov6a40f092016-10-25 15:46:51 +01003452 pw.println(" Device owner id:" + mDeviceOwnerUserId);
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01003453 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003454 pw.println(" Guest restrictions:");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003455 synchronized (mGuestRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003456 UserRestrictionsUtils.dumpRestrictions(pw, " ", mGuestRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003457 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003458 synchronized (mUsersLock) {
3459 pw.println();
3460 pw.println(" Device managed: " + mIsDeviceManaged);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003461 if (mRemovingUserIds.size() > 0) {
3462 pw.println();
3463 pw.println(" Recently removed userIds: " + mRecentlyRemovedIds);
3464 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003465 }
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003466 synchronized (mUserStates) {
3467 pw.println(" Started users state: " + mUserStates);
3468 }
Amith Yamasani12747872015-12-07 14:19:49 -08003469 // Dump some capabilities
3470 pw.println();
3471 pw.println(" Max users: " + UserManager.getMaxSupportedUsers());
3472 pw.println(" Supports switchable users: " + UserManager.supportsMultipleUsers());
Lenka Trochtova02fee152015-12-22 14:26:18 +01003473 pw.println(" All guests ephemeral: " + Resources.getSystem().getBoolean(
3474 com.android.internal.R.bool.config_guestUserEphemeral));
Amith Yamasani920ace02012-09-20 22:15:37 -07003475 }
3476 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08003477
3478 final class MainHandler extends Handler {
3479
3480 @Override
3481 public void handleMessage(Message msg) {
3482 switch (msg.what) {
3483 case WRITE_USER_MSG:
3484 removeMessages(WRITE_USER_MSG, msg.obj);
3485 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08003486 int userId = ((UserData) msg.obj).info.id;
3487 UserData userData = getUserDataNoChecks(userId);
3488 if (userData != null) {
3489 writeUserLP(userData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08003490 }
3491 }
3492 }
3493 }
3494 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07003495
3496 /**
3497 * @param userId
3498 * @return whether the user has been initialized yet
3499 */
3500 boolean isInitialized(int userId) {
3501 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
3502 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003503
3504 private class LocalService extends UserManagerInternal {
Makoto Onuki068c54a2015-10-13 14:34:03 -07003505 @Override
Pavel Grafov6a40f092016-10-25 15:46:51 +01003506 public void setDevicePolicyUserRestrictions(int userId, @Nullable Bundle restrictions,
3507 boolean isDeviceOwner, int cameraRestrictionScope) {
3508 UserManagerService.this.setDevicePolicyUserRestrictionsInner(userId, restrictions,
3509 isDeviceOwner, cameraRestrictionScope);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003510 }
3511
3512 @Override
3513 public Bundle getBaseUserRestrictions(int userId) {
3514 synchronized (mRestrictionsLock) {
3515 return mBaseUserRestrictions.get(userId);
3516 }
3517 }
3518
3519 @Override
3520 public void setBaseUserRestrictionsByDpmsForMigration(
3521 int userId, Bundle baseRestrictions) {
3522 synchronized (mRestrictionsLock) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01003523 if (updateRestrictionsIfNeededLR(
3524 userId, new Bundle(baseRestrictions), mBaseUserRestrictions)) {
3525 invalidateEffectiveUserRestrictionsLR(userId);
3526 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003527 }
3528
Amith Yamasani12747872015-12-07 14:19:49 -08003529 final UserData userData = getUserDataNoChecks(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003530 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08003531 if (userData != null) {
3532 writeUserLP(userData);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003533 } else {
3534 Slog.w(LOG_TAG, "UserInfo not found for " + userId);
3535 }
3536 }
3537 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08003538
3539 @Override
3540 public boolean getUserRestriction(int userId, String key) {
3541 return getUserRestrictions(userId).getBoolean(key);
3542 }
3543
3544 @Override
3545 public void addUserRestrictionsListener(UserRestrictionsListener listener) {
3546 synchronized (mUserRestrictionsListeners) {
3547 mUserRestrictionsListeners.add(listener);
3548 }
3549 }
3550
3551 @Override
3552 public void removeUserRestrictionsListener(UserRestrictionsListener listener) {
3553 synchronized (mUserRestrictionsListeners) {
3554 mUserRestrictionsListeners.remove(listener);
3555 }
3556 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003557
3558 @Override
3559 public void setDeviceManaged(boolean isManaged) {
3560 synchronized (mUsersLock) {
3561 mIsDeviceManaged = isManaged;
3562 }
3563 }
3564
3565 @Override
3566 public void setUserManaged(int userId, boolean isManaged) {
3567 synchronized (mUsersLock) {
3568 mIsUserManaged.put(userId, isManaged);
3569 }
3570 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01003571
3572 @Override
3573 public void setUserIcon(int userId, Bitmap bitmap) {
3574 long ident = Binder.clearCallingIdentity();
3575 try {
3576 synchronized (mPackagesLock) {
3577 UserData userData = getUserDataNoChecks(userId);
3578 if (userData == null || userData.info.partial) {
3579 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
3580 return;
3581 }
3582 writeBitmapLP(userData.info, bitmap);
3583 writeUserLP(userData);
3584 }
3585 sendUserInfoChangedBroadcast(userId);
3586 } finally {
3587 Binder.restoreCallingIdentity(ident);
3588 }
3589 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01003590
3591 @Override
3592 public void setForceEphemeralUsers(boolean forceEphemeralUsers) {
3593 synchronized (mUsersLock) {
3594 mForceEphemeralUsers = forceEphemeralUsers;
3595 }
3596 }
3597
3598 @Override
3599 public void removeAllUsers() {
3600 if (UserHandle.USER_SYSTEM == ActivityManager.getCurrentUser()) {
3601 // Remove the non-system users straight away.
3602 removeNonSystemUsers();
3603 } else {
3604 // Switch to the system user first and then remove the other users.
3605 BroadcastReceiver userSwitchedReceiver = new BroadcastReceiver() {
3606 @Override
3607 public void onReceive(Context context, Intent intent) {
3608 int userId =
3609 intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3610 if (userId != UserHandle.USER_SYSTEM) {
3611 return;
3612 }
3613 mContext.unregisterReceiver(this);
3614 removeNonSystemUsers();
3615 }
3616 };
3617 IntentFilter userSwitchedFilter = new IntentFilter();
3618 userSwitchedFilter.addAction(Intent.ACTION_USER_SWITCHED);
3619 mContext.registerReceiver(
3620 userSwitchedReceiver, userSwitchedFilter, null, mHandler);
3621
3622 // Switch to the system user.
3623 ActivityManager am =
3624 (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
3625 am.switchUser(UserHandle.USER_SYSTEM);
3626 }
3627 }
phweisse9c44062016-02-10 12:57:38 +01003628
3629 @Override
Lenka Trochtova1ddda472016-02-12 10:42:12 +01003630 public void onEphemeralUserStop(int userId) {
3631 synchronized (mUsersLock) {
3632 UserInfo userInfo = getUserInfoLU(userId);
3633 if (userInfo != null && userInfo.isEphemeral()) {
3634 // Do not allow switching back to the ephemeral user again as the user is going
3635 // to be deleted.
3636 userInfo.flags |= UserInfo.FLAG_DISABLED;
3637 if (userInfo.isGuest()) {
3638 // Indicate that the guest will be deleted after it stops.
3639 userInfo.guestToRemove = true;
3640 }
3641 }
3642 }
3643 }
3644
3645 @Override
phweisse9c44062016-02-10 12:57:38 +01003646 public UserInfo createUserEvenWhenDisallowed(String name, int flags) {
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07003647 UserInfo user = createUserInternalUnchecked(name, flags, UserHandle.USER_NULL, null);
phweisse9c44062016-02-10 12:57:38 +01003648 // Keep this in sync with UserManager.createUser
Christine Franks97a54802017-08-09 10:06:43 -07003649 if (user != null && !user.isAdmin() && !user.isDemo()) {
phweisse9c44062016-02-10 12:57:38 +01003650 setUserRestriction(UserManager.DISALLOW_SMS, true, user.id);
3651 setUserRestriction(UserManager.DISALLOW_OUTGOING_CALLS, true, user.id);
3652 }
3653 return user;
3654 }
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003655
3656 @Override
Nicolas Prevotdf1b87d2016-10-25 13:57:08 +01003657 public boolean removeUserEvenWhenDisallowed(int userId) {
3658 return removeUserUnchecked(userId);
3659 }
3660
3661 @Override
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003662 public boolean isUserRunning(int userId) {
3663 synchronized (mUserStates) {
3664 return mUserStates.get(userId, -1) >= 0;
3665 }
3666 }
3667
3668 @Override
3669 public void setUserState(int userId, int userState) {
3670 synchronized (mUserStates) {
3671 mUserStates.put(userId, userState);
3672 }
3673 }
3674
3675 @Override
3676 public void removeUserState(int userId) {
3677 synchronized (mUserStates) {
3678 mUserStates.delete(userId);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003679 }
3680 }
3681
3682 @Override
Michael Wachenschwanz3f2b6552017-05-15 13:53:09 -07003683 public int[] getUserIds() {
3684 return UserManagerService.this.getUserIds();
3685 }
3686
3687 @Override
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003688 public boolean isUserUnlockingOrUnlocked(int userId) {
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07003689 int state;
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003690 synchronized (mUserStates) {
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07003691 state = mUserStates.get(userId, -1);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003692 }
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07003693 // Special case, in the stopping/shutdown state user key can still be unlocked
3694 if (state == UserState.STATE_STOPPING || state == UserState.STATE_SHUTDOWN) {
3695 return StorageManager.isUserKeyUnlocked(userId);
3696 }
3697 return (state == UserState.STATE_RUNNING_UNLOCKING)
3698 || (state == UserState.STATE_RUNNING_UNLOCKED);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003699 }
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08003700
3701 @Override
3702 public boolean isUserUnlocked(int userId) {
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07003703 int state;
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08003704 synchronized (mUserStates) {
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07003705 state = mUserStates.get(userId, -1);
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08003706 }
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07003707 // Special case, in the stopping/shutdown state user key can still be unlocked
3708 if (state == UserState.STATE_STOPPING || state == UserState.STATE_SHUTDOWN) {
3709 return StorageManager.isUserKeyUnlocked(userId);
3710 }
3711 return state == UserState.STATE_RUNNING_UNLOCKED;
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08003712 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01003713 }
3714
3715 /* Remove all the users except of the system one. */
3716 private void removeNonSystemUsers() {
3717 ArrayList<UserInfo> usersToRemove = new ArrayList<>();
3718 synchronized (mUsersLock) {
3719 final int userSize = mUsers.size();
3720 for (int i = 0; i < userSize; i++) {
3721 UserInfo ui = mUsers.valueAt(i).info;
3722 if (ui.id != UserHandle.USER_SYSTEM) {
3723 usersToRemove.add(ui);
3724 }
3725 }
3726 }
3727 for (UserInfo ui: usersToRemove) {
3728 removeUser(ui.id);
3729 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003730 }
Todd Kennedy60459ab2015-10-30 11:32:16 -07003731
3732 private class Shell extends ShellCommand {
3733 @Override
3734 public int onCommand(String cmd) {
3735 return onShellCommand(this, cmd);
3736 }
3737
3738 @Override
3739 public void onHelp() {
3740 final PrintWriter pw = getOutPrintWriter();
3741 pw.println("User manager (user) commands:");
3742 pw.println(" help");
3743 pw.println(" Print this help text.");
3744 pw.println("");
3745 pw.println(" list");
3746 pw.println(" Prints all users on the system.");
3747 }
3748 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003749
3750 private static void debug(String message) {
3751 Log.d(LOG_TAG, message +
3752 (DBG_WITH_STACKTRACE ? " called at\n" + Debug.getCallers(10, " ") : ""));
3753 }
Kenny Guy02c89902016-11-15 19:36:38 +00003754
3755 @VisibleForTesting
3756 static int getMaxManagedProfiles() {
3757 // Allow overriding max managed profiles on debuggable builds for testing
3758 // of multiple profiles.
3759 if (!Build.IS_DEBUGGABLE) {
3760 return MAX_MANAGED_PROFILES;
3761 } else {
3762 return SystemProperties.getInt("persist.sys.max_profiles",
3763 MAX_MANAGED_PROFILES);
3764 }
3765 }
3766
3767 @VisibleForTesting
3768 int getFreeProfileBadgeLU(int parentUserId) {
3769 int maxManagedProfiles = getMaxManagedProfiles();
3770 boolean[] usedBadges = new boolean[maxManagedProfiles];
3771 final int userSize = mUsers.size();
3772 for (int i = 0; i < userSize; i++) {
3773 UserInfo ui = mUsers.valueAt(i).info;
3774 // Check which badge indexes are already used by this profile group.
3775 if (ui.isManagedProfile()
3776 && ui.profileGroupId == parentUserId
3777 && !mRemovingUserIds.get(ui.id)
3778 && ui.profileBadge < maxManagedProfiles) {
3779 usedBadges[ui.profileBadge] = true;
3780 }
3781 }
3782 for (int i = 0; i < maxManagedProfiles; i++) {
3783 if (!usedBadges[i]) {
3784 return i;
3785 }
3786 }
3787 return 0;
3788 }
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07003789
3790 /**
3791 * Checks if the given user has a managed profile associated with it.
3792 * @param userId The parent user
3793 * @return
3794 */
3795 boolean hasManagedProfile(int userId) {
3796 synchronized (mUsersLock) {
3797 UserInfo userInfo = getUserInfoLU(userId);
3798 final int userSize = mUsers.size();
3799 for (int i = 0; i < userSize; i++) {
3800 UserInfo profile = mUsers.valueAt(i).info;
3801 if (userId != profile.id && isProfileOf(userInfo, profile)) {
3802 return true;
3803 }
3804 }
3805 return false;
3806 }
3807 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003808}