blob: 92fd9041b32d3b1ad51decc9f5fb4c210d74f349 [file] [log] [blame]
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
Benjamin Franzf02420c2016-04-04 18:52:21 +010019import static android.content.Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS;
20import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
21
Xiaohui Chenb3b92582015-12-07 11:22:13 -080022import android.Manifest;
Xiaohui Chen594f2082015-08-18 11:04:20 -070023import android.annotation.NonNull;
Makoto Onuki068c54a2015-10-13 14:34:03 -070024import android.annotation.Nullable;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -060025import android.annotation.UserIdInt;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070026import android.app.Activity;
Amith Yamasani2a003292012-08-14 18:25:45 -070027import android.app.ActivityManager;
Amith Yamasani515d4062015-09-28 11:30:06 -070028import android.app.ActivityManagerInternal;
Andrew Scull85a63bc2016-10-24 13:47:47 +010029import android.app.ActivityManagerNative;
Todd Kennedy60459ab2015-10-30 11:32:16 -070030import android.app.IActivityManager;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070031import android.app.IStopUserCallback;
Benjamin Franzf02420c2016-04-04 18:52:21 +010032import android.app.KeyguardManager;
Ricky Waib1dd80b2016-06-07 18:00:55 +010033import android.app.PendingIntent;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070034import android.content.BroadcastReceiver;
Amith Yamasani258848d2012-08-10 17:06:33 -070035import android.content.Context;
36import android.content.Intent;
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +010037import android.content.IntentFilter;
Benjamin Franzf02420c2016-04-04 18:52:21 +010038import android.content.IntentSender;
Amith Yamasani0b285492011-04-14 17:35:23 -070039import android.content.pm.PackageManager;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -080040import android.content.pm.PackageManager.NameNotFoundException;
Tony Make3d1f652017-12-12 11:00:37 +000041import android.content.pm.ShortcutServiceInternal;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070042import android.content.pm.UserInfo;
Lenka Trochtova02fee152015-12-22 14:26:18 +010043import android.content.res.Resources;
Amith Yamasanie928d7d2012-09-17 21:46:51 -070044import android.graphics.Bitmap;
Amith Yamasani258848d2012-08-10 17:06:33 -070045import android.os.Binder;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -060046import android.os.Build;
Amith Yamasanie4cf7342012-12-17 11:12:09 -080047import android.os.Bundle;
Makoto Onuki1a2cd742015-11-16 13:51:27 -080048import android.os.Debug;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070049import android.os.Environment;
50import android.os.FileUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080051import android.os.Handler;
Svet Ganov9cea80cd2016-02-16 11:47:00 -080052import android.os.IBinder;
Tony Mak64fd8c02017-12-01 19:11:59 +000053import android.os.IProgressListener;
Amith Yamasani258848d2012-08-10 17:06:33 -070054import android.os.IUserManager;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -080055import android.os.Message;
Adrian Roos1bdff912015-02-17 15:51:35 +010056import android.os.ParcelFileDescriptor;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070057import android.os.Parcelable;
Amith Yamasani12747872015-12-07 14:19:49 -080058import android.os.PersistableBundle;
Amith Yamasani258848d2012-08-10 17:06:33 -070059import android.os.Process;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070060import android.os.RemoteException;
Todd Kennedy60459ab2015-10-30 11:32:16 -070061import android.os.ResultReceiver;
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +010062import android.os.SELinux;
Jason Monk62062992014-05-06 09:55:28 -040063import android.os.ServiceManager;
Dianne Hackborn354736e2016-08-22 17:00:05 -070064import android.os.ShellCallback;
Todd Kennedy60459ab2015-10-30 11:32:16 -070065import android.os.ShellCommand;
Makoto Onuki73dded22017-12-20 13:14:48 +090066import android.os.SystemClock;
Kenny Guy02c89902016-11-15 19:36:38 +000067import android.os.SystemProperties;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070068import android.os.UserHandle;
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070069import android.os.UserManager;
Pavel Grafov6a40f092016-10-25 15:46:51 +010070import android.os.UserManager.EnforcingUser;
Makoto Onuki068c54a2015-10-13 14:34:03 -070071import android.os.UserManagerInternal;
Makoto Onukid45a4a22015-11-02 17:17:38 -080072import android.os.UserManagerInternal.UserRestrictionsListener;
Paul Crowley85e4e812015-05-19 12:42:00 +010073import android.os.storage.StorageManager;
Amith Yamasanid04aaa32016-06-13 12:09:36 -070074import android.security.GateKeeper;
75import android.service.gatekeeper.IGateKeeperService;
Amith Yamasani2a003292012-08-14 18:25:45 -070076import android.util.AtomicFile;
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -070077import android.util.IntArray;
Amith Yamasani655d0e22013-06-12 14:19:10 -070078import android.util.Log;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070079import android.util.Slog;
80import android.util.SparseArray;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080081import android.util.SparseBooleanArray;
Amith Yamasaniea1b9d72016-05-27 15:57:38 +000082import android.util.SparseIntArray;
Makoto Onuki73dded22017-12-20 13:14:48 +090083import android.util.SparseLongArray;
Amith Yamasani920ace02012-09-20 22:15:37 -070084import android.util.TimeUtils;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070085import android.util.Xml;
86
Makoto Onuki068c54a2015-10-13 14:34:03 -070087import com.android.internal.annotations.GuardedBy;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070088import com.android.internal.annotations.VisibleForTesting;
Jason Monk62062992014-05-06 09:55:28 -040089import com.android.internal.app.IAppOpsService;
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -080090import com.android.internal.logging.MetricsLogger;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -060091import com.android.internal.util.DumpUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080092import com.android.internal.util.FastXmlSerializer;
Makoto Onuki068c54a2015-10-13 14:34:03 -070093import com.android.internal.util.Preconditions;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070094import com.android.internal.util.XmlUtils;
Clara Bayarri10ad84a2015-12-01 17:38:05 +000095import com.android.internal.widget.LockPatternUtils;
Amith Yamasani515d4062015-09-28 11:30:06 -070096import com.android.server.LocalServices;
Jeff Sharkey5f3e9342017-03-13 14:53:11 -060097import com.android.server.LockGuard;
Amith Yamasanid04aaa32016-06-13 12:09:36 -070098import com.android.server.SystemService;
Amith Yamasaniea1b9d72016-05-27 15:57:38 +000099import com.android.server.am.UserState;
Suprabh Shuklac5e057c2016-08-08 16:22:44 -0700100import com.android.server.storage.DeviceStorageMonitorInternal;
Tony Mak6dc428f2016-10-10 15:48:27 +0100101
Jeff Sharkey47f71082016-02-01 17:03:54 -0700102import libcore.io.IoUtils;
103import libcore.util.Objects;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800104
105import org.xmlpull.v1.XmlPullParser;
106import org.xmlpull.v1.XmlPullParserException;
107import org.xmlpull.v1.XmlSerializer;
108
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700109import java.io.BufferedOutputStream;
110import java.io.File;
Amith Yamasani920ace02012-09-20 22:15:37 -0700111import java.io.FileDescriptor;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700112import java.io.FileInputStream;
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700113import java.io.FileNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700114import java.io.FileOutputStream;
Tony Mak64fd8c02017-12-01 19:11:59 +0000115import java.io.IOException;
Kenny Guy02c89902016-11-15 19:36:38 +0000116import java.io.InputStream;
117import java.io.OutputStream;
Amith Yamasani920ace02012-09-20 22:15:37 -0700118import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100119import java.nio.charset.StandardCharsets;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700120import java.util.ArrayList;
Pavel Grafov6a40f092016-10-25 15:46:51 +0100121import java.util.Collections;
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700122import java.util.LinkedList;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700123import java.util.List;
124
Makoto Onuki068c54a2015-10-13 14:34:03 -0700125/**
126 * Service for {@link UserManager}.
127 *
128 * Method naming convention:
Fyodor Kupolov82402752015-10-28 14:54:51 -0700129 * <ul>
Fyodor Kupolovd31cee92017-09-05 16:31:08 -0700130 * <li> Methods suffixed with "LAr" should be called within the {@link #mAppRestrictionsLock} lock.
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();
Fyodor Kupolovd31cee92017-09-05 16:31:08 -0700235 // Used for serializing access to app restriction files
236 private final Object mAppRestrictionsLock = new Object();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700237
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800238 private final Handler mHandler;
239
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700240 private final File mUsersDir;
241 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700242
Svet Ganov9cea80cd2016-02-16 11:47:00 -0800243 private static final IBinder mUserRestriconToken = new Binder();
244
Makoto Onuki068c54a2015-10-13 14:34:03 -0700245 /**
Makoto Onuki73dded22017-12-20 13:14:48 +0900246 * Internal non-parcelable wrapper for UserInfo that is not exposed to other system apps.
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800247 */
Kenny Guy02c89902016-11-15 19:36:38 +0000248 @VisibleForTesting
249 static class UserData {
Amith Yamasani12747872015-12-07 14:19:49 -0800250 // Basic user information and properties
251 UserInfo info;
252 // Account name used when there is a strong association between a user and an account
253 String account;
254 // Account information for seeding into a newly created user. This could also be
255 // used for login validation for an existing user, for updating their credentials.
256 // In the latter case, data may not need to be persisted as it is only valid for the
257 // current login session.
258 String seedAccountName;
259 String seedAccountType;
260 PersistableBundle seedAccountOptions;
261 // Whether to perist the seed account information to be available after a boot
262 boolean persistSeedData;
263
Makoto Onuki73dded22017-12-20 13:14:48 +0900264 /** Elapsed realtime since boot when the user started. */
265 long startRealtime;
266
267 /** Elapsed realtime since boot when the user was unlocked. */
268 long unlockRealtime;
269
Amith Yamasani12747872015-12-07 14:19:49 -0800270 void clearSeedAccountData() {
271 seedAccountName = null;
272 seedAccountType = null;
273 seedAccountOptions = null;
274 persistSeedData = false;
275 }
276 }
277
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800278 @GuardedBy("mUsersLock")
Amith Yamasani12747872015-12-07 14:19:49 -0800279 private final SparseArray<UserData> mUsers = new SparseArray<>();
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800280
281 /**
Makoto Onuki068c54a2015-10-13 14:34:03 -0700282 * User restrictions set via UserManager. This doesn't include restrictions set by
Pavel Grafov6a40f092016-10-25 15:46:51 +0100283 * device owner / profile owners. Only non-empty restriction bundles are stored.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700284 *
285 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
286 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
287 * maybe shared between {@link #mBaseUserRestrictions} and
288 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
289 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700290 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700291 */
292 @GuardedBy("mRestrictionsLock")
293 private final SparseArray<Bundle> mBaseUserRestrictions = new SparseArray<>();
294
295 /**
296 * Cached user restrictions that are in effect -- i.e. {@link #mBaseUserRestrictions} combined
297 * with device / profile owner restrictions. We'll initialize it lazily; use
298 * {@link #getEffectiveUserRestrictions} to access it.
299 *
300 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
301 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
302 * maybe shared between {@link #mBaseUserRestrictions} and
303 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
304 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700305 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700306 */
307 @GuardedBy("mRestrictionsLock")
308 private final SparseArray<Bundle> mCachedEffectiveUserRestrictions = new SparseArray<>();
309
Makoto Onuki4f160732015-10-27 17:15:38 -0700310 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800311 * User restrictions that have already been applied in
312 * {@link #updateUserRestrictionsInternalLR(Bundle, int)}. We use it to detect restrictions
313 * that have changed since the last
314 * {@link #updateUserRestrictionsInternalLR(Bundle, int)} call.
Makoto Onuki4f160732015-10-27 17:15:38 -0700315 */
316 @GuardedBy("mRestrictionsLock")
317 private final SparseArray<Bundle> mAppliedUserRestrictions = new SparseArray<>();
318
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800319 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800320 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
Pavel Grafov6a40f092016-10-25 15:46:51 +0100321 * that should be applied to all users, including guests. Only non-empty restriction bundles are
322 * stored.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800323 */
324 @GuardedBy("mRestrictionsLock")
Pavel Grafov6a40f092016-10-25 15:46:51 +0100325 private final SparseArray<Bundle> mDevicePolicyGlobalUserRestrictions = new SparseArray<>();
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800326
327 /**
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +0100328 * Id of the user that set global restrictions.
329 */
330 @GuardedBy("mRestrictionsLock")
Pavel Grafov6a40f092016-10-25 15:46:51 +0100331 private int mDeviceOwnerUserId = UserHandle.USER_NULL;
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +0100332
333 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800334 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
Pavel Grafov6a40f092016-10-25 15:46:51 +0100335 * for each user. Only non-empty restriction bundles are stored.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800336 */
337 @GuardedBy("mRestrictionsLock")
338 private final SparseArray<Bundle> mDevicePolicyLocalUserRestrictions = new SparseArray<>();
339
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800340 @GuardedBy("mGuestRestrictions")
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530341 private final Bundle mGuestRestrictions = new Bundle();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800342
343 /**
344 * Set of user IDs being actively removed. Removed IDs linger in this set
345 * for several seconds to work around a VFS caching issue.
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700346 * Use {@link #addRemovingUserIdLocked(int)} to add elements to this array
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800347 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700348 @GuardedBy("mUsersLock")
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800349 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700350
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700351 /**
352 * Queue of recently removed userIds. Used for recycling of userIds
353 */
354 @GuardedBy("mUsersLock")
355 private final LinkedList<Integer> mRecentlyRemovedIds = new LinkedList<>();
356
Fyodor Kupolov82402752015-10-28 14:54:51 -0700357 @GuardedBy("mUsersLock")
Amith Yamasani0b285492011-04-14 17:35:23 -0700358 private int[] mUserIds;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800359 @GuardedBy("mPackagesLock")
Amith Yamasani2a003292012-08-14 18:25:45 -0700360 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700361 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700362
Jason Monk62062992014-05-06 09:55:28 -0400363 private IAppOpsService mAppOpsService;
364
Makoto Onuki068c54a2015-10-13 14:34:03 -0700365 private final LocalService mLocalService;
366
Makoto Onukie7927da2015-11-25 10:05:17 -0800367 @GuardedBy("mUsersLock")
368 private boolean mIsDeviceManaged;
369
370 @GuardedBy("mUsersLock")
371 private final SparseBooleanArray mIsUserManaged = new SparseBooleanArray();
372
Makoto Onukid45a4a22015-11-02 17:17:38 -0800373 @GuardedBy("mUserRestrictionsListeners")
374 private final ArrayList<UserRestrictionsListener> mUserRestrictionsListeners =
375 new ArrayList<>();
376
Clara Bayarria1771112015-12-18 16:29:18 +0000377 private final LockPatternUtils mLockPatternUtils;
378
Ricky Waib1dd80b2016-06-07 18:00:55 +0100379 private final String ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK =
380 "com.android.server.pm.DISABLE_QUIET_MODE_AFTER_UNLOCK";
381
382 private final BroadcastReceiver mDisableQuietModeCallback = new BroadcastReceiver() {
383 @Override
384 public void onReceive(Context context, Intent intent) {
Tony Mak64fd8c02017-12-01 19:11:59 +0000385 if (!ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK.equals(intent.getAction())) {
386 return;
Ricky Waib1dd80b2016-06-07 18:00:55 +0100387 }
Tony Mak64fd8c02017-12-01 19:11:59 +0000388 final IntentSender target = intent.getParcelableExtra(Intent.EXTRA_INTENT);
389 final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_ID, UserHandle.USER_NULL);
390 setQuietModeEnabled(userHandle, false, target);
Ricky Waib1dd80b2016-06-07 18:00:55 +0100391 }
392 };
393
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +0100394 /**
Tony Mak64fd8c02017-12-01 19:11:59 +0000395 * Start an {@link IntentSender} when user is unlocked after disabling quiet mode.
396 *
Tony Makbece85d2018-01-12 12:10:17 +0000397 * @see {@link #requestQuietModeEnabled(String, boolean, int, IntentSender)}
Tony Mak64fd8c02017-12-01 19:11:59 +0000398 */
399 private class DisableQuietModeUserUnlockedCallback extends IProgressListener.Stub {
400 private final IntentSender mTarget;
401
402 public DisableQuietModeUserUnlockedCallback(IntentSender target) {
403 Preconditions.checkNotNull(target);
404 mTarget = target;
405 }
406
407 @Override
408 public void onStarted(int id, Bundle extras) {}
409
410 @Override
411 public void onProgress(int id, int progress, Bundle extras) {}
412
413 @Override
414 public void onFinished(int id, Bundle extras) {
415 try {
416 mContext.startIntentSender(mTarget, null, 0, 0, 0);
417 } catch (IntentSender.SendIntentException e) {
418 Slog.e(LOG_TAG, "Failed to start the target in the callback", e);
419 }
420 }
421 }
422
423 /**
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +0100424 * Whether all users should be created ephemeral.
425 */
426 @GuardedBy("mUsersLock")
427 private boolean mForceEphemeralUsers;
428
Amith Yamasaniea1b9d72016-05-27 15:57:38 +0000429 @GuardedBy("mUserStates")
430 private final SparseIntArray mUserStates = new SparseIntArray();
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -0700431
Amith Yamasani258848d2012-08-10 17:06:33 -0700432 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700433
Dianne Hackborn4428e172012-08-24 17:43:05 -0700434 public static UserManagerService getInstance() {
435 synchronized (UserManagerService.class) {
436 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700437 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700438 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700439
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700440 public static class LifeCycle extends SystemService {
441
442 private UserManagerService mUms;
443
444 /**
445 * @param context
446 */
447 public LifeCycle(Context context) {
448 super(context);
449 }
450
451 @Override
452 public void onStart() {
453 mUms = UserManagerService.getInstance();
454 publishBinderService(Context.USER_SERVICE, mUms);
455 }
456
457 @Override
458 public void onBootPhase(int phase) {
459 if (phase == SystemService.PHASE_ACTIVITY_MANAGER_READY) {
460 mUms.cleanupPartialUsers();
461 }
462 }
Makoto Onuki73dded22017-12-20 13:14:48 +0900463
464 @Override
465 public void onStartUser(int userHandle) {
466 synchronized (mUms.mUsersLock) {
467 final UserData user = mUms.getUserDataLU(userHandle);
468 if (user != null) {
469 user.startRealtime = SystemClock.elapsedRealtime();
470 }
471 }
472 }
473
474 @Override
475 public void onUnlockUser(int userHandle) {
476 synchronized (mUms.mUsersLock) {
477 final UserData user = mUms.getUserDataLU(userHandle);
478 if (user != null) {
479 user.unlockRealtime = SystemClock.elapsedRealtime();
480 }
481 }
482 }
483
484 @Override
485 public void onStopUser(int userHandle) {
486 synchronized (mUms.mUsersLock) {
487 final UserData user = mUms.getUserDataLU(userHandle);
488 if (user != null) {
489 user.startRealtime = 0;
490 user.unlockRealtime = 0;
491 }
492 }
493 }
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700494 }
495
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700496 // TODO b/28848102 Add support for test dependencies injection
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800497 @VisibleForTesting
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700498 UserManagerService(Context context) {
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800499 this(context, null, null, new Object(), context.getCacheDir());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700500 }
501
Dianne Hackborn4428e172012-08-24 17:43:05 -0700502 /**
503 * Called by package manager to create the service. This is closely
504 * associated with the package manager, and the given lock is the
505 * package manager's own lock.
506 */
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800507 UserManagerService(Context context, PackageManagerService pm, UserDataPreparer userDataPreparer,
508 Object packagesLock) {
509 this(context, pm, userDataPreparer, packagesLock, Environment.getDataDirectory());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700510 }
511
Dianne Hackborn4428e172012-08-24 17:43:05 -0700512 private UserManagerService(Context context, PackageManagerService pm,
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800513 UserDataPreparer userDataPreparer, Object packagesLock, File dataDir) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700514 mContext = context;
515 mPm = pm;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700516 mPackagesLock = packagesLock;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800517 mHandler = new MainHandler();
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800518 mUserDataPreparer = userDataPreparer;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800519 synchronized (mPackagesLock) {
520 mUsersDir = new File(dataDir, USER_INFO_DIR);
521 mUsersDir.mkdirs();
522 // Make zeroth user directory, for services to migrate their files to that location
523 File userZeroDir = new File(mUsersDir, String.valueOf(UserHandle.USER_SYSTEM));
524 userZeroDir.mkdirs();
525 FileUtils.setPermissions(mUsersDir.toString(),
526 FileUtils.S_IRWXU | FileUtils.S_IRWXG | FileUtils.S_IROTH | FileUtils.S_IXOTH,
527 -1, -1);
528 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
529 initDefaultGuestRestrictions();
530 readUserListLP();
531 sInstance = this;
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700532 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700533 mLocalService = new LocalService();
534 LocalServices.addService(UserManagerInternal.class, mLocalService);
Clara Bayarria1771112015-12-18 16:29:18 +0000535 mLockPatternUtils = new LockPatternUtils(mContext);
Amith Yamasaniea1b9d72016-05-27 15:57:38 +0000536 mUserStates.put(UserHandle.USER_SYSTEM, UserState.STATE_BOOTING);
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700537 }
538
539 void systemReady() {
Jason Monk62062992014-05-06 09:55:28 -0400540 mAppOpsService = IAppOpsService.Stub.asInterface(
541 ServiceManager.getService(Context.APP_OPS_SERVICE));
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800542
543 synchronized (mRestrictionsLock) {
544 applyUserRestrictionsLR(UserHandle.USER_SYSTEM);
Jason Monk62062992014-05-06 09:55:28 -0400545 }
Samuel Tand9453b82016-03-14 15:57:02 -0700546
547 UserInfo currentGuestUser = findCurrentGuestUser();
548 if (currentGuestUser != null && !hasUserRestriction(
549 UserManager.DISALLOW_CONFIG_WIFI, currentGuestUser.id)) {
550 // If a guest user currently exists, apply the DISALLOW_CONFIG_WIFI option
551 // to it, in case this guest was created in a previous version where this
552 // user restriction was not a default guest restriction.
553 setUserRestriction(UserManager.DISALLOW_CONFIG_WIFI, true, currentGuestUser.id);
554 }
Amith Yamasanieb437d42016-04-29 09:31:25 -0700555
Ricky Waib1dd80b2016-06-07 18:00:55 +0100556 mContext.registerReceiver(mDisableQuietModeCallback,
557 new IntentFilter(ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK),
558 null, mHandler);
Amith Yamasani258848d2012-08-10 17:06:33 -0700559 }
560
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700561 void cleanupPartialUsers() {
562 // Prune out any partially created, partially removed and ephemeral users.
563 ArrayList<UserInfo> partials = new ArrayList<>();
564 synchronized (mUsersLock) {
565 final int userSize = mUsers.size();
566 for (int i = 0; i < userSize; i++) {
567 UserInfo ui = mUsers.valueAt(i).info;
568 if ((ui.partial || ui.guestToRemove || ui.isEphemeral()) && i != 0) {
569 partials.add(ui);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700570 addRemovingUserIdLocked(ui.id);
Amith Yamasaniae261892016-06-27 10:40:09 -0700571 ui.partial = true;
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700572 }
573 }
574 }
575 final int partialsSize = partials.size();
576 for (int i = 0; i < partialsSize; i++) {
577 UserInfo ui = partials.get(i);
578 Slog.w(LOG_TAG, "Removing partially created user " + ui.id
579 + " (name=" + ui.name + ")");
580 removeUserState(ui.id);
581 }
582 }
583
Amith Yamasani258848d2012-08-10 17:06:33 -0700584 @Override
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800585 public String getUserAccount(int userId) {
586 checkManageUserAndAcrossUsersFullPermission("get user account");
587 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800588 return mUsers.get(userId).account;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800589 }
590 }
591
592 @Override
593 public void setUserAccount(int userId, String accountName) {
594 checkManageUserAndAcrossUsersFullPermission("set user account");
Amith Yamasani12747872015-12-07 14:19:49 -0800595 UserData userToUpdate = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800596 synchronized (mPackagesLock) {
597 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800598 final UserData userData = mUsers.get(userId);
599 if (userData == null) {
600 Slog.e(LOG_TAG, "User not found for setting user account: u" + userId);
601 return;
602 }
603 String currentAccount = userData.account;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800604 if (!Objects.equal(currentAccount, accountName)) {
Amith Yamasani12747872015-12-07 14:19:49 -0800605 userData.account = accountName;
606 userToUpdate = userData;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800607 }
608 }
609
610 if (userToUpdate != null) {
611 writeUserLP(userToUpdate);
612 }
613 }
614 }
615
616 @Override
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700617 public UserInfo getPrimaryUser() {
618 checkManageUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700619 synchronized (mUsersLock) {
Amith Yamasani515d4062015-09-28 11:30:06 -0700620 final int userSize = mUsers.size();
621 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800622 UserInfo ui = mUsers.valueAt(i).info;
Xiaohui Chend3e9e182015-11-18 13:37:32 -0800623 if (ui.isPrimary() && !mRemovingUserIds.get(ui.id)) {
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700624 return ui;
625 }
626 }
627 }
628 return null;
629 }
630
631 @Override
Xiaohui Chen594f2082015-08-18 11:04:20 -0700632 public @NonNull List<UserInfo> getUsers(boolean excludeDying) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -0700633 checkManageOrCreateUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700634 synchronized (mUsersLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700635 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasani515d4062015-09-28 11:30:06 -0700636 final int userSize = mUsers.size();
637 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800638 UserInfo ui = mUsers.valueAt(i).info;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700639 if (ui.partial) {
640 continue;
641 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800642 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Amith Yamasani6f48d6e2016-03-23 14:28:25 -0700643 users.add(userWithName(ui));
Amith Yamasani920ace02012-09-20 22:15:37 -0700644 }
Amith Yamasani13593602012-03-22 16:16:17 -0700645 }
646 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700647 }
Amith Yamasani13593602012-03-22 16:16:17 -0700648 }
649
Amith Yamasani258848d2012-08-10 17:06:33 -0700650 @Override
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100651 public List<UserInfo> getProfiles(int userId, boolean enabledOnly) {
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700652 boolean returnFullInfo = true;
Amith Yamasani4f582632014-02-19 14:31:52 -0800653 if (userId != UserHandle.getCallingUserId()) {
Sudheer Shanka74680912016-07-29 11:03:37 -0700654 checkManageOrCreateUsersPermission("getting profiles related to user " + userId);
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700655 } else {
656 returnFullInfo = hasManageUsersPermission();
Amith Yamasani4f582632014-02-19 14:31:52 -0800657 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700658 final long ident = Binder.clearCallingIdentity();
659 try {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700660 synchronized (mUsersLock) {
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700661 return getProfilesLU(userId, enabledOnly, returnFullInfo);
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100662 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700663 } finally {
664 Binder.restoreCallingIdentity(ident);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000665 }
666 }
667
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700668 @Override
669 public int[] getProfileIds(int userId, boolean enabledOnly) {
670 if (userId != UserHandle.getCallingUserId()) {
bohu12d23a12016-09-26 16:20:07 -0700671 checkManageOrCreateUsersPermission("getting profiles related to user " + userId);
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700672 }
673 final long ident = Binder.clearCallingIdentity();
674 try {
675 synchronized (mUsersLock) {
676 return getProfileIdsLU(userId, enabledOnly).toArray();
677 }
678 } finally {
679 Binder.restoreCallingIdentity(ident);
680 }
681 }
682
Amith Yamasanibe465322014-04-24 13:45:17 -0700683 /** Assume permissions already checked and caller's identity cleared */
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700684 private List<UserInfo> getProfilesLU(int userId, boolean enabledOnly, boolean fullInfo) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700685 IntArray profileIds = getProfileIdsLU(userId, enabledOnly);
686 ArrayList<UserInfo> users = new ArrayList<>(profileIds.size());
687 for (int i = 0; i < profileIds.size(); i++) {
688 int profileId = profileIds.get(i);
689 UserInfo userInfo = mUsers.get(profileId).info;
690 // If full info is not required - clear PII data to prevent 3P apps from reading it
691 if (!fullInfo) {
692 userInfo = new UserInfo(userInfo);
693 userInfo.name = null;
694 userInfo.iconPath = null;
695 } else {
696 userInfo = userWithName(userInfo);
697 }
698 users.add(userInfo);
699 }
700 return users;
701 }
702
703 /**
704 * Assume permissions already checked and caller's identity cleared
705 */
706 private IntArray getProfileIdsLU(int userId, boolean enabledOnly) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700707 UserInfo user = getUserInfoLU(userId);
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700708 IntArray result = new IntArray(mUsers.size());
Amith Yamasanidda003f2014-08-28 18:06:51 -0700709 if (user == null) {
710 // Probably a dying user
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700711 return result;
Amith Yamasanidda003f2014-08-28 18:06:51 -0700712 }
Amith Yamasani515d4062015-09-28 11:30:06 -0700713 final int userSize = mUsers.size();
714 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800715 UserInfo profile = mUsers.valueAt(i).info;
Amith Yamasanibe465322014-04-24 13:45:17 -0700716 if (!isProfileOf(user, profile)) {
717 continue;
718 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100719 if (enabledOnly && !profile.isEnabled()) {
720 continue;
Amith Yamasanibe465322014-04-24 13:45:17 -0700721 }
Amith Yamasani70fcf0c2014-07-11 08:40:19 -0700722 if (mRemovingUserIds.get(profile.id)) {
723 continue;
724 }
Tony Mak80189cd2016-04-05 17:21:42 +0100725 if (profile.partial) {
726 continue;
727 }
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700728 result.add(profile.id);
Amith Yamasanibe465322014-04-24 13:45:17 -0700729 }
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700730 return result;
Amith Yamasanibe465322014-04-24 13:45:17 -0700731 }
732
Jessica Hummelbe81c802014-04-22 15:49:22 +0100733 @Override
Andres Moralesc5548c02015-08-05 10:23:12 -0700734 public int getCredentialOwnerProfile(int userHandle) {
735 checkManageUsersPermission("get the credential owner");
Clara Bayarria1771112015-12-18 16:29:18 +0000736 if (!mLockPatternUtils.isSeparateProfileChallengeEnabled(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700737 synchronized (mUsersLock) {
738 UserInfo profileParent = getProfileParentLU(userHandle);
Andres Moralesc5548c02015-08-05 10:23:12 -0700739 if (profileParent != null) {
740 return profileParent.id;
741 }
742 }
743 }
744
745 return userHandle;
746 }
747
748 @Override
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700749 public boolean isSameProfileGroup(int userId, int otherUserId) {
750 if (userId == otherUserId) return true;
751 checkManageUsersPermission("check if in the same profile group");
Fyodor Kupolov0fb772e2016-10-13 16:27:34 -0700752 return isSameProfileGroupNoChecks(userId, otherUserId);
753 }
754
755 private boolean isSameProfileGroupNoChecks(int userId, int otherUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700756 synchronized (mUsersLock) {
757 UserInfo userInfo = getUserInfoLU(userId);
758 if (userInfo == null || userInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
759 return false;
760 }
761 UserInfo otherUserInfo = getUserInfoLU(otherUserId);
762 if (otherUserInfo == null
763 || otherUserInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
764 return false;
765 }
766 return userInfo.profileGroupId == otherUserInfo.profileGroupId;
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700767 }
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700768 }
769
770 @Override
Jessica Hummelbe81c802014-04-22 15:49:22 +0100771 public UserInfo getProfileParent(int userHandle) {
772 checkManageUsersPermission("get the profile parent");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700773 synchronized (mUsersLock) {
774 return getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700775 }
776 }
777
Jakub Pawlowski0f1f5b72017-11-15 14:50:43 -0800778 @Override
779 public int getProfileParentId(int userHandle) {
780 checkManageUsersPermission("get the profile parent");
781 synchronized (mUsersLock) {
782 UserInfo profileParent = getProfileParentLU(userHandle);
783 if (profileParent == null) {
784 return userHandle;
785 }
786
787 return profileParent.id;
788 }
789 }
790
Fyodor Kupolov82402752015-10-28 14:54:51 -0700791 private UserInfo getProfileParentLU(int userHandle) {
792 UserInfo profile = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700793 if (profile == null) {
794 return null;
795 }
796 int parentUserId = profile.profileGroupId;
Amith Yamasani801e3422017-01-25 11:35:44 -0800797 if (parentUserId == userHandle || parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700798 return null;
799 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700800 return getUserInfoLU(parentUserId);
Jessica Hummelbe81c802014-04-22 15:49:22 +0100801 }
802 }
803
Fyodor Kupolov82402752015-10-28 14:54:51 -0700804 private static boolean isProfileOf(UserInfo user, UserInfo profile) {
Kenny Guy2a764942014-04-02 13:29:20 +0100805 return user.id == profile.id ||
806 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
807 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000808 }
809
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000810 private void broadcastProfileAvailabilityChanges(UserHandle profileHandle,
Rubin Xuf13c9802016-01-21 18:06:00 +0000811 UserHandle parentHandle, boolean inQuietMode) {
Rubin Xue95057a2016-04-01 16:49:25 +0100812 Intent intent = new Intent();
813 if (inQuietMode) {
814 intent.setAction(Intent.ACTION_MANAGED_PROFILE_UNAVAILABLE);
815 } else {
816 intent.setAction(Intent.ACTION_MANAGED_PROFILE_AVAILABLE);
817 }
Rubin Xuf13c9802016-01-21 18:06:00 +0000818 intent.putExtra(Intent.EXTRA_QUIET_MODE, inQuietMode);
819 intent.putExtra(Intent.EXTRA_USER, profileHandle);
820 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileHandle.getIdentifier());
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000821 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Rubin Xuf13c9802016-01-21 18:06:00 +0000822 mContext.sendBroadcastAsUser(intent, parentHandle);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000823 }
824
825 @Override
Tony Makbece85d2018-01-12 12:10:17 +0000826 public boolean requestQuietModeEnabled(@NonNull String callingPackage, boolean enableQuietMode,
Tony Make3d1f652017-12-12 11:00:37 +0000827 int userHandle, @Nullable IntentSender target) {
828 Preconditions.checkNotNull(callingPackage);
829
Tony Makb7e6fd42017-12-05 19:40:28 +0000830 if (enableQuietMode && target != null) {
831 throw new IllegalArgumentException(
832 "target should only be specified when we are disabling quiet mode.");
833 }
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000834
Tony Makd390ae92017-12-28 13:23:10 +0000835 ensureCanModifyQuietMode(callingPackage, Binder.getCallingUid(), target != null);
Tony Makb7e6fd42017-12-05 19:40:28 +0000836 final long identity = Binder.clearCallingIdentity();
837 try {
838 if (enableQuietMode) {
839 setQuietModeEnabled(userHandle, true /* enableQuietMode */, target);
840 return true;
841 } else {
842 boolean needToShowConfirmCredential =
843 mLockPatternUtils.isSecure(userHandle)
844 && !StorageManager.isUserKeyUnlocked(userHandle);
845 if (needToShowConfirmCredential) {
846 showConfirmCredentialToDisableQuietMode(userHandle, target);
847 return false;
848 } else {
849 setQuietModeEnabled(userHandle, false /* enableQuietMode */, target);
850 return true;
851 }
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000852 }
Tony Makb7e6fd42017-12-05 19:40:28 +0000853 } finally {
854 Binder.restoreCallingIdentity(identity);
855 }
856 }
857
Tony Make3d1f652017-12-12 11:00:37 +0000858 /**
Tony Makd390ae92017-12-28 13:23:10 +0000859 * The caller can modify quiet mode if it meets one of these conditions:
Tony Make3d1f652017-12-12 11:00:37 +0000860 * <ul>
861 * <li>Has system UID or root UID</li>
862 * <li>Has {@link Manifest.permission#MODIFY_QUIET_MODE}</li>
863 * <li>Has {@link Manifest.permission#MANAGE_USERS}</li>
864 * </ul>
Tony Makd390ae92017-12-28 13:23:10 +0000865 * <p>
866 * If caller wants to start an intent after disabling the quiet mode, it must has
867 * {@link Manifest.permission#MANAGE_USERS}.
Tony Make3d1f652017-12-12 11:00:37 +0000868 */
Tony Makd390ae92017-12-28 13:23:10 +0000869 private void ensureCanModifyQuietMode(String callingPackage, int callingUid,
870 boolean startIntent) {
Tony Make3d1f652017-12-12 11:00:37 +0000871 if (hasManageUsersPermission()) {
Tony Makd390ae92017-12-28 13:23:10 +0000872 return;
Tony Make3d1f652017-12-12 11:00:37 +0000873 }
Tony Makd390ae92017-12-28 13:23:10 +0000874 if (startIntent) {
875 throw new SecurityException("MANAGE_USERS permission is required to start intent "
876 + "after disabling quiet mode.");
877 }
Tony Make3d1f652017-12-12 11:00:37 +0000878 final boolean hasModifyQuietModePermission = ActivityManager.checkComponentPermission(
879 Manifest.permission.MODIFY_QUIET_MODE,
880 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED;
881 if (hasModifyQuietModePermission) {
Tony Makd390ae92017-12-28 13:23:10 +0000882 return;
Tony Make3d1f652017-12-12 11:00:37 +0000883 }
884
Tony Makd390ae92017-12-28 13:23:10 +0000885 verifyCallingPackage(callingPackage, callingUid);
Tony Make3d1f652017-12-12 11:00:37 +0000886 final ShortcutServiceInternal shortcutInternal =
887 LocalServices.getService(ShortcutServiceInternal.class);
888 if (shortcutInternal != null) {
889 boolean isForegroundLauncher =
890 shortcutInternal.isForegroundDefaultLauncher(callingPackage, callingUid);
891 if (isForegroundLauncher) {
Tony Makd390ae92017-12-28 13:23:10 +0000892 return;
Tony Make3d1f652017-12-12 11:00:37 +0000893 }
894 }
Tony Makd390ae92017-12-28 13:23:10 +0000895 throw new SecurityException("Can't modify quiet mode, caller is neither foreground "
896 + "default launcher nor has MANAGE_USERS/MODIFY_QUIET_MODE permission");
Tony Make3d1f652017-12-12 11:00:37 +0000897 }
898
Tony Makb7e6fd42017-12-05 19:40:28 +0000899 private void setQuietModeEnabled(
900 int userHandle, boolean enableQuietMode, IntentSender target) {
901 final UserInfo profile, parent;
902 final UserData profileUserData;
903 synchronized (mUsersLock) {
904 profile = getUserInfoLU(userHandle);
905 parent = getProfileParentLU(userHandle);
906
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000907 if (profile == null || !profile.isManagedProfile()) {
908 throw new IllegalArgumentException("User " + userHandle + " is not a profile");
909 }
Tony Makb7e6fd42017-12-05 19:40:28 +0000910 if (profile.isQuietModeEnabled() == enableQuietMode) {
911 Slog.i(LOG_TAG, "Quiet mode is already " + enableQuietMode);
912 return;
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000913 }
Tony Makb7e6fd42017-12-05 19:40:28 +0000914 profile.flags ^= UserInfo.FLAG_QUIET_MODE;
915 profileUserData = getUserDataLU(profile.id);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000916 }
Tony Makb7e6fd42017-12-05 19:40:28 +0000917 synchronized (mPackagesLock) {
918 writeUserLP(profileUserData);
919 }
920 try {
921 if (enableQuietMode) {
922 ActivityManager.getService().stopUser(userHandle, /* force */true, null);
923 LocalServices.getService(ActivityManagerInternal.class)
924 .killForegroundAppsForUser(userHandle);
925 } else {
926 IProgressListener callback = target != null
927 ? new DisableQuietModeUserUnlockedCallback(target)
928 : null;
929 ActivityManager.getService().startUserInBackgroundWithListener(
930 userHandle, callback);
Rubin Xuf13c9802016-01-21 18:06:00 +0000931 }
Tony Makb7e6fd42017-12-05 19:40:28 +0000932 } catch (RemoteException e) {
933 // Should not happen, same process.
934 e.rethrowAsRuntimeException();
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000935 }
Tony Makb7e6fd42017-12-05 19:40:28 +0000936 broadcastProfileAvailabilityChanges(profile.getUserHandle(), parent.getUserHandle(),
937 enableQuietMode);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000938 }
939
940 @Override
941 public boolean isQuietModeEnabled(int userHandle) {
942 synchronized (mPackagesLock) {
943 UserInfo info;
944 synchronized (mUsersLock) {
945 info = getUserInfoLU(userHandle);
946 }
947 if (info == null || !info.isManagedProfile()) {
Rubin Xuf13c9802016-01-21 18:06:00 +0000948 return false;
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000949 }
950 return info.isQuietModeEnabled();
951 }
952 }
953
Tony Makb7e6fd42017-12-05 19:40:28 +0000954 /**
955 * Show confirm credential screen to unlock user in order to turn off quiet mode.
956 */
957 private void showConfirmCredentialToDisableQuietMode(
Tony Mak64fd8c02017-12-01 19:11:59 +0000958 @UserIdInt int userHandle, @Nullable IntentSender target) {
Tony Makb7e6fd42017-12-05 19:40:28 +0000959 // otherwise, we show a profile challenge to trigger decryption of the user
960 final KeyguardManager km = (KeyguardManager) mContext.getSystemService(
961 Context.KEYGUARD_SERVICE);
962 // We should use userHandle not credentialOwnerUserId here, as even if it is unified
963 // lock, confirm screenlock page will know and show personal challenge, and unlock
964 // work profile when personal challenge is correct
965 final Intent unlockIntent = km.createConfirmDeviceCredentialIntent(null, null,
966 userHandle);
967 if (unlockIntent == null) {
968 return;
Benjamin Franzf02420c2016-04-04 18:52:21 +0100969 }
Tony Makb7e6fd42017-12-05 19:40:28 +0000970 final Intent callBackIntent = new Intent(
971 ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK);
972 if (target != null) {
973 callBackIntent.putExtra(Intent.EXTRA_INTENT, target);
Benjamin Franzf02420c2016-04-04 18:52:21 +0100974 }
Tony Makb7e6fd42017-12-05 19:40:28 +0000975 callBackIntent.putExtra(Intent.EXTRA_USER_ID, userHandle);
976 callBackIntent.setPackage(mContext.getPackageName());
977 callBackIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
978 final PendingIntent pendingIntent = PendingIntent.getBroadcast(
979 mContext,
980 0,
981 callBackIntent,
982 PendingIntent.FLAG_CANCEL_CURRENT |
983 PendingIntent.FLAG_ONE_SHOT |
984 PendingIntent.FLAG_IMMUTABLE);
985 // After unlocking the challenge, it will disable quiet mode and run the original
986 // intentSender
987 unlockIntent.putExtra(Intent.EXTRA_INTENT, pendingIntent.getIntentSender());
988 unlockIntent.setFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
989 mContext.startActivity(unlockIntent);
Benjamin Franzf02420c2016-04-04 18:52:21 +0100990 }
991
992 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100993 public void setUserEnabled(int userId) {
994 checkManageUsersPermission("enable user");
995 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700996 UserInfo info;
997 synchronized (mUsersLock) {
998 info = getUserInfoLU(userId);
999 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +01001000 if (info != null && !info.isEnabled()) {
1001 info.flags ^= UserInfo.FLAG_DISABLED;
Amith Yamasani12747872015-12-07 14:19:49 -08001002 writeUserLP(getUserDataLU(info.id));
Alexandra Gherghinadf35d572014-04-09 13:54:39 +01001003 }
1004 }
1005 }
1006
Andrew Scull85a63bc2016-10-24 13:47:47 +01001007 /**
1008 * Evicts a user's CE key by stopping and restarting the user.
1009 *
1010 * The key is evicted automatically by the user controller when the user has stopped.
1011 */
1012 @Override
1013 public void evictCredentialEncryptionKey(@UserIdInt int userId) {
1014 checkManageUsersPermission("evict CE key");
1015 final IActivityManager am = ActivityManagerNative.getDefault();
1016 final long identity = Binder.clearCallingIdentity();
1017 try {
1018 am.restartUserInBackground(userId);
1019 } catch (RemoteException re) {
1020 throw re.rethrowAsRuntimeException();
1021 } finally {
1022 Binder.restoreCallingIdentity(identity);
1023 }
1024 }
1025
Alexandra Gherghinadf35d572014-04-09 13:54:39 +01001026 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -07001027 public UserInfo getUserInfo(int userId) {
Sudheer Shankaaccaa082016-06-14 16:22:57 -07001028 checkManageOrCreateUsersPermission("query user");
Tony Mak8673b282016-03-21 21:10:59 +00001029 synchronized (mUsersLock) {
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001030 return userWithName(getUserInfoLU(userId));
1031 }
1032 }
1033
1034 /**
1035 * Returns a UserInfo object with the name filled in, for Owner, or the original
1036 * if the name is already set.
1037 */
1038 private UserInfo userWithName(UserInfo orig) {
1039 if (orig != null && orig.name == null && orig.id == UserHandle.USER_SYSTEM) {
1040 UserInfo withName = new UserInfo(orig);
1041 withName.name = getOwnerName();
1042 return withName;
1043 } else {
1044 return orig;
Tony Mak8673b282016-03-21 21:10:59 +00001045 }
1046 }
1047
1048 @Override
Kenny Guy02c89902016-11-15 19:36:38 +00001049 public int getManagedProfileBadge(@UserIdInt int userId) {
1050 int callingUserId = UserHandle.getCallingUserId();
1051 if (callingUserId != userId && !hasManageUsersPermission()) {
1052 if (!isSameProfileGroupNoChecks(callingUserId, userId)) {
1053 throw new SecurityException(
1054 "You need MANAGE_USERS permission to: check if specified user a " +
1055 "managed profile outside your profile group");
1056 }
1057 }
1058 synchronized (mUsersLock) {
1059 UserInfo userInfo = getUserInfoLU(userId);
1060 return userInfo != null ? userInfo.profileBadge : 0;
1061 }
1062 }
1063
1064 @Override
Tony Mak8673b282016-03-21 21:10:59 +00001065 public boolean isManagedProfile(int userId) {
Tony Makb531d082016-03-16 14:49:52 +00001066 int callingUserId = UserHandle.getCallingUserId();
1067 if (callingUserId != userId && !hasManageUsersPermission()) {
Fyodor Kupolov0fb772e2016-10-13 16:27:34 -07001068 if (!isSameProfileGroupNoChecks(callingUserId, userId)) {
Fyodor Kupolovc413f702016-10-06 17:11:14 -07001069 throw new SecurityException(
1070 "You need MANAGE_USERS permission to: check if specified user a " +
1071 "managed profile outside your profile group");
Tony Makb531d082016-03-16 14:49:52 +00001072 }
Tony Mak4dc008c2016-03-16 10:46:49 +00001073 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001074 synchronized (mUsersLock) {
Amith Yamasani1c41dc82016-06-28 16:13:15 -07001075 UserInfo userInfo = getUserInfoLU(userId);
Tony Mak8673b282016-03-21 21:10:59 +00001076 return userInfo != null && userInfo.isManagedProfile();
Amith Yamasani13593602012-03-22 16:16:17 -07001077 }
1078 }
1079
Amith Yamasani71e6c692013-03-24 17:39:28 -07001080 @Override
Fyodor Kupolovc413f702016-10-06 17:11:14 -07001081 public boolean isUserUnlockingOrUnlocked(int userId) {
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08001082 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isUserUnlockingOrUnlocked");
Fyodor Kupolovc413f702016-10-06 17:11:14 -07001083 return mLocalService.isUserUnlockingOrUnlocked(userId);
1084 }
1085
1086 @Override
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08001087 public boolean isUserUnlocked(int userId) {
1088 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isUserUnlocked");
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07001089 return mLocalService.isUserUnlocked(userId);
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08001090 }
1091
1092 @Override
1093 public boolean isUserRunning(int userId) {
1094 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isUserRunning");
1095 return mLocalService.isUserRunning(userId);
1096 }
1097
Makoto Onuki73dded22017-12-20 13:14:48 +09001098 @Override
1099 public long getUserStartRealtime() {
1100 final int userId = UserHandle.getUserId(Binder.getCallingUid());
1101 synchronized (mUsersLock) {
1102 final UserData user = getUserDataLU(userId);
1103 if (user != null) {
1104 return user.startRealtime;
1105 }
1106 return 0;
1107 }
1108 }
1109
1110 @Override
1111 public long getUserUnlockRealtime() {
1112 synchronized (mUsersLock) {
1113 final UserData user = getUserDataLU(UserHandle.getUserId(Binder.getCallingUid()));
1114 if (user != null) {
1115 return user.unlockRealtime;
1116 }
1117 return 0;
1118 }
1119 }
1120
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08001121 private void checkManageOrInteractPermIfCallerInOtherProfileGroup(int userId, String name) {
1122 int callingUserId = UserHandle.getCallingUserId();
1123 if (callingUserId == userId || isSameProfileGroupNoChecks(callingUserId, userId) ||
1124 hasManageUsersPermission()) {
1125 return;
1126 }
1127 if (ActivityManager.checkComponentPermission(Manifest.permission.INTERACT_ACROSS_USERS,
1128 Binder.getCallingUid(), -1, true) != PackageManager.PERMISSION_GRANTED) {
1129 throw new SecurityException("You need INTERACT_ACROSS_USERS or MANAGE_USERS permission "
1130 + "to: check " + name);
1131 }
1132 }
1133
1134 @Override
Amith Yamasani1c41dc82016-06-28 16:13:15 -07001135 public boolean isDemoUser(int userId) {
1136 int callingUserId = UserHandle.getCallingUserId();
1137 if (callingUserId != userId && !hasManageUsersPermission()) {
1138 throw new SecurityException("You need MANAGE_USERS permission to query if u=" + userId
1139 + " is a demo user");
1140 }
1141 synchronized (mUsersLock) {
1142 UserInfo userInfo = getUserInfoLU(userId);
1143 return userInfo != null && userInfo.isDemo();
1144 }
1145 }
1146
1147 @Override
Amith Yamasani71e6c692013-03-24 17:39:28 -07001148 public boolean isRestricted() {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001149 synchronized (mUsersLock) {
1150 return getUserInfoLU(UserHandle.getCallingUserId()).isRestricted();
Amith Yamasani71e6c692013-03-24 17:39:28 -07001151 }
1152 }
1153
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001154 @Override
1155 public boolean canHaveRestrictedProfile(int userId) {
1156 checkManageUsersPermission("canHaveRestrictedProfile");
Fyodor Kupolov82402752015-10-28 14:54:51 -07001157 synchronized (mUsersLock) {
1158 final UserInfo userInfo = getUserInfoLU(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001159 if (userInfo == null || !userInfo.canHaveProfile()) {
1160 return false;
1161 }
1162 if (!userInfo.isAdmin()) {
1163 return false;
1164 }
Makoto Onukie7927da2015-11-25 10:05:17 -08001165 // restricted profile can be created if there is no DO set and the admin user has no PO;
1166 return !mIsDeviceManaged && !mIsUserManaged.get(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001167 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001168 }
1169
Fyodor Kupolovca177562017-11-09 17:43:01 -08001170 @Override
1171 public boolean hasRestrictedProfiles() {
1172 checkManageUsersPermission("hasRestrictedProfiles");
1173 final int callingUserId = UserHandle.getCallingUserId();
1174 synchronized (mUsersLock) {
1175 final int userSize = mUsers.size();
1176 for (int i = 0; i < userSize; i++) {
1177 UserInfo profile = mUsers.valueAt(i).info;
1178 if (callingUserId != profile.id
1179 && profile.restrictedProfileParentId == callingUserId) {
1180 return true;
1181 }
1182 }
1183 return false;
1184 }
1185 }
1186
Amith Yamasani195263742012-08-21 15:40:12 -07001187 /*
1188 * Should be locked on mUsers before calling this.
1189 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001190 private UserInfo getUserInfoLU(int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -08001191 final UserData userData = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -07001192 // If it is partial and not in the process of being removed, return as unknown user.
Amith Yamasani12747872015-12-07 14:19:49 -08001193 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001194 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
1195 return null;
1196 }
Amith Yamasani12747872015-12-07 14:19:49 -08001197 return userData != null ? userData.info : null;
1198 }
1199
1200 private UserData getUserDataLU(int userId) {
1201 final UserData userData = mUsers.get(userId);
1202 // If it is partial and not in the process of being removed, return as unknown user.
1203 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
1204 return null;
1205 }
1206 return userData;
Amith Yamasani195263742012-08-21 15:40:12 -07001207 }
1208
Fyodor Kupolov82402752015-10-28 14:54:51 -07001209 /**
1210 * Obtains {@link #mUsersLock} and return UserInfo from mUsers.
1211 * <p>No permissions checking or any addition checks are made</p>
1212 */
1213 private UserInfo getUserInfoNoChecks(int userId) {
1214 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001215 final UserData userData = mUsers.get(userId);
1216 return userData != null ? userData.info : null;
1217 }
1218 }
1219
1220 /**
1221 * Obtains {@link #mUsersLock} and return UserData from mUsers.
1222 * <p>No permissions checking or any addition checks are made</p>
1223 */
1224 private UserData getUserDataNoChecks(int userId) {
1225 synchronized (mUsersLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001226 return mUsers.get(userId);
1227 }
1228 }
1229
Amith Yamasani236b2b52015-08-18 14:32:14 -07001230 /** Called by PackageManagerService */
Amith Yamasani13593602012-03-22 16:16:17 -07001231 public boolean exists(int userId) {
Todd Kennedy0eb97382017-10-03 16:57:22 -07001232 return mLocalService.exists(userId);
Amith Yamasani13593602012-03-22 16:16:17 -07001233 }
1234
Amith Yamasani258848d2012-08-10 17:06:33 -07001235 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001236 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001237 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001238 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -07001239 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001240 UserData userData = getUserDataNoChecks(userId);
1241 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001242 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
1243 return;
1244 }
Amith Yamasani12747872015-12-07 14:19:49 -08001245 if (name != null && !name.equals(userData.info.name)) {
1246 userData.info.name = name;
1247 writeUserLP(userData);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001248 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -07001249 }
1250 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001251 if (changed) {
1252 sendUserInfoChangedBroadcast(userId);
1253 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001254 }
1255
Amith Yamasani258848d2012-08-10 17:06:33 -07001256 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001257 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001258 checkManageUsersPermission("update users");
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01001259 if (hasUserRestriction(UserManager.DISALLOW_SET_USER_ICON, userId)) {
1260 Log.w(LOG_TAG, "Cannot set user icon. DISALLOW_SET_USER_ICON is enabled.");
1261 return;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001262 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01001263 mLocalService.setUserIcon(userId, bitmap);
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001264 }
1265
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01001266
1267
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001268 private void sendUserInfoChangedBroadcast(int userId) {
1269 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
1270 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
1271 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -07001272 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001273 }
1274
Amith Yamasani258848d2012-08-10 17:06:33 -07001275 @Override
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001276 public ParcelFileDescriptor getUserIcon(int targetUserId) {
Adrian Roos1bdff912015-02-17 15:51:35 +01001277 String iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001278 synchronized (mPackagesLock) {
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001279 UserInfo targetUserInfo = getUserInfoNoChecks(targetUserId);
1280 if (targetUserInfo == null || targetUserInfo.partial) {
1281 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + targetUserId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001282 return null;
1283 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001284
1285 final int callingUserId = UserHandle.getCallingUserId();
1286 final int callingGroupId = getUserInfoNoChecks(callingUserId).profileGroupId;
1287 final int targetGroupId = targetUserInfo.profileGroupId;
1288 final boolean sameGroup = (callingGroupId != UserInfo.NO_PROFILE_GROUP_ID
1289 && callingGroupId == targetGroupId);
1290 if ((callingUserId != targetUserId) && !sameGroup) {
Nicolas Prevot88cc3462014-05-14 14:51:48 +01001291 checkManageUsersPermission("get the icon of a user who is not related");
1292 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001293
1294 if (targetUserInfo.iconPath == null) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001295 return null;
1296 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001297 iconPath = targetUserInfo.iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001298 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001299
1300 try {
1301 return ParcelFileDescriptor.open(
1302 new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
1303 } catch (FileNotFoundException e) {
1304 Log.e(LOG_TAG, "Couldn't find icon file", e);
1305 }
1306 return null;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001307 }
1308
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001309 public void makeInitialized(int userId) {
1310 checkManageUsersPermission("makeInitialized");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001311 boolean scheduleWriteUser = false;
Amith Yamasani12747872015-12-07 14:19:49 -08001312 UserData userData;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001313 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001314 userData = mUsers.get(userId);
1315 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001316 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001317 return;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001318 }
Amith Yamasani12747872015-12-07 14:19:49 -08001319 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1320 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001321 scheduleWriteUser = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001322 }
1323 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001324 if (scheduleWriteUser) {
Amith Yamasani12747872015-12-07 14:19:49 -08001325 scheduleWriteUser(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001326 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001327 }
1328
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001329 /**
1330 * If default guest restrictions haven't been initialized yet, add the basic
1331 * restrictions.
1332 */
1333 private void initDefaultGuestRestrictions() {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001334 synchronized (mGuestRestrictions) {
1335 if (mGuestRestrictions.isEmpty()) {
Samuel Tand9453b82016-03-14 15:57:02 -07001336 mGuestRestrictions.putBoolean(UserManager.DISALLOW_CONFIG_WIFI, true);
Fyodor Kupolove04462c2015-11-30 15:02:53 -08001337 mGuestRestrictions.putBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, true);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001338 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
1339 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
1340 }
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001341 }
1342 }
1343
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001344 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301345 public Bundle getDefaultGuestRestrictions() {
1346 checkManageUsersPermission("getDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001347 synchronized (mGuestRestrictions) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301348 return new Bundle(mGuestRestrictions);
1349 }
1350 }
1351
1352 @Override
1353 public void setDefaultGuestRestrictions(Bundle restrictions) {
1354 checkManageUsersPermission("setDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001355 synchronized (mGuestRestrictions) {
1356 mGuestRestrictions.clear();
1357 mGuestRestrictions.putAll(restrictions);
1358 }
1359 synchronized (mPackagesLock) {
1360 writeUserListLP();
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301361 }
1362 }
1363
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001364 /**
Pavel Grafov6a40f092016-10-25 15:46:51 +01001365 * See {@link UserManagerInternal#setDevicePolicyUserRestrictions}
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001366 */
Pavel Grafov6a40f092016-10-25 15:46:51 +01001367 private void setDevicePolicyUserRestrictionsInner(int userId, @Nullable Bundle restrictions,
1368 boolean isDeviceOwner, int cameraRestrictionScope) {
1369 final Bundle global = new Bundle();
1370 final Bundle local = new Bundle();
1371
1372 // Sort restrictions into local and global ensuring they don't overlap.
1373 UserRestrictionsUtils.sortToGlobalAndLocal(restrictions, isDeviceOwner,
1374 cameraRestrictionScope, global, local);
1375
1376 boolean globalChanged, localChanged;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001377 synchronized (mRestrictionsLock) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001378 // Update global and local restrictions if they were changed.
1379 globalChanged = updateRestrictionsIfNeededLR(
1380 userId, global, mDevicePolicyGlobalUserRestrictions);
1381 localChanged = updateRestrictionsIfNeededLR(
1382 userId, local, mDevicePolicyLocalUserRestrictions);
1383
1384 if (isDeviceOwner) {
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001385 // Remember the global restriction owner userId to be able to make a distinction
1386 // in getUserRestrictionSource on who set local policies.
Pavel Grafov6a40f092016-10-25 15:46:51 +01001387 mDeviceOwnerUserId = userId;
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001388 } else {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001389 if (mDeviceOwnerUserId == userId) {
Zoltan Szatmary-Ban8a5536d2016-05-27 17:56:44 +01001390 // When profile owner sets restrictions it passes null global bundle and we
1391 // reset global restriction owner userId.
1392 // This means this user used to have DO, but now the DO is gone and the user
1393 // instead has PO.
Pavel Grafov6a40f092016-10-25 15:46:51 +01001394 mDeviceOwnerUserId = UserHandle.USER_NULL;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001395 }
1396 }
1397 }
1398 if (DBG) {
1399 Log.d(LOG_TAG, "setDevicePolicyUserRestrictions: userId=" + userId
1400 + " global=" + global + (globalChanged ? " (changed)" : "")
1401 + " local=" + local + (localChanged ? " (changed)" : "")
1402 );
1403 }
1404 // Don't call them within the mRestrictionsLock.
1405 synchronized (mPackagesLock) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001406 if (localChanged || globalChanged) {
Amith Yamasani12747872015-12-07 14:19:49 -08001407 writeUserLP(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001408 }
1409 }
1410
1411 synchronized (mRestrictionsLock) {
1412 if (globalChanged) {
1413 applyUserRestrictionsForAllUsersLR();
1414 } else if (localChanged) {
1415 applyUserRestrictionsLR(userId);
1416 }
1417 }
1418 }
1419
Pavel Grafov6a40f092016-10-25 15:46:51 +01001420 /**
1421 * Updates restriction bundle for a given user in a given restriction array. If new bundle is
1422 * empty, record is removed from the array.
1423 * @return whether restrictions bundle is different from the old one.
1424 */
1425 private boolean updateRestrictionsIfNeededLR(int userId, @Nullable Bundle restrictions,
1426 SparseArray<Bundle> restrictionsArray) {
1427 final boolean changed =
1428 !UserRestrictionsUtils.areEqual(restrictionsArray.get(userId), restrictions);
1429 if (changed) {
1430 if (!UserRestrictionsUtils.isEmpty(restrictions)) {
1431 restrictionsArray.put(userId, restrictions);
1432 } else {
1433 restrictionsArray.delete(userId);
1434 }
1435 }
1436 return changed;
1437 }
1438
Makoto Onuki068c54a2015-10-13 14:34:03 -07001439 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001440 private Bundle computeEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001441 final Bundle baseRestrictions =
1442 UserRestrictionsUtils.nonNull(mBaseUserRestrictions.get(userId));
Pavel Grafov6a40f092016-10-25 15:46:51 +01001443 final Bundle global = UserRestrictionsUtils.mergeAll(mDevicePolicyGlobalUserRestrictions);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001444 final Bundle local = mDevicePolicyLocalUserRestrictions.get(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001445
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001446 if (UserRestrictionsUtils.isEmpty(global) && UserRestrictionsUtils.isEmpty(local)) {
1447 // Common case first.
1448 return baseRestrictions;
Makoto Onuki068c54a2015-10-13 14:34:03 -07001449 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001450 final Bundle effective = UserRestrictionsUtils.clone(baseRestrictions);
1451 UserRestrictionsUtils.merge(effective, global);
1452 UserRestrictionsUtils.merge(effective, local);
1453
Makoto Onuki068c54a2015-10-13 14:34:03 -07001454 return effective;
1455 }
1456
1457 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001458 private void invalidateEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki068c54a2015-10-13 14:34:03 -07001459 if (DBG) {
1460 Log.d(LOG_TAG, "invalidateEffectiveUserRestrictions userId=" + userId);
1461 }
1462 mCachedEffectiveUserRestrictions.remove(userId);
1463 }
1464
1465 private Bundle getEffectiveUserRestrictions(int userId) {
1466 synchronized (mRestrictionsLock) {
1467 Bundle restrictions = mCachedEffectiveUserRestrictions.get(userId);
1468 if (restrictions == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001469 restrictions = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001470 mCachedEffectiveUserRestrictions.put(userId, restrictions);
1471 }
1472 return restrictions;
Amith Yamasani8cd28b52014-06-08 17:54:27 -07001473 }
1474 }
1475
Makoto Onuki068c54a2015-10-13 14:34:03 -07001476 /** @return a specific user restriction that's in effect currently. */
1477 @Override
1478 public boolean hasUserRestriction(String restrictionKey, int userId) {
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001479 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1480 return false;
1481 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001482 Bundle restrictions = getEffectiveUserRestrictions(userId);
1483 return restrictions != null && restrictions.getBoolean(restrictionKey);
1484 }
1485
1486 /**
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001487 * @hide
1488 *
1489 * Returns who set a user restriction on a user.
1490 * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
1491 * @param restrictionKey the string key representing the restriction
1492 * @param userId the id of the user for whom to retrieve the restrictions.
1493 * @return The source of user restriction. Any combination of
1494 * {@link UserManager#RESTRICTION_NOT_SET},
1495 * {@link UserManager#RESTRICTION_SOURCE_SYSTEM},
1496 * {@link UserManager#RESTRICTION_SOURCE_DEVICE_OWNER}
1497 * and {@link UserManager#RESTRICTION_SOURCE_PROFILE_OWNER}
1498 */
1499 @Override
1500 public int getUserRestrictionSource(String restrictionKey, int userId) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001501 List<EnforcingUser> enforcingUsers = getUserRestrictionSources(restrictionKey, userId);
1502 // Get "bitwise or" of restriction sources for all enforcing users.
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001503 int result = UserManager.RESTRICTION_NOT_SET;
Pavel Grafov6a40f092016-10-25 15:46:51 +01001504 for (int i = enforcingUsers.size() - 1; i >= 0; i--) {
1505 result |= enforcingUsers.get(i).getUserRestrictionSource();
1506 }
1507 return result;
1508 }
1509
1510 @Override
1511 public List<EnforcingUser> getUserRestrictionSources(
1512 String restrictionKey, @UserIdInt int userId) {
1513 checkManageUsersPermission("getUserRestrictionSource");
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001514
1515 // Shortcut for the most common case
1516 if (!hasUserRestriction(restrictionKey, userId)) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001517 return Collections.emptyList();
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001518 }
1519
Pavel Grafov6a40f092016-10-25 15:46:51 +01001520 final List<EnforcingUser> result = new ArrayList<>();
1521
1522 // Check if it is base restriction.
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001523 if (hasBaseUserRestriction(restrictionKey, userId)) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001524 result.add(new EnforcingUser(
1525 UserHandle.USER_NULL, UserManager.RESTRICTION_SOURCE_SYSTEM));
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001526 }
1527
Pavel Grafov6a40f092016-10-25 15:46:51 +01001528 synchronized (mRestrictionsLock) {
1529 // Check if it is set by profile owner.
1530 Bundle profileOwnerRestrictions = mDevicePolicyLocalUserRestrictions.get(userId);
1531 if (UserRestrictionsUtils.contains(profileOwnerRestrictions, restrictionKey)) {
1532 result.add(getEnforcingUserLocked(userId));
1533 }
1534
1535 // Iterate over all users who enforce global restrictions.
1536 for (int i = mDevicePolicyGlobalUserRestrictions.size() - 1; i >= 0; i--) {
1537 Bundle globalRestrictions = mDevicePolicyGlobalUserRestrictions.valueAt(i);
1538 int profileUserId = mDevicePolicyGlobalUserRestrictions.keyAt(i);
1539 if (UserRestrictionsUtils.contains(globalRestrictions, restrictionKey)) {
1540 result.add(getEnforcingUserLocked(profileUserId));
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001541 }
1542 }
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001543 }
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001544 return result;
1545 }
1546
Pavel Grafov6a40f092016-10-25 15:46:51 +01001547 private EnforcingUser getEnforcingUserLocked(@UserIdInt int userId) {
1548 int source = mDeviceOwnerUserId == userId ? UserManager.RESTRICTION_SOURCE_DEVICE_OWNER
1549 : UserManager.RESTRICTION_SOURCE_PROFILE_OWNER;
1550 return new EnforcingUser(userId, source);
1551 }
1552
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001553 /**
Makoto Onuki068c54a2015-10-13 14:34:03 -07001554 * @return UserRestrictions that are in effect currently. This always returns a new
1555 * {@link Bundle}.
1556 */
Amith Yamasani8cd28b52014-06-08 17:54:27 -07001557 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001558 public Bundle getUserRestrictions(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001559 return UserRestrictionsUtils.clone(getEffectiveUserRestrictions(userId));
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001560 }
1561
1562 @Override
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +00001563 public boolean hasBaseUserRestriction(String restrictionKey, int userId) {
1564 checkManageUsersPermission("hasBaseUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001565 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1566 return false;
1567 }
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +00001568 synchronized (mRestrictionsLock) {
1569 Bundle bundle = mBaseUserRestrictions.get(userId);
1570 return (bundle != null && bundle.getBoolean(restrictionKey, false));
1571 }
1572 }
1573
1574 @Override
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001575 public void setUserRestriction(String key, boolean value, int userId) {
Fyodor Kupolovd4b26042015-07-27 14:30:59 -07001576 checkManageUsersPermission("setUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001577 if (!UserRestrictionsUtils.isValidRestriction(key)) {
1578 return;
1579 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001580 synchronized (mRestrictionsLock) {
1581 // Note we can't modify Bundles stored in mBaseUserRestrictions directly, so create
1582 // a copy.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001583 final Bundle newRestrictions = UserRestrictionsUtils.clone(
1584 mBaseUserRestrictions.get(userId));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001585 newRestrictions.putBoolean(key, value);
1586
Fyodor Kupolov82402752015-10-28 14:54:51 -07001587 updateUserRestrictionsInternalLR(newRestrictions, userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001588 }
1589 }
1590
Makoto Onuki068c54a2015-10-13 14:34:03 -07001591 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001592 * Optionally updating user restrictions, calculate the effective user restrictions and also
1593 * propagate to other services and system settings.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001594 *
Pavel Grafov6a40f092016-10-25 15:46:51 +01001595 * @param newBaseRestrictions User restrictions to set.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001596 * If null, will not update user restrictions and only does the propagation.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001597 * @param userId target user ID.
1598 */
1599 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001600 private void updateUserRestrictionsInternalLR(
Pavel Grafov6a40f092016-10-25 15:46:51 +01001601 @Nullable Bundle newBaseRestrictions, int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001602 final Bundle prevAppliedRestrictions = UserRestrictionsUtils.nonNull(
1603 mAppliedUserRestrictions.get(userId));
1604
1605 // Update base restrictions.
Pavel Grafov6a40f092016-10-25 15:46:51 +01001606 if (newBaseRestrictions != null) {
1607 // If newBaseRestrictions == the current one, it's probably a bug.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001608 final Bundle prevBaseRestrictions = mBaseUserRestrictions.get(userId);
1609
Pavel Grafov6a40f092016-10-25 15:46:51 +01001610 Preconditions.checkState(prevBaseRestrictions != newBaseRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001611 Preconditions.checkState(mCachedEffectiveUserRestrictions.get(userId)
Pavel Grafov6a40f092016-10-25 15:46:51 +01001612 != newBaseRestrictions);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001613
Pavel Grafov6a40f092016-10-25 15:46:51 +01001614 if (updateRestrictionsIfNeededLR(userId, newBaseRestrictions, mBaseUserRestrictions)) {
Amith Yamasani12747872015-12-07 14:19:49 -08001615 scheduleWriteUser(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001616 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001617 }
1618
Fyodor Kupolov82402752015-10-28 14:54:51 -07001619 final Bundle effective = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001620
Makoto Onuki759a7632015-10-28 16:43:10 -07001621 mCachedEffectiveUserRestrictions.put(userId, effective);
1622
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001623 // Apply the new restrictions.
Makoto Onuki4f160732015-10-27 17:15:38 -07001624 if (DBG) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001625 debug("Applying user restrictions: userId=" + userId
1626 + " new=" + effective + " prev=" + prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001627 }
1628
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001629 if (mAppOpsService != null) { // We skip it until system-ready.
Fyodor Kupolovec30ca32016-06-16 15:09:29 -07001630 mHandler.post(new Runnable() {
1631 @Override
1632 public void run() {
1633 try {
1634 mAppOpsService.setUserRestrictions(effective, mUserRestriconToken, userId);
1635 } catch (RemoteException e) {
1636 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
1637 }
1638 }
1639 });
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001640 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001641
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001642 propagateUserRestrictionsLR(userId, effective, prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001643
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001644 mAppliedUserRestrictions.put(userId, new Bundle(effective));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001645 }
1646
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001647 private void propagateUserRestrictionsLR(final int userId,
Makoto Onukid45a4a22015-11-02 17:17:38 -08001648 Bundle newRestrictions, Bundle prevRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001649 // Note this method doesn't touch any state, meaning it doesn't require mRestrictionsLock
1650 // actually, but we still need some kind of synchronization otherwise we might end up
1651 // calling listeners out-of-order, thus "LR".
1652
1653 if (UserRestrictionsUtils.areEqual(newRestrictions, prevRestrictions)) {
1654 return;
1655 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08001656
1657 final Bundle newRestrictionsFinal = new Bundle(newRestrictions);
1658 final Bundle prevRestrictionsFinal = new Bundle(prevRestrictions);
1659
1660 mHandler.post(new Runnable() {
1661 @Override
1662 public void run() {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07001663 UserRestrictionsUtils.applyUserRestrictions(
1664 mContext, userId, newRestrictionsFinal, prevRestrictionsFinal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001665
Makoto Onukid45a4a22015-11-02 17:17:38 -08001666 final UserRestrictionsListener[] listeners;
1667 synchronized (mUserRestrictionsListeners) {
1668 listeners = new UserRestrictionsListener[mUserRestrictionsListeners.size()];
1669 mUserRestrictionsListeners.toArray(listeners);
1670 }
1671 for (int i = 0; i < listeners.length; i++) {
1672 listeners[i].onUserRestrictionsChanged(userId,
1673 newRestrictionsFinal, prevRestrictionsFinal);
1674 }
Makoto Onukie72f81b2017-03-16 14:08:19 -07001675
1676 final Intent broadcast = new Intent(UserManager.ACTION_USER_RESTRICTIONS_CHANGED)
1677 .setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
1678 mContext.sendBroadcastAsUser(broadcast, UserHandle.of(userId));
Makoto Onukid45a4a22015-11-02 17:17:38 -08001679 }
1680 });
1681 }
1682
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001683 // Package private for the inner class.
1684 void applyUserRestrictionsLR(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001685 updateUserRestrictionsInternalLR(null, userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001686 }
1687
1688 @GuardedBy("mRestrictionsLock")
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001689 // Package private for the inner class.
1690 void applyUserRestrictionsForAllUsersLR() {
1691 if (DBG) {
1692 debug("applyUserRestrictionsForAllUsersLR");
1693 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001694 // First, invalidate all cached values.
Makoto Onuki4f160732015-10-27 17:15:38 -07001695 mCachedEffectiveUserRestrictions.clear();
1696
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001697 // We don't want to call into ActivityManagerService while taking a lock, so we'll call
Makoto Onuki068c54a2015-10-13 14:34:03 -07001698 // it on a handler.
1699 final Runnable r = new Runnable() {
1700 @Override
1701 public void run() {
1702 // Then get the list of running users.
1703 final int[] runningUsers;
1704 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001705 runningUsers = ActivityManager.getService().getRunningUserIds();
Makoto Onuki068c54a2015-10-13 14:34:03 -07001706 } catch (RemoteException e) {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001707 Log.w(LOG_TAG, "Unable to access ActivityManagerService");
Makoto Onuki068c54a2015-10-13 14:34:03 -07001708 return;
1709 }
1710 // Then re-calculate the effective restrictions and apply, only for running users.
1711 // It's okay if a new user has started after the getRunningUserIds() call,
1712 // because we'll do the same thing (re-calculate the restrictions and apply)
1713 // when we start a user.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001714 synchronized (mRestrictionsLock) {
1715 for (int i = 0; i < runningUsers.length; i++) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001716 applyUserRestrictionsLR(runningUsers[i]);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001717 }
1718 }
1719 }
1720 };
1721 mHandler.post(r);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001722 }
1723
Amith Yamasani258848d2012-08-10 17:06:33 -07001724 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001725 * Check if we've hit the limit of how many users can be created.
1726 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001727 private boolean isUserLimitReached() {
1728 int count;
1729 synchronized (mUsersLock) {
1730 count = getAliveUsersExcludingGuestsCountLU();
1731 }
1732 return count >= UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001733 }
1734
1735 @Override
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001736 public boolean canAddMoreManagedProfiles(int userId, boolean allowedToRemoveOne) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001737 checkManageUsersPermission("check if more managed profiles can be added.");
1738 if (ActivityManager.isLowRamDeviceStatic()) {
1739 return false;
1740 }
Fyodor Kupolovb6157992015-06-05 15:32:28 -07001741 if (!mContext.getPackageManager().hasSystemFeature(
1742 PackageManager.FEATURE_MANAGED_USERS)) {
1743 return false;
1744 }
Nicolas Prevotb8186812015-08-06 15:00:03 +01001745 // Limit number of managed profiles that can be created
Benjamin Franzc8776152017-01-06 14:16:41 +00001746 final int managedProfilesCount = getProfiles(userId, false).size() - 1;
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001747 final int profilesRemovedCount = managedProfilesCount > 0 && allowedToRemoveOne ? 1 : 0;
Kenny Guy02c89902016-11-15 19:36:38 +00001748 if (managedProfilesCount - profilesRemovedCount >= getMaxManagedProfiles()) {
Nicolas Prevotb8186812015-08-06 15:00:03 +01001749 return false;
1750 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001751 synchronized(mUsersLock) {
1752 UserInfo userInfo = getUserInfoLU(userId);
yuanhao47f9f7c2017-01-18 09:54:45 +08001753 if (userInfo == null || !userInfo.canHaveProfile()) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001754 return false;
1755 }
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001756 int usersCountAfterRemoving = getAliveUsersExcludingGuestsCountLU()
1757 - profilesRemovedCount;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001758 // We allow creating a managed profile in the special case where there is only one user.
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001759 return usersCountAfterRemoving == 1
1760 || usersCountAfterRemoving < UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001761 }
1762 }
1763
Fyodor Kupolov82402752015-10-28 14:54:51 -07001764 private int getAliveUsersExcludingGuestsCountLU() {
Amith Yamasanif584f012014-05-19 17:57:25 -07001765 int aliveUserCount = 0;
1766 final int totalUserCount = mUsers.size();
1767 // Skip over users being removed
1768 for (int i = 0; i < totalUserCount; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001769 UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov6e99d3f2016-11-01 17:18:41 -07001770 if (!mRemovingUserIds.get(user.id) && !user.isGuest()) {
Amith Yamasanif584f012014-05-19 17:57:25 -07001771 aliveUserCount++;
1772 }
1773 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001774 return aliveUserCount;
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001775 }
1776
1777 /**
Amith Yamasani195263742012-08-21 15:40:12 -07001778 * Enforces that only the system UID or root's UID or apps that have the
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001779 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} and
1780 * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL INTERACT_ACROSS_USERS_FULL}
1781 * permissions can make certain calls to the UserManager.
1782 *
1783 * @param message used as message if SecurityException is thrown
1784 * @throws SecurityException if the caller does not have enough privilege.
1785 */
1786 private static final void checkManageUserAndAcrossUsersFullPermission(String message) {
1787 final int uid = Binder.getCallingUid();
1788 if (uid != Process.SYSTEM_UID && uid != 0
1789 && ActivityManager.checkComponentPermission(
1790 Manifest.permission.MANAGE_USERS,
1791 uid, -1, true) != PackageManager.PERMISSION_GRANTED
1792 && ActivityManager.checkComponentPermission(
1793 Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1794 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
1795 throw new SecurityException(
1796 "You need MANAGE_USERS and INTERACT_ACROSS_USERS_FULL permission to: "
1797 + message);
1798 }
1799 }
1800
1801 /**
1802 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001803 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -07001804 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -07001805 *
1806 * @param message used as message if SecurityException is thrown
1807 * @throws SecurityException if the caller is not system or root
Tony Mak4dc008c2016-03-16 10:46:49 +00001808 * @see #hasManageUsersPermission()
Amith Yamasani258848d2012-08-10 17:06:33 -07001809 */
Amith Yamasanibe465322014-04-24 13:45:17 -07001810 private static final void checkManageUsersPermission(String message) {
Tony Mak4dc008c2016-03-16 10:46:49 +00001811 if (!hasManageUsersPermission()) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001812 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
1813 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -04001814 }
1815
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001816 /**
Sudheer Shankaf5cea032016-06-08 17:13:24 -07001817 * Enforces that only the system UID or root's UID or apps that have the
1818 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or
1819 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS}
1820 * can make certain calls to the UserManager.
1821 *
1822 * @param message used as message if SecurityException is thrown
1823 * @throws SecurityException if the caller is not system or root
1824 * @see #hasManageOrCreateUsersPermission()
1825 */
1826 private static final void checkManageOrCreateUsersPermission(String message) {
1827 if (!hasManageOrCreateUsersPermission()) {
1828 throw new SecurityException(
1829 "You either need MANAGE_USERS or CREATE_USERS permission to: " + message);
1830 }
1831 }
1832
1833 /**
1834 * Similar to {@link #checkManageOrCreateUsersPermission(String)} but when the caller is tries
1835 * to create user/profiles other than what is allowed for
1836 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS} permission, then it will only
1837 * allow callers with {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} permission.
1838 */
1839 private static final void checkManageOrCreateUsersPermission(int creationFlags) {
1840 if ((creationFlags & ~ALLOWED_FLAGS_FOR_CREATE_USERS_PERMISSION) == 0) {
1841 if (!hasManageOrCreateUsersPermission()) {
1842 throw new SecurityException("You either need MANAGE_USERS or CREATE_USERS "
1843 + "permission to create an user with flags: " + creationFlags);
1844 }
1845 } else if (!hasManageUsersPermission()) {
1846 throw new SecurityException("You need MANAGE_USERS permission to create an user "
1847 + " with flags: " + creationFlags);
1848 }
1849 }
1850
1851 /**
Tony Mak4dc008c2016-03-16 10:46:49 +00001852 * @return whether the calling UID is system UID or root's UID or the calling app has the
1853 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}.
1854 */
1855 private static final boolean hasManageUsersPermission() {
1856 final int callingUid = Binder.getCallingUid();
1857 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
1858 || callingUid == Process.ROOT_UID
1859 || ActivityManager.checkComponentPermission(
1860 android.Manifest.permission.MANAGE_USERS,
1861 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED;
1862 }
1863
1864 /**
Sudheer Shankaf5cea032016-06-08 17:13:24 -07001865 * @return whether the calling UID is system UID or root's UID or the calling app has the
1866 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or
1867 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS}.
1868 */
1869 private static final boolean hasManageOrCreateUsersPermission() {
1870 final int callingUid = Binder.getCallingUid();
1871 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
1872 || callingUid == Process.ROOT_UID
1873 || ActivityManager.checkComponentPermission(
1874 android.Manifest.permission.MANAGE_USERS,
1875 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED
1876 || ActivityManager.checkComponentPermission(
1877 android.Manifest.permission.CREATE_USERS,
1878 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED;
1879 }
1880
1881 /**
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001882 * Enforces that only the system UID or root's UID (on any user) can make certain calls to the
1883 * UserManager.
1884 *
1885 * @param message used as message if SecurityException is thrown
1886 * @throws SecurityException if the caller is not system or root
1887 */
1888 private static void checkSystemOrRoot(String message) {
1889 final int uid = Binder.getCallingUid();
1890 if (!UserHandle.isSameApp(uid, Process.SYSTEM_UID) && uid != Process.ROOT_UID) {
1891 throw new SecurityException("Only system may: " + message);
1892 }
1893 }
1894
Fyodor Kupolov82402752015-10-28 14:54:51 -07001895 private void writeBitmapLP(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001896 try {
1897 File dir = new File(mUsersDir, Integer.toString(info.id));
1898 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +01001899 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001900 if (!dir.exists()) {
1901 dir.mkdir();
1902 FileUtils.setPermissions(
1903 dir.getPath(),
1904 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
1905 -1, -1);
1906 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001907 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +01001908 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001909 && tmp.renameTo(file) && SELinux.restorecon(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -07001910 info.iconPath = file.getAbsolutePath();
1911 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001912 try {
1913 os.close();
1914 } catch (IOException ioe) {
1915 // What the ... !
1916 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001917 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001918 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001919 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001920 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001921 }
1922
Amith Yamasani0b285492011-04-14 17:35:23 -07001923 /**
1924 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
1925 * cache it elsewhere.
1926 * @return the array of user ids.
1927 */
Dianne Hackborn1676c852012-09-10 14:52:30 -07001928 public int[] getUserIds() {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001929 synchronized (mUsersLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001930 return mUserIds;
1931 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001932 }
1933
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001934 private void readUserListLP() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001935 if (!mUserListFile.exists()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001936 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001937 return;
1938 }
1939 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001940 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001941 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001942 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001943 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001944 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001945 int type;
1946 while ((type = parser.next()) != XmlPullParser.START_TAG
1947 && type != XmlPullParser.END_DOCUMENT) {
Amith Yamasani12747872015-12-07 14:19:49 -08001948 // Skip
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001949 }
1950
1951 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001952 Slog.e(LOG_TAG, "Unable to read user list");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001953 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001954 return;
1955 }
1956
Amith Yamasani2a003292012-08-14 18:25:45 -07001957 mNextSerialNumber = -1;
1958 if (parser.getName().equals(TAG_USERS)) {
1959 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
1960 if (lastSerialNumber != null) {
1961 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
1962 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001963 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
1964 if (versionNumber != null) {
1965 mUserVersion = Integer.parseInt(versionNumber);
1966 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001967 }
1968
Pavel Grafov6a40f092016-10-25 15:46:51 +01001969 // Pre-O global user restriction were stored as a single bundle (as opposed to per-user
1970 // currently), take care of it in case of upgrade.
1971 Bundle oldDevicePolicyGlobalUserRestrictions = null;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001972
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001973 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301974 if (type == XmlPullParser.START_TAG) {
1975 final String name = parser.getName();
1976 if (name.equals(TAG_USER)) {
1977 String id = parser.getAttributeValue(null, ATTR_ID);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001978
Amith Yamasani12747872015-12-07 14:19:49 -08001979 UserData userData = readUserLP(Integer.parseInt(id));
1980
1981 if (userData != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001982 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001983 mUsers.put(userData.info.id, userData);
1984 if (mNextSerialNumber < 0
1985 || mNextSerialNumber <= userData.info.id) {
1986 mNextSerialNumber = userData.info.id + 1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001987 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301988 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001989 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301990 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -08001991 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1992 && type != XmlPullParser.END_TAG) {
1993 if (type == XmlPullParser.START_TAG) {
1994 if (parser.getName().equals(TAG_RESTRICTIONS)) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001995 synchronized (mGuestRestrictions) {
Fyodor Kupoloveafee022017-03-15 17:09:04 -07001996 UserRestrictionsUtils
1997 .readRestrictions(parser, mGuestRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001998 }
Amith Yamasanida0b1682014-11-21 12:58:17 -08001999 }
2000 break;
2001 }
2002 }
Pavel Grafov6a40f092016-10-25 15:46:51 +01002003 } else if (name.equals(TAG_DEVICE_OWNER_USER_ID)
2004 // Legacy name, should only be encountered when upgrading from pre-O.
2005 || name.equals(TAG_GLOBAL_RESTRICTION_OWNER_ID)) {
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01002006 String ownerUserId = parser.getAttributeValue(null, ATTR_ID);
2007 if (ownerUserId != null) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01002008 mDeviceOwnerUserId = Integer.parseInt(ownerUserId);
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01002009 }
Pavel Grafov6a40f092016-10-25 15:46:51 +01002010 } else if (name.equals(TAG_DEVICE_POLICY_RESTRICTIONS)) {
2011 // Should only happen when upgrading from pre-O (version < 7).
2012 oldDevicePolicyGlobalUserRestrictions =
2013 UserRestrictionsUtils.readRestrictions(parser);
Amith Yamasani258848d2012-08-10 17:06:33 -07002014 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002015 }
2016 }
Pavel Grafov6a40f092016-10-25 15:46:51 +01002017
Fyodor Kupolov82402752015-10-28 14:54:51 -07002018 updateUserIds();
Pavel Grafov6a40f092016-10-25 15:46:51 +01002019 upgradeIfNecessaryLP(oldDevicePolicyGlobalUserRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002020 } catch (IOException | XmlPullParserException e) {
2021 fallbackToSingleUserLP();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08002022 } finally {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002023 IoUtils.closeQuietly(fis);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002024 }
2025 }
2026
Amith Yamasani6f34b412012-10-22 18:19:27 -07002027 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -08002028 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Pavel Grafov6a40f092016-10-25 15:46:51 +01002029 * @param oldGlobalUserRestrictions Pre-O global device policy restrictions.
Amith Yamasani6f34b412012-10-22 18:19:27 -07002030 */
Pavel Grafov6a40f092016-10-25 15:46:51 +01002031 private void upgradeIfNecessaryLP(Bundle oldGlobalUserRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002032 final int originalVersion = mUserVersion;
Amith Yamasani6f34b412012-10-22 18:19:27 -07002033 int userVersion = mUserVersion;
2034 if (userVersion < 1) {
2035 // Assign a proper name for the owner, if not initialized correctly before
Amith Yamasani12747872015-12-07 14:19:49 -08002036 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
2037 if ("Primary".equals(userData.info.name)) {
2038 userData.info.name =
2039 mContext.getResources().getString(com.android.internal.R.string.owner_name);
2040 scheduleWriteUser(userData);
Amith Yamasani6f34b412012-10-22 18:19:27 -07002041 }
2042 userVersion = 1;
2043 }
2044
Amith Yamasanibc9625052012-11-15 14:39:18 -08002045 if (userVersion < 2) {
2046 // Owner should be marked as initialized
Amith Yamasani12747872015-12-07 14:19:49 -08002047 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
2048 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
2049 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
2050 scheduleWriteUser(userData);
Amith Yamasanibc9625052012-11-15 14:39:18 -08002051 }
2052 userVersion = 2;
2053 }
2054
Amith Yamasani350962c2013-08-06 11:18:53 -07002055
Amith Yamasani5e486f52013-08-07 11:06:44 -07002056 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -07002057 userVersion = 4;
2058 }
2059
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07002060 if (userVersion < 5) {
2061 initDefaultGuestRestrictions();
2062 userVersion = 5;
2063 }
2064
Fyodor Kupolov1c363152015-09-02 13:27:21 -07002065 if (userVersion < 6) {
2066 final boolean splitSystemUser = UserManager.isSplitSystemUser();
Fyodor Kupolov82402752015-10-28 14:54:51 -07002067 synchronized (mUsersLock) {
2068 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002069 UserData userData = mUsers.valueAt(i);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002070 // In non-split mode, only user 0 can have restricted profiles
Amith Yamasani12747872015-12-07 14:19:49 -08002071 if (!splitSystemUser && userData.info.isRestricted()
2072 && (userData.info.restrictedProfileParentId
2073 == UserInfo.NO_PROFILE_GROUP_ID)) {
2074 userData.info.restrictedProfileParentId = UserHandle.USER_SYSTEM;
2075 scheduleWriteUser(userData);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002076 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07002077 }
2078 }
2079 userVersion = 6;
2080 }
2081
Pavel Grafov6a40f092016-10-25 15:46:51 +01002082 if (userVersion < 7) {
2083 // Previously only one user could enforce global restrictions, now it is per-user.
2084 synchronized (mRestrictionsLock) {
2085 if (!UserRestrictionsUtils.isEmpty(oldGlobalUserRestrictions)
2086 && mDeviceOwnerUserId != UserHandle.USER_NULL) {
2087 mDevicePolicyGlobalUserRestrictions.put(
2088 mDeviceOwnerUserId, oldGlobalUserRestrictions);
2089 }
2090 // ENSURE_VERIFY_APPS is now enforced globally even if put by profile owner, so move
2091 // it from local to global bundle for all users who set it.
2092 UserRestrictionsUtils.moveRestriction(UserManager.ENSURE_VERIFY_APPS,
2093 mDevicePolicyLocalUserRestrictions, mDevicePolicyGlobalUserRestrictions
2094 );
2095 }
2096 userVersion = 7;
2097 }
2098
Amith Yamasani6f34b412012-10-22 18:19:27 -07002099 if (userVersion < USER_VERSION) {
2100 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
2101 + USER_VERSION);
2102 } else {
2103 mUserVersion = userVersion;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002104
2105 if (originalVersion < mUserVersion) {
2106 writeUserListLP();
2107 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07002108 }
2109 }
2110
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002111 private void fallbackToSingleUserLP() {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07002112 int flags = UserInfo.FLAG_INITIALIZED;
2113 // In split system user mode, the admin and primary flags are assigned to the first human
2114 // user.
2115 if (!UserManager.isSplitSystemUser()) {
2116 flags |= UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY;
2117 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -07002118 // Create the system user
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07002119 UserInfo system = new UserInfo(UserHandle.USER_SYSTEM, null, null, flags);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002120 UserData userData = putUserInfo(system);
Amith Yamasani634cf312012-10-04 17:34:21 -07002121 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -04002122 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -08002123
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05002124 Bundle restrictions = new Bundle();
Mahaver Chopra3d9805d2016-07-07 16:25:05 +01002125 try {
2126 final String[] defaultFirstUserRestrictions = mContext.getResources().getStringArray(
2127 com.android.internal.R.array.config_defaultFirstUserRestrictions);
2128 for (String userRestriction : defaultFirstUserRestrictions) {
2129 if (UserRestrictionsUtils.isValidRestriction(userRestriction)) {
2130 restrictions.putBoolean(userRestriction, true);
2131 }
2132 }
2133 } catch (Resources.NotFoundException e) {
2134 Log.e(LOG_TAG, "Couldn't find resource: config_defaultFirstUserRestrictions", e);
2135 }
2136
Pavel Grafov6a40f092016-10-25 15:46:51 +01002137 if (!restrictions.isEmpty()) {
2138 synchronized (mRestrictionsLock) {
2139 mBaseUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions);
2140 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07002141 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08002142
Fyodor Kupolov82402752015-10-28 14:54:51 -07002143 updateUserIds();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07002144 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002145
Amith Yamasani12747872015-12-07 14:19:49 -08002146 writeUserLP(userData);
Jeff Sharkeycd575992016-03-29 14:12:49 -06002147 writeUserListLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002148 }
2149
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07002150 private String getOwnerName() {
2151 return mContext.getResources().getString(com.android.internal.R.string.owner_name);
2152 }
2153
Amith Yamasani12747872015-12-07 14:19:49 -08002154 private void scheduleWriteUser(UserData UserData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002155 if (DBG) {
2156 debug("scheduleWriteUser");
2157 }
Makoto Onuki9e935a32015-11-06 14:24:24 -08002158 // No need to wrap it within a lock -- worst case, we'll just post the same message
2159 // twice.
Amith Yamasani12747872015-12-07 14:19:49 -08002160 if (!mHandler.hasMessages(WRITE_USER_MSG, UserData)) {
2161 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, UserData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002162 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
2163 }
2164 }
2165
Amith Yamasani12747872015-12-07 14:19:49 -08002166 private void writeUserLP(UserData userData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002167 if (DBG) {
Amith Yamasani12747872015-12-07 14:19:49 -08002168 debug("writeUserLP " + userData);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002169 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002170 FileOutputStream fos = null;
Amith Yamasani12747872015-12-07 14:19:49 -08002171 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userData.info.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002172 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07002173 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002174 final BufferedOutputStream bos = new BufferedOutputStream(fos);
Kenny Guy02c89902016-11-15 19:36:38 +00002175 writeUserLP(userData, bos);
Amith Yamasani2a003292012-08-14 18:25:45 -07002176 userFile.finishWrite(fos);
2177 } catch (Exception ioe) {
Jeff Sharkeycd575992016-03-29 14:12:49 -06002178 Slog.e(LOG_TAG, "Error writing user info " + userData.info.id, ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -07002179 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002180 }
2181 }
2182
2183 /*
Kenny Guy02c89902016-11-15 19:36:38 +00002184 * Writes the user file in this format:
2185 *
2186 * <user flags="20039023" id="0">
2187 * <name>Primary</name>
2188 * </user>
2189 */
2190 @VisibleForTesting
2191 void writeUserLP(UserData userData, OutputStream os)
2192 throws IOException, XmlPullParserException {
2193 // XmlSerializer serializer = XmlUtils.serializerInstance();
2194 final XmlSerializer serializer = new FastXmlSerializer();
2195 serializer.setOutput(os, StandardCharsets.UTF_8.name());
2196 serializer.startDocument(null, true);
2197 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2198
2199 final UserInfo userInfo = userData.info;
2200 serializer.startTag(null, TAG_USER);
2201 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
2202 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
2203 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
2204 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
2205 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
2206 Long.toString(userInfo.lastLoggedInTime));
2207 if (userInfo.lastLoggedInFingerprint != null) {
2208 serializer.attribute(null, ATTR_LAST_LOGGED_IN_FINGERPRINT,
2209 userInfo.lastLoggedInFingerprint);
2210 }
2211 if (userInfo.iconPath != null) {
2212 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
2213 }
2214 if (userInfo.partial) {
2215 serializer.attribute(null, ATTR_PARTIAL, "true");
2216 }
2217 if (userInfo.guestToRemove) {
2218 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
2219 }
2220 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
2221 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
2222 Integer.toString(userInfo.profileGroupId));
2223 }
2224 serializer.attribute(null, ATTR_PROFILE_BADGE,
2225 Integer.toString(userInfo.profileBadge));
2226 if (userInfo.restrictedProfileParentId != UserInfo.NO_PROFILE_GROUP_ID) {
2227 serializer.attribute(null, ATTR_RESTRICTED_PROFILE_PARENT_ID,
2228 Integer.toString(userInfo.restrictedProfileParentId));
2229 }
2230 // Write seed data
2231 if (userData.persistSeedData) {
2232 if (userData.seedAccountName != null) {
2233 serializer.attribute(null, ATTR_SEED_ACCOUNT_NAME, userData.seedAccountName);
2234 }
2235 if (userData.seedAccountType != null) {
2236 serializer.attribute(null, ATTR_SEED_ACCOUNT_TYPE, userData.seedAccountType);
2237 }
2238 }
2239 if (userInfo.name != null) {
2240 serializer.startTag(null, TAG_NAME);
2241 serializer.text(userInfo.name);
2242 serializer.endTag(null, TAG_NAME);
2243 }
2244 synchronized (mRestrictionsLock) {
2245 UserRestrictionsUtils.writeRestrictions(serializer,
2246 mBaseUserRestrictions.get(userInfo.id), TAG_RESTRICTIONS);
2247 UserRestrictionsUtils.writeRestrictions(serializer,
2248 mDevicePolicyLocalUserRestrictions.get(userInfo.id),
2249 TAG_DEVICE_POLICY_RESTRICTIONS);
Pavel Grafov6a40f092016-10-25 15:46:51 +01002250 UserRestrictionsUtils.writeRestrictions(serializer,
2251 mDevicePolicyGlobalUserRestrictions.get(userInfo.id),
2252 TAG_DEVICE_POLICY_GLOBAL_RESTRICTIONS);
Kenny Guy02c89902016-11-15 19:36:38 +00002253 }
2254
2255 if (userData.account != null) {
2256 serializer.startTag(null, TAG_ACCOUNT);
2257 serializer.text(userData.account);
2258 serializer.endTag(null, TAG_ACCOUNT);
2259 }
2260
2261 if (userData.persistSeedData && userData.seedAccountOptions != null) {
2262 serializer.startTag(null, TAG_SEED_ACCOUNT_OPTIONS);
2263 userData.seedAccountOptions.saveToXml(serializer);
2264 serializer.endTag(null, TAG_SEED_ACCOUNT_OPTIONS);
2265 }
2266
2267 serializer.endTag(null, TAG_USER);
2268
2269 serializer.endDocument();
2270 }
2271
2272 /*
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002273 * Writes the user list file in this format:
2274 *
Amith Yamasani2a003292012-08-14 18:25:45 -07002275 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002276 * <user id="0"></user>
2277 * <user id="2"></user>
2278 * </users>
2279 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002280 private void writeUserListLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002281 if (DBG) {
2282 debug("writeUserList");
2283 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002284 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07002285 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002286 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07002287 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002288 final BufferedOutputStream bos = new BufferedOutputStream(fos);
2289
2290 // XmlSerializer serializer = XmlUtils.serializerInstance();
2291 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002292 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002293 serializer.startDocument(null, true);
2294 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2295
2296 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -07002297 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -07002298 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002299
Adam Lesinskieddeb492014-09-08 17:50:03 -07002300 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002301 synchronized (mGuestRestrictions) {
2302 UserRestrictionsUtils
2303 .writeRestrictions(serializer, mGuestRestrictions, TAG_RESTRICTIONS);
2304 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05302305 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Pavel Grafov6a40f092016-10-25 15:46:51 +01002306 serializer.startTag(null, TAG_DEVICE_OWNER_USER_ID);
2307 serializer.attribute(null, ATTR_ID, Integer.toString(mDeviceOwnerUserId));
2308 serializer.endTag(null, TAG_DEVICE_OWNER_USER_ID);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002309 int[] userIdsToWrite;
2310 synchronized (mUsersLock) {
2311 userIdsToWrite = new int[mUsers.size()];
2312 for (int i = 0; i < userIdsToWrite.length; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002313 UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002314 userIdsToWrite[i] = user.id;
2315 }
2316 }
2317 for (int id : userIdsToWrite) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002318 serializer.startTag(null, TAG_USER);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002319 serializer.attribute(null, ATTR_ID, Integer.toString(id));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002320 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002321 }
2322
2323 serializer.endTag(null, TAG_USERS);
2324
2325 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07002326 userListFile.finishWrite(fos);
2327 } catch (Exception e) {
2328 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -07002329 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002330 }
2331 }
2332
Amith Yamasani12747872015-12-07 14:19:49 -08002333 private UserData readUserLP(int id) {
Kenny Guy02c89902016-11-15 19:36:38 +00002334 FileInputStream fis = null;
2335 try {
2336 AtomicFile userFile =
2337 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
2338 fis = userFile.openRead();
2339 return readUserLP(id, fis);
2340 } catch (IOException ioe) {
2341 Slog.e(LOG_TAG, "Error reading user list");
2342 } catch (XmlPullParserException pe) {
2343 Slog.e(LOG_TAG, "Error reading user list");
2344 } finally {
2345 IoUtils.closeQuietly(fis);
2346 }
2347 return null;
2348 }
2349
2350 @VisibleForTesting
2351 UserData readUserLP(int id, InputStream is) throws IOException,
2352 XmlPullParserException {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002353 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -07002354 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002355 String name = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -08002356 String account = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002357 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -07002358 long creationTime = 0L;
2359 long lastLoggedInTime = 0L;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002360 String lastLoggedInFingerprint = null;
Kenny Guy2a764942014-04-02 13:29:20 +01002361 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Kenny Guy02c89902016-11-15 19:36:38 +00002362 int profileBadge = 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002363 int restrictedProfileParentId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002364 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -07002365 boolean guestToRemove = false;
Amith Yamasani12747872015-12-07 14:19:49 -08002366 boolean persistSeedData = false;
2367 String seedAccountName = null;
2368 String seedAccountType = null;
2369 PersistableBundle seedAccountOptions = null;
Pavel Grafov6a40f092016-10-25 15:46:51 +01002370 Bundle baseRestrictions = null;
2371 Bundle localRestrictions = null;
2372 Bundle globalRestrictions = null;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002373
Kenny Guy02c89902016-11-15 19:36:38 +00002374 XmlPullParser parser = Xml.newPullParser();
2375 parser.setInput(is, StandardCharsets.UTF_8.name());
2376 int type;
2377 while ((type = parser.next()) != XmlPullParser.START_TAG
2378 && type != XmlPullParser.END_DOCUMENT) {
2379 // Skip
2380 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002381
Kenny Guy02c89902016-11-15 19:36:38 +00002382 if (type != XmlPullParser.START_TAG) {
2383 Slog.e(LOG_TAG, "Unable to read user " + id);
2384 return null;
2385 }
2386
2387 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
2388 int storedId = readIntAttribute(parser, ATTR_ID, -1);
2389 if (storedId != id) {
2390 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002391 return null;
2392 }
Kenny Guy02c89902016-11-15 19:36:38 +00002393 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
2394 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
2395 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
2396 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
2397 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
2398 lastLoggedInFingerprint = parser.getAttributeValue(null,
2399 ATTR_LAST_LOGGED_IN_FINGERPRINT);
2400 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
2401 UserInfo.NO_PROFILE_GROUP_ID);
2402 profileBadge = readIntAttribute(parser, ATTR_PROFILE_BADGE, 0);
2403 restrictedProfileParentId = readIntAttribute(parser,
2404 ATTR_RESTRICTED_PROFILE_PARENT_ID, UserInfo.NO_PROFILE_GROUP_ID);
2405 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
2406 if ("true".equals(valueString)) {
2407 partial = true;
2408 }
2409 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
2410 if ("true".equals(valueString)) {
2411 guestToRemove = true;
2412 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002413
Kenny Guy02c89902016-11-15 19:36:38 +00002414 seedAccountName = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_NAME);
2415 seedAccountType = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_TYPE);
2416 if (seedAccountName != null || seedAccountType != null) {
2417 persistSeedData = true;
2418 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002419
Kenny Guy02c89902016-11-15 19:36:38 +00002420 int outerDepth = parser.getDepth();
2421 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2422 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2423 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2424 continue;
2425 }
2426 String tag = parser.getName();
2427 if (TAG_NAME.equals(tag)) {
2428 type = parser.next();
2429 if (type == XmlPullParser.TEXT) {
2430 name = parser.getText();
2431 }
2432 } else if (TAG_RESTRICTIONS.equals(tag)) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01002433 baseRestrictions = UserRestrictionsUtils.readRestrictions(parser);
Kenny Guy02c89902016-11-15 19:36:38 +00002434 } else if (TAG_DEVICE_POLICY_RESTRICTIONS.equals(tag)) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01002435 localRestrictions = UserRestrictionsUtils.readRestrictions(parser);
2436 } else if (TAG_DEVICE_POLICY_GLOBAL_RESTRICTIONS.equals(tag)) {
2437 globalRestrictions = UserRestrictionsUtils.readRestrictions(parser);
Kenny Guy02c89902016-11-15 19:36:38 +00002438 } else if (TAG_ACCOUNT.equals(tag)) {
2439 type = parser.next();
2440 if (type == XmlPullParser.TEXT) {
2441 account = parser.getText();
2442 }
2443 } else if (TAG_SEED_ACCOUNT_OPTIONS.equals(tag)) {
2444 seedAccountOptions = PersistableBundle.restoreFromXml(parser);
Amith Yamasani12747872015-12-07 14:19:49 -08002445 persistSeedData = true;
2446 }
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08002447 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002448 }
Kenny Guy02c89902016-11-15 19:36:38 +00002449
2450 // Create the UserInfo object that gets passed around
2451 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
2452 userInfo.serialNumber = serialNumber;
2453 userInfo.creationTime = creationTime;
2454 userInfo.lastLoggedInTime = lastLoggedInTime;
2455 userInfo.lastLoggedInFingerprint = lastLoggedInFingerprint;
2456 userInfo.partial = partial;
2457 userInfo.guestToRemove = guestToRemove;
2458 userInfo.profileGroupId = profileGroupId;
2459 userInfo.profileBadge = profileBadge;
2460 userInfo.restrictedProfileParentId = restrictedProfileParentId;
2461
2462 // Create the UserData object that's internal to this class
2463 UserData userData = new UserData();
2464 userData.info = userInfo;
2465 userData.account = account;
2466 userData.seedAccountName = seedAccountName;
2467 userData.seedAccountType = seedAccountType;
2468 userData.persistSeedData = persistSeedData;
2469 userData.seedAccountOptions = seedAccountOptions;
2470
2471 synchronized (mRestrictionsLock) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01002472 if (baseRestrictions != null) {
2473 mBaseUserRestrictions.put(id, baseRestrictions);
2474 }
2475 if (localRestrictions != null) {
2476 mDevicePolicyLocalUserRestrictions.put(id, localRestrictions);
2477 }
2478 if (globalRestrictions != null) {
2479 mDevicePolicyGlobalUserRestrictions.put(id, globalRestrictions);
2480 }
Kenny Guy02c89902016-11-15 19:36:38 +00002481 }
2482 return userData;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002483 }
2484
Amith Yamasani920ace02012-09-20 22:15:37 -07002485 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
2486 String valueString = parser.getAttributeValue(null, attr);
2487 if (valueString == null) return defaultValue;
2488 try {
2489 return Integer.parseInt(valueString);
2490 } catch (NumberFormatException nfe) {
2491 return defaultValue;
2492 }
2493 }
2494
2495 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
2496 String valueString = parser.getAttributeValue(null, attr);
2497 if (valueString == null) return defaultValue;
2498 try {
2499 return Long.parseLong(valueString);
2500 } catch (NumberFormatException nfe) {
2501 return defaultValue;
2502 }
2503 }
2504
Amith Yamasanib82add22013-07-09 11:24:44 -07002505 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002506 * Removes the app restrictions file for a specific package and user id, if it exists.
2507 */
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07002508 private static void cleanAppRestrictionsForPackageLAr(String pkg, int userId) {
2509 File dir = Environment.getUserSystemDirectory(userId);
2510 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
2511 if (resFile.exists()) {
2512 resFile.delete();
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002513 }
2514 }
2515
Kenny Guya52dc3e2014-02-11 15:33:14 +00002516 @Override
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002517 public UserInfo createProfileForUser(String name, int flags, int userId,
2518 String[] disallowedPackages) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002519 checkManageOrCreateUsersPermission(flags);
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002520 return createUserInternal(name, flags, userId, disallowedPackages);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002521 }
2522
Amith Yamasani258848d2012-08-10 17:06:33 -07002523 @Override
Tony Mak6dc428f2016-10-10 15:48:27 +01002524 public UserInfo createProfileForUserEvenWhenDisallowed(String name, int flags, int userId,
2525 String[] disallowedPackages) {
2526 checkManageOrCreateUsersPermission(flags);
2527 return createUserInternalUnchecked(name, flags, userId, disallowedPackages);
2528 }
2529
2530 @Override
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00002531 public boolean removeUserEvenWhenDisallowed(@UserIdInt int userHandle) {
2532 checkManageOrCreateUsersPermission("Only the system can remove users");
2533 return removeUserUnchecked(userHandle);
2534 }
2535
2536 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07002537 public UserInfo createUser(String name, int flags) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002538 checkManageOrCreateUsersPermission(flags);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00002539 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002540 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07002541
Jessica Hummelbe81c802014-04-22 15:49:22 +01002542 private UserInfo createUserInternal(String name, int flags, int parentId) {
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002543 return createUserInternal(name, flags, parentId, null);
2544 }
2545
2546 private UserInfo createUserInternal(String name, int flags, int parentId,
2547 String[] disallowedPackages) {
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002548 String restriction = ((flags & UserInfo.FLAG_MANAGED_PROFILE) != 0)
2549 ? UserManager.DISALLOW_ADD_MANAGED_PROFILE
2550 : UserManager.DISALLOW_ADD_USER;
2551 if (hasUserRestriction(restriction, UserHandle.getCallingUserId())) {
2552 Log.w(LOG_TAG, "Cannot add user. " + restriction + " is enabled.");
Julia Reynolds75175022014-06-26 16:35:00 -04002553 return null;
2554 }
Tony Mak6dc428f2016-10-10 15:48:27 +01002555 return createUserInternalUnchecked(name, flags, parentId, disallowedPackages);
2556 }
2557
2558 private UserInfo createUserInternalUnchecked(String name, int flags, int parentId,
2559 String[] disallowedPackages) {
Suprabh Shuklac5e057c2016-08-08 16:22:44 -07002560 DeviceStorageMonitorInternal dsm = LocalServices
2561 .getService(DeviceStorageMonitorInternal.class);
2562 if (dsm.isMemoryLow()) {
2563 Log.w(LOG_TAG, "Cannot add user. Not enough space on disk.");
2564 return null;
2565 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07002566 if (ActivityManager.isLowRamDeviceStatic()) {
2567 return null;
2568 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07002569 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Nicolas Prevot12678a92015-05-13 12:15:03 -07002570 final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002571 final boolean isRestricted = (flags & UserInfo.FLAG_RESTRICTED) != 0;
Amith Yamasani52c21e32016-05-31 09:12:20 -07002572 final boolean isDemo = (flags & UserInfo.FLAG_DEMO) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002573 final long ident = Binder.clearCallingIdentity();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002574 UserInfo userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08002575 UserData userData;
Amith Yamasanibb054c92015-07-09 14:16:27 -07002576 final int userId;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002577 try {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002578 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002579 UserData parent = null;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002580 if (parentId != UserHandle.USER_NULL) {
2581 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002582 parent = getUserDataLU(parentId);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00002583 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002584 if (parent == null) return null;
2585 }
2586 if (isManagedProfile && !canAddMoreManagedProfiles(parentId, false)) {
2587 Log.e(LOG_TAG, "Cannot add more managed profiles for user " + parentId);
2588 return null;
2589 }
Amith Yamasani52c21e32016-05-31 09:12:20 -07002590 if (!isGuest && !isManagedProfile && !isDemo && isUserLimitReached()) {
2591 // If we're not adding a guest/demo user or a managed profile and the limit has
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002592 // been reached, cannot add a user.
2593 return null;
2594 }
2595 // If we're adding a guest and there already exists one, bail.
2596 if (isGuest && findCurrentGuestUser() != null) {
2597 return null;
2598 }
2599 // In legacy mode, restricted profile's parent can only be the owner user
2600 if (isRestricted && !UserManager.isSplitSystemUser()
2601 && (parentId != UserHandle.USER_SYSTEM)) {
2602 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
2603 return null;
2604 }
2605 if (isRestricted && UserManager.isSplitSystemUser()) {
2606 if (parent == null) {
2607 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be "
2608 + "specified");
Nicolas Prevot12678a92015-05-13 12:15:03 -07002609 return null;
2610 }
Amith Yamasani12747872015-12-07 14:19:49 -08002611 if (!parent.info.canHaveProfile()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002612 Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be "
2613 + "created for the specified parent user id " + parentId);
Amith Yamasani95ab7842014-08-11 17:09:26 -07002614 return null;
2615 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002616 }
2617 // In split system user mode, we assign the first human user the primary flag.
2618 // And if there is no device owner, we also assign the admin flag to primary user.
2619 if (UserManager.isSplitSystemUser()
2620 && !isGuest && !isManagedProfile && getPrimaryUser() == null) {
2621 flags |= UserInfo.FLAG_PRIMARY;
Makoto Onukie7927da2015-11-25 10:05:17 -08002622 synchronized (mUsersLock) {
2623 if (!mIsDeviceManaged) {
2624 flags |= UserInfo.FLAG_ADMIN;
2625 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07002626 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002627 }
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002628
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002629 userId = getNextAvailableId();
2630 Environment.getUserSystemDirectory(userId).mkdirs();
Lenka Trochtova02fee152015-12-22 14:26:18 +01002631 boolean ephemeralGuests = Resources.getSystem()
2632 .getBoolean(com.android.internal.R.bool.config_guestUserEphemeral);
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002633
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002634 synchronized (mUsersLock) {
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002635 // Add ephemeral flag to guests/users if required. Also inherit it from parent.
2636 if ((isGuest && ephemeralGuests) || mForceEphemeralUsers
2637 || (parent != null && parent.info.isEphemeral())) {
2638 flags |= UserInfo.FLAG_EPHEMERAL;
2639 }
2640
2641 userInfo = new UserInfo(userId, name, null, flags);
2642 userInfo.serialNumber = mNextSerialNumber++;
2643 long now = System.currentTimeMillis();
2644 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
2645 userInfo.partial = true;
Fyodor Kupolov83c24242016-03-31 13:30:42 -07002646 userInfo.lastLoggedInFingerprint = Build.FINGERPRINT;
Kenny Guy02c89902016-11-15 19:36:38 +00002647 if (isManagedProfile && parentId != UserHandle.USER_NULL) {
2648 userInfo.profileBadge = getFreeProfileBadgeLU(parentId);
2649 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002650 userData = new UserData();
2651 userData.info = userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08002652 mUsers.put(userId, userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002653 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06002654 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002655 writeUserListLP();
2656 if (parent != null) {
2657 if (isManagedProfile) {
Amith Yamasani12747872015-12-07 14:19:49 -08002658 if (parent.info.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
2659 parent.info.profileGroupId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002660 writeUserLP(parent);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002661 }
Amith Yamasani12747872015-12-07 14:19:49 -08002662 userInfo.profileGroupId = parent.info.profileGroupId;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002663 } else if (isRestricted) {
Amith Yamasani12747872015-12-07 14:19:49 -08002664 if (parent.info.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) {
2665 parent.info.restrictedProfileParentId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002666 writeUserLP(parent);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002667 }
Amith Yamasani12747872015-12-07 14:19:49 -08002668 userInfo.restrictedProfileParentId = parent.info.restrictedProfileParentId;
Makoto Onuki068c54a2015-10-13 14:34:03 -07002669 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002670 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07002671 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002672 final StorageManager storage = mContext.getSystemService(StorageManager.class);
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002673 storage.createUserKey(userId, userInfo.serialNumber, userInfo.isEphemeral());
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -08002674 mUserDataPreparer.prepareUserData(userId, userInfo.serialNumber,
Jeff Sharkey47f71082016-02-01 17:03:54 -07002675 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002676 mPm.createNewUser(userId, disallowedPackages);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002677 userInfo.partial = false;
2678 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002679 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002680 }
2681 updateUserIds();
2682 Bundle restrictions = new Bundle();
Fyodor Kupolove04462c2015-11-30 15:02:53 -08002683 if (isGuest) {
2684 synchronized (mGuestRestrictions) {
2685 restrictions.putAll(mGuestRestrictions);
2686 }
2687 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002688 synchronized (mRestrictionsLock) {
2689 mBaseUserRestrictions.append(userId, restrictions);
2690 }
Fyodor Kupolov5fd967d2016-07-12 14:46:19 -07002691 mPm.onNewUserCreated(userId);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002692 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
2693 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
2694 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
2695 android.Manifest.permission.MANAGE_USERS);
Christine Franks88220562017-05-24 11:11:21 -07002696 MetricsLogger.count(mContext, isGuest ? TRON_GUEST_CREATED
2697 : (isDemo ? TRON_DEMO_CREATED : TRON_USER_CREATED), 1);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002698 } finally {
2699 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07002700 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002701 return userInfo;
2702 }
2703
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002704 @VisibleForTesting
2705 UserData putUserInfo(UserInfo userInfo) {
2706 final UserData userData = new UserData();
2707 userData.info = userInfo;
2708 synchronized (mUsers) {
2709 mUsers.put(userInfo.id, userData);
2710 }
2711 return userData;
2712 }
2713
2714 @VisibleForTesting
2715 void removeUserInfo(int userId) {
2716 synchronized (mUsers) {
2717 mUsers.remove(userId);
2718 }
2719 }
2720
Amith Yamasani0b285492011-04-14 17:35:23 -07002721 /**
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002722 * @hide
2723 */
Amith Yamasani12747872015-12-07 14:19:49 -08002724 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002725 public UserInfo createRestrictedProfile(String name, int parentUserId) {
Sudheer Shanka53d41472016-06-16 09:11:08 -07002726 checkManageOrCreateUsersPermission("setupRestrictedProfile");
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002727 final UserInfo user = createProfileForUser(
2728 name, UserInfo.FLAG_RESTRICTED, parentUserId, null);
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002729 if (user == null) {
2730 return null;
2731 }
Fyodor Kupolov9e912ba2016-02-09 18:29:43 -08002732 long identity = Binder.clearCallingIdentity();
2733 try {
2734 setUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, true, user.id);
2735 // Change the setting before applying the DISALLOW_SHARE_LOCATION restriction, otherwise
2736 // the putIntForUser() will fail.
2737 android.provider.Settings.Secure.putIntForUser(mContext.getContentResolver(),
2738 android.provider.Settings.Secure.LOCATION_MODE,
2739 android.provider.Settings.Secure.LOCATION_MODE_OFF, user.id);
2740 setUserRestriction(UserManager.DISALLOW_SHARE_LOCATION, true, user.id);
2741 } finally {
2742 Binder.restoreCallingIdentity(identity);
2743 }
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002744 return user;
2745 }
2746
2747 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07002748 * Find the current guest user. If the Guest user is partial,
2749 * then do not include it in the results as it is about to die.
Adam Lesinskieddeb492014-09-08 17:50:03 -07002750 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002751 private UserInfo findCurrentGuestUser() {
2752 synchronized (mUsersLock) {
2753 final int size = mUsers.size();
2754 for (int i = 0; i < size; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002755 final UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002756 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
2757 return user;
2758 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002759 }
2760 }
2761 return null;
2762 }
2763
2764 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07002765 * Mark this guest user for deletion to allow us to create another guest
2766 * and switch to that user before actually removing this guest.
2767 * @param userHandle the userid of the current guest
2768 * @return whether the user could be marked for deletion
2769 */
Amith Yamasani12747872015-12-07 14:19:49 -08002770 @Override
Amith Yamasani1df14732014-08-29 21:37:27 -07002771 public boolean markGuestForDeletion(int userHandle) {
2772 checkManageUsersPermission("Only the system can remove users");
2773 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
2774 UserManager.DISALLOW_REMOVE_USER, false)) {
2775 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
2776 return false;
2777 }
2778
2779 long ident = Binder.clearCallingIdentity();
2780 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002781 final UserData userData;
Amith Yamasani1df14732014-08-29 21:37:27 -07002782 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002783 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002784 userData = mUsers.get(userHandle);
2785 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002786 return false;
2787 }
Amith Yamasani1df14732014-08-29 21:37:27 -07002788 }
Amith Yamasani12747872015-12-07 14:19:49 -08002789 if (!userData.info.isGuest()) {
Amith Yamasani1df14732014-08-29 21:37:27 -07002790 return false;
2791 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002792 // We set this to a guest user that is to be removed. This is a temporary state
2793 // where we are allowed to add new Guest users, even if this one is still not
2794 // removed. This user will still show up in getUserInfo() calls.
2795 // If we don't get around to removing this Guest user, it will be purged on next
2796 // startup.
Amith Yamasani12747872015-12-07 14:19:49 -08002797 userData.info.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07002798 // Mark it as disabled, so that it isn't returned any more when
2799 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002800 userData.info.flags |= UserInfo.FLAG_DISABLED;
2801 writeUserLP(userData);
Amith Yamasani1df14732014-08-29 21:37:27 -07002802 }
2803 } finally {
2804 Binder.restoreCallingIdentity(ident);
2805 }
2806 return true;
2807 }
2808
2809 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002810 * Removes a user and all data directories created for that user. This method should be called
2811 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07002812 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07002813 */
Amith Yamasani12747872015-12-07 14:19:49 -08002814 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -07002815 public boolean removeUser(int userHandle) {
Fyodor Kupolov4593e422016-10-27 11:00:29 -07002816 Slog.i(LOG_TAG, "removeUser u" + userHandle);
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002817 checkManageOrCreateUsersPermission("Only the system can remove users");
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002818
2819 final boolean isManagedProfile;
2820 synchronized (mUsersLock) {
2821 UserInfo userInfo = getUserInfoLU(userHandle);
2822 isManagedProfile = userInfo != null && userInfo.isManagedProfile();
2823 }
2824 String restriction = isManagedProfile
2825 ? UserManager.DISALLOW_REMOVE_MANAGED_PROFILE : UserManager.DISALLOW_REMOVE_USER;
2826 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(restriction, false)) {
2827 Log.w(LOG_TAG, "Cannot remove user. " + restriction + " is enabled.");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04002828 return false;
2829 }
Nicolas Prevotdf1b87d2016-10-25 13:57:08 +01002830 return removeUserUnchecked(userHandle);
2831 }
Julia Reynolds4ac5f852014-06-23 17:38:51 -04002832
Nicolas Prevotdf1b87d2016-10-25 13:57:08 +01002833 private boolean removeUserUnchecked(int userHandle) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002834 long ident = Binder.clearCallingIdentity();
2835 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002836 final UserData userData;
Fyodor Kupolov0df68cd2015-10-01 13:54:22 -07002837 int currentUser = ActivityManager.getCurrentUser();
2838 if (currentUser == userHandle) {
2839 Log.w(LOG_TAG, "Current user cannot be removed");
2840 return false;
2841 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002842 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002843 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002844 userData = mUsers.get(userHandle);
2845 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002846 return false;
2847 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002848
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002849 addRemovingUserIdLocked(userHandle);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002850 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002851
Kenny Guyee58b4f2014-05-23 15:19:53 +01002852 // Set this to a partially created user, so that the user will be purged
2853 // on next startup, in case the runtime stops now before stopping and
2854 // removing the user completely.
Amith Yamasani12747872015-12-07 14:19:49 -08002855 userData.info.partial = true;
Kenny Guyee58b4f2014-05-23 15:19:53 +01002856 // Mark it as disabled, so that it isn't returned any more when
2857 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002858 userData.info.flags |= UserInfo.FLAG_DISABLED;
2859 writeUserLP(userData);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002860 }
Fyodor Kupolov6c96f7f2017-06-28 18:22:59 -07002861 try {
2862 mAppOpsService.removeUser(userHandle);
2863 } catch (RemoteException e) {
2864 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
2865 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002866
Amith Yamasani12747872015-12-07 14:19:49 -08002867 if (userData.info.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
2868 && userData.info.isManagedProfile()) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002869 // Send broadcast to notify system that the user removed was a
2870 // managed user.
Amith Yamasani12747872015-12-07 14:19:49 -08002871 sendProfileRemovedBroadcast(userData.info.profileGroupId, userData.info.id);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002872 }
2873
2874 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
2875 int res;
2876 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08002877 res = ActivityManager.getService().stopUser(userHandle, /* force= */ true,
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07002878 new IStopUserCallback.Stub() {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002879 @Override
2880 public void userStopped(int userId) {
2881 finishRemoveUser(userId);
2882 }
2883 @Override
2884 public void userStopAborted(int userId) {
2885 }
2886 });
2887 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002888 return false;
2889 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002890 return res == ActivityManager.USER_OP_SUCCESS;
2891 } finally {
2892 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002893 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002894 }
2895
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002896 @VisibleForTesting
2897 void addRemovingUserIdLocked(int userId) {
2898 // We remember deleted user IDs to prevent them from being
2899 // reused during the current boot; they can still be reused
2900 // after a reboot or recycling of userIds.
2901 mRemovingUserIds.put(userId, true);
2902 mRecentlyRemovedIds.add(userId);
2903 // Keep LRU queue of recently removed IDs for recycling
2904 if (mRecentlyRemovedIds.size() > MAX_RECENTLY_REMOVED_IDS_SIZE) {
2905 mRecentlyRemovedIds.removeFirst();
2906 }
2907 }
2908
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002909 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07002910 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002911 // Let other services shutdown any activity and clean up their state before completely
2912 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002913 long ident = Binder.clearCallingIdentity();
2914 try {
2915 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
2916 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002917 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
2918 android.Manifest.permission.MANAGE_USERS,
2919
2920 new BroadcastReceiver() {
2921 @Override
2922 public void onReceive(Context context, Intent intent) {
2923 if (DBG) {
2924 Slog.i(LOG_TAG,
2925 "USER_REMOVED broadcast sent, cleaning up user data "
2926 + userHandle);
2927 }
2928 new Thread() {
Amith Yamasani12747872015-12-07 14:19:49 -08002929 @Override
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002930 public void run() {
Amith Yamasani515d4062015-09-28 11:30:06 -07002931 // Clean up any ActivityManager state
2932 LocalServices.getService(ActivityManagerInternal.class)
2933 .onUserRemoved(userHandle);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002934 removeUserState(userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002935 }
2936 }.start();
2937 }
2938 },
2939
2940 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002941 } finally {
2942 Binder.restoreCallingIdentity(ident);
2943 }
Amith Yamasani2a003292012-08-14 18:25:45 -07002944 }
2945
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002946 private void removeUserState(final int userHandle) {
Paul Crowley91293792016-03-25 15:23:07 -07002947 try {
2948 mContext.getSystemService(StorageManager.class).destroyUserKey(userHandle);
2949 } catch (IllegalStateException e) {
2950 // This may be simply because the user was partially created.
2951 Slog.i(LOG_TAG,
2952 "Destroying key for user " + userHandle + " failed, continuing anyway", e);
2953 }
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002954
Amith Yamasanid04aaa32016-06-13 12:09:36 -07002955 // Cleanup gatekeeper secure user id
2956 try {
2957 final IGateKeeperService gk = GateKeeper.getService();
2958 if (gk != null) {
2959 gk.clearSecureUserId(userHandle);
2960 }
2961 } catch (Exception ex) {
2962 Slog.w(LOG_TAG, "unable to clear GK secure user id");
2963 }
2964
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002965 // Cleanup package manager settings
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002966 mPm.cleanUpUser(this, userHandle);
Amith Yamasanid04aaa32016-06-13 12:09:36 -07002967
2968 // Clean up all data before removing metadata
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -08002969 mUserDataPreparer.destroyUserData(userHandle,
Amith Yamasanid04aaa32016-06-13 12:09:36 -07002970 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2971
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002972 // Remove this user from the list
Fyodor Kupolov82402752015-10-28 14:54:51 -07002973 synchronized (mUsersLock) {
2974 mUsers.remove(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08002975 mIsUserManaged.delete(userHandle);
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00002976 }
2977 synchronized (mUserStates) {
2978 mUserStates.delete(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08002979 }
2980 synchronized (mRestrictionsLock) {
2981 mBaseUserRestrictions.remove(userHandle);
2982 mAppliedUserRestrictions.remove(userHandle);
2983 mCachedEffectiveUserRestrictions.remove(userHandle);
2984 mDevicePolicyLocalUserRestrictions.remove(userHandle);
Pavel Grafov6a40f092016-10-25 15:46:51 +01002985 if (mDevicePolicyGlobalUserRestrictions.get(userHandle) != null) {
2986 mDevicePolicyGlobalUserRestrictions.remove(userHandle);
2987 applyUserRestrictionsForAllUsersLR();
2988 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002989 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002990 // Update the user list
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002991 synchronized (mPackagesLock) {
2992 writeUserListLP();
2993 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06002994 // Remove user file
2995 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
2996 userFile.delete();
Fyodor Kupolov82402752015-10-28 14:54:51 -07002997 updateUserIds();
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002998 if (RELEASE_DELETED_USER_ID) {
2999 synchronized (mUsers) {
3000 mRemovingUserIds.delete(userHandle);
3001 }
3002 }
Amith Yamasani61f57372012-08-31 12:12:28 -07003003 }
3004
Kenny Guyf8d3a232014-05-15 16:09:52 +01003005 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01003006 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01003007 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
3008 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01003009 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
Jeff Sharkeyaf6ec292015-12-17 11:19:00 -07003010 managedProfileIntent.putExtra(Intent.EXTRA_USER_HANDLE, removedUserId);
Kenny Guyf8d3a232014-05-15 16:09:52 +01003011 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01003012 }
3013
Amith Yamasani2a003292012-08-14 18:25:45 -07003014 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07003015 public Bundle getApplicationRestrictions(String packageName) {
3016 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
3017 }
3018
3019 @Override
3020 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003021 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07003022 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07003023 checkSystemOrRoot("get application restrictions for other user/app " + packageName);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003024 }
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003025 synchronized (mAppRestrictionsLock) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003026 // Read the restrictions from XML
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003027 return readApplicationRestrictionsLAr(packageName, userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003028 }
3029 }
3030
3031 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07003032 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003033 int userId) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00003034 checkSystemOrRoot("set application restrictions");
Fyodor Kupolov0d88d542016-04-19 11:37:22 -07003035 if (restrictions != null) {
3036 restrictions.setDefusable(true);
3037 }
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003038 synchronized (mAppRestrictionsLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01003039 if (restrictions == null || restrictions.isEmpty()) {
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003040 cleanAppRestrictionsForPackageLAr(packageName, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01003041 } else {
3042 // Write the restrictions to XML
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003043 writeApplicationRestrictionsLAr(packageName, restrictions, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01003044 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003045 }
Robin Lee66e5d962014-04-09 16:44:21 +01003046
Fyodor Kupolovd2846122016-02-11 18:06:34 -08003047 // Notify package of changes via an intent - only sent to explicitly registered receivers.
3048 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
3049 changeIntent.setPackage(packageName);
3050 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3051 mContext.sendBroadcastAsUser(changeIntent, UserHandle.of(userId));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003052 }
3053
3054 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07003055 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003056 try {
3057 return mContext.getPackageManager().getApplicationInfo(packageName,
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07003058 PackageManager.MATCH_ANY_USER).uid;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003059 } catch (NameNotFoundException nnfe) {
3060 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07003061 } finally {
3062 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003063 }
3064 }
3065
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003066 @GuardedBy("mAppRestrictionsLock")
3067 private static Bundle readApplicationRestrictionsLAr(String packageName, int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003068 AtomicFile restrictionsFile =
3069 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
3070 packageToRestrictionsFileName(packageName)));
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003071 return readApplicationRestrictionsLAr(restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003072 }
3073
3074 @VisibleForTesting
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003075 @GuardedBy("mAppRestrictionsLock")
3076 static Bundle readApplicationRestrictionsLAr(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07003077 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003078 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07003079 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07003080 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07003081 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003082
3083 FileInputStream fis = null;
3084 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003085 fis = restrictionsFile.openRead();
3086 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01003087 parser.setInput(fis, StandardCharsets.UTF_8.name());
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003088 XmlUtils.nextElement(parser);
3089 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003090 Slog.e(LOG_TAG, "Unable to read restrictions file "
3091 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07003092 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003093 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003094 while (parser.next() != XmlPullParser.END_DOCUMENT) {
3095 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003096 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003097 } catch (IOException|XmlPullParserException e) {
3098 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003099 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003100 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003101 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07003102 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003103 }
3104
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003105 private static void readEntry(Bundle restrictions, ArrayList<String> values,
3106 XmlPullParser parser) throws XmlPullParserException, IOException {
3107 int type = parser.getEventType();
3108 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
3109 String key = parser.getAttributeValue(null, ATTR_KEY);
3110 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
3111 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
3112 if (multiple != null) {
3113 values.clear();
3114 int count = Integer.parseInt(multiple);
3115 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
3116 if (type == XmlPullParser.START_TAG
3117 && parser.getName().equals(TAG_VALUE)) {
3118 values.add(parser.nextText().trim());
3119 count--;
3120 }
3121 }
3122 String [] valueStrings = new String[values.size()];
3123 values.toArray(valueStrings);
3124 restrictions.putStringArray(key, valueStrings);
3125 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
3126 restrictions.putBundle(key, readBundleEntry(parser, values));
3127 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
3128 final int outerDepth = parser.getDepth();
3129 ArrayList<Bundle> bundleList = new ArrayList<>();
3130 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
3131 Bundle childBundle = readBundleEntry(parser, values);
3132 bundleList.add(childBundle);
3133 }
3134 restrictions.putParcelableArray(key,
3135 bundleList.toArray(new Bundle[bundleList.size()]));
3136 } else {
3137 String value = parser.nextText().trim();
3138 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
3139 restrictions.putBoolean(key, Boolean.parseBoolean(value));
3140 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
3141 restrictions.putInt(key, Integer.parseInt(value));
3142 } else {
3143 restrictions.putString(key, value);
3144 }
3145 }
3146 }
3147 }
3148
3149 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
3150 throws IOException, XmlPullParserException {
3151 Bundle childBundle = new Bundle();
3152 final int outerDepth = parser.getDepth();
3153 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
3154 readEntry(childBundle, values, parser);
3155 }
3156 return childBundle;
3157 }
3158
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003159 @GuardedBy("mAppRestrictionsLock")
3160 private static void writeApplicationRestrictionsLAr(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07003161 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003162 AtomicFile restrictionsFile = new AtomicFile(
3163 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07003164 packageToRestrictionsFileName(packageName)));
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003165 writeApplicationRestrictionsLAr(restrictions, restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003166 }
3167
3168 @VisibleForTesting
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003169 @GuardedBy("mAppRestrictionsLock")
3170 static void writeApplicationRestrictionsLAr(Bundle restrictions, AtomicFile restrictionsFile) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003171 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003172 try {
3173 fos = restrictionsFile.startWrite();
3174 final BufferedOutputStream bos = new BufferedOutputStream(fos);
3175
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003176 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01003177 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003178 serializer.startDocument(null, true);
3179 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
3180
3181 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003182 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003183 serializer.endTag(null, TAG_RESTRICTIONS);
3184
3185 serializer.endDocument();
3186 restrictionsFile.finishWrite(fos);
3187 } catch (Exception e) {
3188 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003189 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
3190 }
3191 }
3192
3193 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
3194 throws IOException {
3195 for (String key : restrictions.keySet()) {
3196 Object value = restrictions.get(key);
3197 serializer.startTag(null, TAG_ENTRY);
3198 serializer.attribute(null, ATTR_KEY, key);
3199
3200 if (value instanceof Boolean) {
3201 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
3202 serializer.text(value.toString());
3203 } else if (value instanceof Integer) {
3204 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
3205 serializer.text(value.toString());
3206 } else if (value == null || value instanceof String) {
3207 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
3208 serializer.text(value != null ? (String) value : "");
3209 } else if (value instanceof Bundle) {
3210 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
3211 writeBundle((Bundle) value, serializer);
3212 } else if (value instanceof Parcelable[]) {
3213 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
3214 Parcelable[] array = (Parcelable[]) value;
3215 for (Parcelable parcelable : array) {
3216 if (!(parcelable instanceof Bundle)) {
3217 throw new IllegalArgumentException("bundle-array can only hold Bundles");
3218 }
3219 serializer.startTag(null, TAG_ENTRY);
3220 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
3221 writeBundle((Bundle) parcelable, serializer);
3222 serializer.endTag(null, TAG_ENTRY);
3223 }
3224 } else {
3225 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
3226 String[] values = (String[]) value;
3227 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
3228 for (String choice : values) {
3229 serializer.startTag(null, TAG_VALUE);
3230 serializer.text(choice != null ? choice : "");
3231 serializer.endTag(null, TAG_VALUE);
3232 }
3233 }
3234 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003235 }
3236 }
3237
3238 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07003239 public int getUserSerialNumber(int userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003240 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07003241 if (!exists(userHandle)) return -1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003242 return getUserInfoLU(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07003243 }
3244 }
3245
3246 @Override
Fyodor Kupolov605b12a2017-05-10 15:58:09 -07003247 public boolean isUserNameSet(int userHandle) {
3248 synchronized (mUsersLock) {
3249 UserInfo userInfo = getUserInfoLU(userHandle);
3250 return userInfo != null && userInfo.name != null;
3251 }
3252 }
3253
3254 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07003255 public int getUserHandle(int userSerialNumber) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003256 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07003257 for (int userId : mUserIds) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003258 UserInfo info = getUserInfoLU(userId);
Kenny Guy945f8832015-02-10 15:17:26 +00003259 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07003260 }
3261 // Not found
3262 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07003263 }
3264 }
3265
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003266 @Override
3267 public long getUserCreationTime(int userHandle) {
3268 int callingUserId = UserHandle.getCallingUserId();
3269 UserInfo userInfo = null;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003270 synchronized (mUsersLock) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003271 if (callingUserId == userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003272 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003273 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003274 UserInfo parent = getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003275 if (parent != null && parent.id == callingUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003276 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003277 }
3278 }
3279 }
3280 if (userInfo == null) {
3281 throw new SecurityException("userHandle can only be the calling user or a managed "
3282 + "profile associated with this user");
3283 }
3284 return userInfo.creationTime;
3285 }
3286
Amith Yamasani0b285492011-04-14 17:35:23 -07003287 /**
3288 * Caches the list of user ids in an array, adjusting the array size when necessary.
3289 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07003290 private void updateUserIds() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003291 int num = 0;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003292 synchronized (mUsersLock) {
3293 final int userSize = mUsers.size();
3294 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003295 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003296 num++;
3297 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003298 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07003299 final int[] newUsers = new int[num];
3300 int n = 0;
3301 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003302 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003303 newUsers[n++] = mUsers.keyAt(i);
3304 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003305 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07003306 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07003307 }
3308 }
3309
3310 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003311 * Called right before a user is started. This gives us a chance to prepare
3312 * app storage and apply any user restrictions.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003313 */
3314 public void onBeforeStartUser(int userId) {
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003315 UserInfo userInfo = getUserInfo(userId);
3316 if (userInfo == null) {
3317 return;
3318 }
3319 final int userSerial = userInfo.serialNumber;
3320 // Migrate only if build fingerprints mismatch
3321 boolean migrateAppsData = !Build.FINGERPRINT.equals(userInfo.lastLoggedInFingerprint);
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -08003322 mUserDataPreparer.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_DE);
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003323 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_DE, migrateAppsData);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003324
3325 if (userId != UserHandle.USER_SYSTEM) {
3326 synchronized (mRestrictionsLock) {
3327 applyUserRestrictionsLR(userId);
3328 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003329 }
3330 }
3331
3332 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003333 * Called right before a user is unlocked. This gives us a chance to prepare
3334 * app storage.
3335 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003336 public void onBeforeUnlockUser(@UserIdInt int userId) {
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003337 UserInfo userInfo = getUserInfo(userId);
3338 if (userInfo == null) {
3339 return;
3340 }
3341 final int userSerial = userInfo.serialNumber;
3342 // Migrate only if build fingerprints mismatch
3343 boolean migrateAppsData = !Build.FINGERPRINT.equals(userInfo.lastLoggedInFingerprint);
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -08003344 mUserDataPreparer.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_CE);
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003345 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_CE, migrateAppsData);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003346 }
3347
3348 /**
Fyodor Kupolov50979d12017-01-27 17:36:32 -08003349 * Examine all users present on given mounted volume, and destroy data
3350 * belonging to users that are no longer valid, or whose user ID has been
3351 * recycled.
3352 */
3353 void reconcileUsers(String volumeUuid) {
3354 mUserDataPreparer.reconcileUsers(volumeUuid, getUsers(true /* excludeDying */));
3355 }
3356
3357 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07003358 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasanieb437d42016-04-29 09:31:25 -07003359 * This is called with ActivityManagerService lock held.
Amith Yamasani920ace02012-09-20 22:15:37 -07003360 * @param userId the user that was just foregrounded
3361 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003362 public void onUserLoggedIn(@UserIdInt int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -08003363 UserData userData = getUserDataNoChecks(userId);
3364 if (userData == null || userData.info.partial) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003365 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
3366 return;
3367 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003368
3369 final long now = System.currentTimeMillis();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003370 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani12747872015-12-07 14:19:49 -08003371 userData.info.lastLoggedInTime = now;
Amith Yamasani920ace02012-09-20 22:15:37 -07003372 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003373 userData.info.lastLoggedInFingerprint = Build.FINGERPRINT;
3374 scheduleWriteUser(userData);
Amith Yamasani920ace02012-09-20 22:15:37 -07003375 }
3376
3377 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07003378 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani0b285492011-04-14 17:35:23 -07003379 */
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003380 @VisibleForTesting
3381 int getNextAvailableId() {
3382 int nextId;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003383 synchronized (mUsersLock) {
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003384 nextId = scanNextAvailableIdLocked();
3385 if (nextId >= 0) {
3386 return nextId;
3387 }
3388 // All ids up to MAX_USER_ID were used. Remove all mRemovingUserIds,
3389 // except most recently removed
3390 if (mRemovingUserIds.size() > 0) {
3391 Slog.i(LOG_TAG, "All available IDs are used. Recycling LRU ids.");
3392 mRemovingUserIds.clear();
3393 for (Integer recentlyRemovedId : mRecentlyRemovedIds) {
3394 mRemovingUserIds.put(recentlyRemovedId, true);
Amith Yamasani195263742012-08-21 15:40:12 -07003395 }
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003396 nextId = scanNextAvailableIdLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003397 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003398 }
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003399 if (nextId < 0) {
3400 throw new IllegalStateException("No user id available!");
3401 }
3402 return nextId;
3403 }
3404
3405 private int scanNextAvailableIdLocked() {
3406 for (int i = MIN_USER_ID; i < MAX_USER_ID; i++) {
3407 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
3408 return i;
3409 }
3410 }
3411 return -1;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003412 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003413
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003414 private static String packageToRestrictionsFileName(String packageName) {
Amith Yamasanifc95e702013-09-26 13:20:17 -07003415 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
3416 }
3417
Amith Yamasani920ace02012-09-20 22:15:37 -07003418 @Override
Amith Yamasani12747872015-12-07 14:19:49 -08003419 public void setSeedAccountData(int userId, String accountName, String accountType,
3420 PersistableBundle accountOptions, boolean persist) {
3421 checkManageUsersPermission("Require MANAGE_USERS permission to set user seed data");
3422 synchronized (mPackagesLock) {
3423 final UserData userData;
3424 synchronized (mUsersLock) {
3425 userData = getUserDataLU(userId);
3426 if (userData == null) {
3427 Slog.e(LOG_TAG, "No such user for settings seed data u=" + userId);
3428 return;
3429 }
3430 userData.seedAccountName = accountName;
3431 userData.seedAccountType = accountType;
3432 userData.seedAccountOptions = accountOptions;
3433 userData.persistSeedData = persist;
3434 }
3435 if (persist) {
3436 writeUserLP(userData);
3437 }
3438 }
3439 }
3440
3441 @Override
3442 public String getSeedAccountName() throws RemoteException {
3443 checkManageUsersPermission("Cannot get seed account information");
3444 synchronized (mUsersLock) {
3445 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3446 return userData.seedAccountName;
3447 }
3448 }
3449
3450 @Override
3451 public String getSeedAccountType() throws RemoteException {
3452 checkManageUsersPermission("Cannot get seed account information");
3453 synchronized (mUsersLock) {
3454 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3455 return userData.seedAccountType;
3456 }
3457 }
3458
3459 @Override
3460 public PersistableBundle getSeedAccountOptions() throws RemoteException {
3461 checkManageUsersPermission("Cannot get seed account information");
3462 synchronized (mUsersLock) {
3463 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3464 return userData.seedAccountOptions;
3465 }
3466 }
3467
3468 @Override
3469 public void clearSeedAccountData() throws RemoteException {
3470 checkManageUsersPermission("Cannot clear seed account information");
3471 synchronized (mPackagesLock) {
3472 UserData userData;
3473 synchronized (mUsersLock) {
3474 userData = getUserDataLU(UserHandle.getCallingUserId());
3475 if (userData == null) return;
3476 userData.clearSeedAccountData();
3477 }
3478 writeUserLP(userData);
3479 }
3480 }
3481
3482 @Override
3483 public boolean someUserHasSeedAccount(String accountName, String accountType)
3484 throws RemoteException {
3485 checkManageUsersPermission("Cannot check seed account information");
3486 synchronized (mUsersLock) {
3487 final int userSize = mUsers.size();
3488 for (int i = 0; i < userSize; i++) {
3489 final UserData data = mUsers.valueAt(i);
3490 if (data.info.isInitialized()) continue;
3491 if (data.seedAccountName == null || !data.seedAccountName.equals(accountName)) {
3492 continue;
3493 }
3494 if (data.seedAccountType == null || !data.seedAccountType.equals(accountType)) {
3495 continue;
3496 }
3497 return true;
3498 }
3499 }
3500 return false;
3501 }
3502
3503 @Override
Todd Kennedy60459ab2015-10-30 11:32:16 -07003504 public void onShellCommand(FileDescriptor in, FileDescriptor out,
Dianne Hackborn354736e2016-08-22 17:00:05 -07003505 FileDescriptor err, String[] args, ShellCallback callback,
3506 ResultReceiver resultReceiver) {
3507 (new Shell()).exec(this, in, out, err, args, callback, resultReceiver);
Todd Kennedy60459ab2015-10-30 11:32:16 -07003508 }
3509
3510 int onShellCommand(Shell shell, String cmd) {
3511 if (cmd == null) {
3512 return shell.handleDefaultCommands(cmd);
3513 }
3514
3515 final PrintWriter pw = shell.getOutPrintWriter();
3516 try {
3517 switch(cmd) {
3518 case "list":
3519 return runList(pw);
3520 }
3521 } catch (RemoteException e) {
3522 pw.println("Remote exception: " + e);
3523 }
3524 return -1;
3525 }
3526
3527 private int runList(PrintWriter pw) throws RemoteException {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003528 final IActivityManager am = ActivityManager.getService();
Todd Kennedy60459ab2015-10-30 11:32:16 -07003529 final List<UserInfo> users = getUsers(false);
3530 if (users == null) {
3531 pw.println("Error: couldn't get users");
3532 return 1;
3533 } else {
3534 pw.println("Users:");
3535 for (int i = 0; i < users.size(); i++) {
Jeff Sharkeye17ac152015-11-06 22:40:29 -08003536 String running = am.isUserRunning(users.get(i).id, 0) ? " running" : "";
Todd Kennedy60459ab2015-10-30 11:32:16 -07003537 pw.println("\t" + users.get(i).toString() + running);
3538 }
3539 return 0;
3540 }
3541 }
3542
3543 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -07003544 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06003545 if (!DumpUtils.checkDumpPermission(mContext, LOG_TAG, pw)) return;
Amith Yamasani920ace02012-09-20 22:15:37 -07003546
3547 long now = System.currentTimeMillis();
Makoto Onuki73dded22017-12-20 13:14:48 +09003548 final long nowRealtime = SystemClock.elapsedRealtime();
Amith Yamasani920ace02012-09-20 22:15:37 -07003549 StringBuilder sb = new StringBuilder();
3550 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003551 synchronized (mUsersLock) {
3552 pw.println("Users:");
3553 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003554 UserData userData = mUsers.valueAt(i);
3555 if (userData == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003556 continue;
3557 }
Amith Yamasani12747872015-12-07 14:19:49 -08003558 UserInfo userInfo = userData.info;
3559 final int userId = userInfo.id;
3560 pw.print(" "); pw.print(userInfo);
3561 pw.print(" serialNo="); pw.print(userInfo.serialNumber);
Makoto Onukie7927da2015-11-25 10:05:17 -08003562 if (mRemovingUserIds.get(userId)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003563 pw.print(" <removing> ");
3564 }
Amith Yamasani12747872015-12-07 14:19:49 -08003565 if (userInfo.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003566 pw.print(" <partial>");
3567 }
3568 pw.println();
Makoto Onuki88aef752017-03-29 16:52:03 -07003569 pw.print(" State: ");
3570 final int state;
3571 synchronized (mUserStates) {
3572 state = mUserStates.get(userId, -1);
3573 }
3574 pw.println(UserState.stateToString(state));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003575 pw.print(" Created: ");
Makoto Onuki73dded22017-12-20 13:14:48 +09003576 dumpTimeAgo(pw, sb, now, userInfo.creationTime);
3577
Fyodor Kupolov82402752015-10-28 14:54:51 -07003578 pw.print(" Last logged in: ");
Makoto Onuki73dded22017-12-20 13:14:48 +09003579 dumpTimeAgo(pw, sb, now, userInfo.lastLoggedInTime);
3580
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003581 pw.print(" Last logged in fingerprint: ");
3582 pw.println(userInfo.lastLoggedInFingerprint);
Makoto Onuki73dded22017-12-20 13:14:48 +09003583
3584 pw.print(" Start time: ");
3585 dumpTimeAgo(pw, sb, nowRealtime, userData.startRealtime);
3586
3587 pw.print(" Unlock time: ");
3588 dumpTimeAgo(pw, sb, nowRealtime, userData.unlockRealtime);
3589
Makoto Onukie7927da2015-11-25 10:05:17 -08003590 pw.print(" Has profile owner: ");
3591 pw.println(mIsUserManaged.get(userId));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003592 pw.println(" Restrictions:");
3593 synchronized (mRestrictionsLock) {
3594 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003595 pw, " ", mBaseUserRestrictions.get(userInfo.id));
Pavel Grafov6a40f092016-10-25 15:46:51 +01003596 pw.println(" Device policy global restrictions:");
3597 UserRestrictionsUtils.dumpRestrictions(
3598 pw, " ", mDevicePolicyGlobalUserRestrictions.get(userInfo.id));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003599 pw.println(" Device policy local restrictions:");
3600 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003601 pw, " ", mDevicePolicyLocalUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003602 pw.println(" Effective restrictions:");
3603 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003604 pw, " ", mCachedEffectiveUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003605 }
Amith Yamasani12747872015-12-07 14:19:49 -08003606
3607 if (userData.account != null) {
3608 pw.print(" Account name: " + userData.account);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08003609 pw.println();
3610 }
Amith Yamasani12747872015-12-07 14:19:49 -08003611
3612 if (userData.seedAccountName != null) {
3613 pw.print(" Seed account name: " + userData.seedAccountName);
3614 pw.println();
3615 if (userData.seedAccountType != null) {
3616 pw.print(" account type: " + userData.seedAccountType);
3617 pw.println();
3618 }
3619 if (userData.seedAccountOptions != null) {
3620 pw.print(" account options exist");
3621 pw.println();
3622 }
3623 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003624 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003625 }
Amith Yamasani12747872015-12-07 14:19:49 -08003626 pw.println();
Pavel Grafov6a40f092016-10-25 15:46:51 +01003627 pw.println(" Device owner id:" + mDeviceOwnerUserId);
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01003628 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003629 pw.println(" Guest restrictions:");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003630 synchronized (mGuestRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003631 UserRestrictionsUtils.dumpRestrictions(pw, " ", mGuestRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003632 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003633 synchronized (mUsersLock) {
3634 pw.println();
3635 pw.println(" Device managed: " + mIsDeviceManaged);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003636 if (mRemovingUserIds.size() > 0) {
3637 pw.println();
3638 pw.println(" Recently removed userIds: " + mRecentlyRemovedIds);
3639 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003640 }
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003641 synchronized (mUserStates) {
3642 pw.println(" Started users state: " + mUserStates);
3643 }
Amith Yamasani12747872015-12-07 14:19:49 -08003644 // Dump some capabilities
3645 pw.println();
3646 pw.println(" Max users: " + UserManager.getMaxSupportedUsers());
3647 pw.println(" Supports switchable users: " + UserManager.supportsMultipleUsers());
Lenka Trochtova02fee152015-12-22 14:26:18 +01003648 pw.println(" All guests ephemeral: " + Resources.getSystem().getBoolean(
3649 com.android.internal.R.bool.config_guestUserEphemeral));
Amith Yamasani920ace02012-09-20 22:15:37 -07003650 }
3651 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08003652
Makoto Onuki73dded22017-12-20 13:14:48 +09003653 private static void dumpTimeAgo(PrintWriter pw, StringBuilder sb, long nowTime, long time) {
3654 if (time == 0) {
3655 pw.println("<unknown>");
3656 } else {
3657 sb.setLength(0);
3658 TimeUtils.formatDuration(nowTime - time, sb);
3659 sb.append(" ago");
3660 pw.println(sb);
3661 }
3662 }
3663
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08003664 final class MainHandler extends Handler {
3665
3666 @Override
3667 public void handleMessage(Message msg) {
3668 switch (msg.what) {
3669 case WRITE_USER_MSG:
3670 removeMessages(WRITE_USER_MSG, msg.obj);
3671 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08003672 int userId = ((UserData) msg.obj).info.id;
3673 UserData userData = getUserDataNoChecks(userId);
3674 if (userData != null) {
3675 writeUserLP(userData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08003676 }
3677 }
3678 }
3679 }
3680 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07003681
3682 /**
3683 * @param userId
3684 * @return whether the user has been initialized yet
3685 */
Todd Kennedy0eb97382017-10-03 16:57:22 -07003686 boolean isUserInitialized(int userId) {
3687 return mLocalService.isUserInitialized(userId);
Amith Yamasanibb054c92015-07-09 14:16:27 -07003688 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003689
3690 private class LocalService extends UserManagerInternal {
Makoto Onuki068c54a2015-10-13 14:34:03 -07003691 @Override
Pavel Grafov6a40f092016-10-25 15:46:51 +01003692 public void setDevicePolicyUserRestrictions(int userId, @Nullable Bundle restrictions,
3693 boolean isDeviceOwner, int cameraRestrictionScope) {
3694 UserManagerService.this.setDevicePolicyUserRestrictionsInner(userId, restrictions,
3695 isDeviceOwner, cameraRestrictionScope);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003696 }
3697
3698 @Override
3699 public Bundle getBaseUserRestrictions(int userId) {
3700 synchronized (mRestrictionsLock) {
3701 return mBaseUserRestrictions.get(userId);
3702 }
3703 }
3704
3705 @Override
3706 public void setBaseUserRestrictionsByDpmsForMigration(
3707 int userId, Bundle baseRestrictions) {
3708 synchronized (mRestrictionsLock) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01003709 if (updateRestrictionsIfNeededLR(
3710 userId, new Bundle(baseRestrictions), mBaseUserRestrictions)) {
3711 invalidateEffectiveUserRestrictionsLR(userId);
3712 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003713 }
3714
Amith Yamasani12747872015-12-07 14:19:49 -08003715 final UserData userData = getUserDataNoChecks(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003716 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08003717 if (userData != null) {
3718 writeUserLP(userData);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003719 } else {
3720 Slog.w(LOG_TAG, "UserInfo not found for " + userId);
3721 }
3722 }
3723 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08003724
3725 @Override
3726 public boolean getUserRestriction(int userId, String key) {
3727 return getUserRestrictions(userId).getBoolean(key);
3728 }
3729
3730 @Override
3731 public void addUserRestrictionsListener(UserRestrictionsListener listener) {
3732 synchronized (mUserRestrictionsListeners) {
3733 mUserRestrictionsListeners.add(listener);
3734 }
3735 }
3736
3737 @Override
3738 public void removeUserRestrictionsListener(UserRestrictionsListener listener) {
3739 synchronized (mUserRestrictionsListeners) {
3740 mUserRestrictionsListeners.remove(listener);
3741 }
3742 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003743
3744 @Override
3745 public void setDeviceManaged(boolean isManaged) {
3746 synchronized (mUsersLock) {
3747 mIsDeviceManaged = isManaged;
3748 }
3749 }
3750
3751 @Override
3752 public void setUserManaged(int userId, boolean isManaged) {
3753 synchronized (mUsersLock) {
3754 mIsUserManaged.put(userId, isManaged);
3755 }
3756 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01003757
3758 @Override
3759 public void setUserIcon(int userId, Bitmap bitmap) {
3760 long ident = Binder.clearCallingIdentity();
3761 try {
3762 synchronized (mPackagesLock) {
3763 UserData userData = getUserDataNoChecks(userId);
3764 if (userData == null || userData.info.partial) {
3765 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
3766 return;
3767 }
3768 writeBitmapLP(userData.info, bitmap);
3769 writeUserLP(userData);
3770 }
3771 sendUserInfoChangedBroadcast(userId);
3772 } finally {
3773 Binder.restoreCallingIdentity(ident);
3774 }
3775 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01003776
3777 @Override
3778 public void setForceEphemeralUsers(boolean forceEphemeralUsers) {
3779 synchronized (mUsersLock) {
3780 mForceEphemeralUsers = forceEphemeralUsers;
3781 }
3782 }
3783
3784 @Override
3785 public void removeAllUsers() {
3786 if (UserHandle.USER_SYSTEM == ActivityManager.getCurrentUser()) {
3787 // Remove the non-system users straight away.
3788 removeNonSystemUsers();
3789 } else {
3790 // Switch to the system user first and then remove the other users.
3791 BroadcastReceiver userSwitchedReceiver = new BroadcastReceiver() {
3792 @Override
3793 public void onReceive(Context context, Intent intent) {
3794 int userId =
3795 intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3796 if (userId != UserHandle.USER_SYSTEM) {
3797 return;
3798 }
3799 mContext.unregisterReceiver(this);
3800 removeNonSystemUsers();
3801 }
3802 };
3803 IntentFilter userSwitchedFilter = new IntentFilter();
3804 userSwitchedFilter.addAction(Intent.ACTION_USER_SWITCHED);
3805 mContext.registerReceiver(
3806 userSwitchedReceiver, userSwitchedFilter, null, mHandler);
3807
3808 // Switch to the system user.
3809 ActivityManager am =
3810 (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
3811 am.switchUser(UserHandle.USER_SYSTEM);
3812 }
3813 }
phweisse9c44062016-02-10 12:57:38 +01003814
3815 @Override
Lenka Trochtova1ddda472016-02-12 10:42:12 +01003816 public void onEphemeralUserStop(int userId) {
3817 synchronized (mUsersLock) {
3818 UserInfo userInfo = getUserInfoLU(userId);
3819 if (userInfo != null && userInfo.isEphemeral()) {
3820 // Do not allow switching back to the ephemeral user again as the user is going
3821 // to be deleted.
3822 userInfo.flags |= UserInfo.FLAG_DISABLED;
3823 if (userInfo.isGuest()) {
3824 // Indicate that the guest will be deleted after it stops.
3825 userInfo.guestToRemove = true;
3826 }
3827 }
3828 }
3829 }
3830
3831 @Override
Alex Chaub6a9f942017-11-07 11:28:56 +08003832 public UserInfo createUserEvenWhenDisallowed(String name, int flags,
3833 String[] disallowedPackages) {
3834 UserInfo user = createUserInternalUnchecked(name, flags, UserHandle.USER_NULL,
3835 disallowedPackages);
phweisse9c44062016-02-10 12:57:38 +01003836 // Keep this in sync with UserManager.createUser
Christine Franks97a54802017-08-09 10:06:43 -07003837 if (user != null && !user.isAdmin() && !user.isDemo()) {
phweisse9c44062016-02-10 12:57:38 +01003838 setUserRestriction(UserManager.DISALLOW_SMS, true, user.id);
3839 setUserRestriction(UserManager.DISALLOW_OUTGOING_CALLS, true, user.id);
3840 }
3841 return user;
3842 }
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003843
3844 @Override
Nicolas Prevotdf1b87d2016-10-25 13:57:08 +01003845 public boolean removeUserEvenWhenDisallowed(int userId) {
3846 return removeUserUnchecked(userId);
3847 }
3848
3849 @Override
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003850 public boolean isUserRunning(int userId) {
3851 synchronized (mUserStates) {
3852 return mUserStates.get(userId, -1) >= 0;
3853 }
3854 }
3855
3856 @Override
3857 public void setUserState(int userId, int userState) {
3858 synchronized (mUserStates) {
3859 mUserStates.put(userId, userState);
3860 }
3861 }
3862
3863 @Override
3864 public void removeUserState(int userId) {
3865 synchronized (mUserStates) {
3866 mUserStates.delete(userId);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003867 }
3868 }
3869
3870 @Override
Michael Wachenschwanz3f2b6552017-05-15 13:53:09 -07003871 public int[] getUserIds() {
3872 return UserManagerService.this.getUserIds();
3873 }
3874
3875 @Override
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003876 public boolean isUserUnlockingOrUnlocked(int userId) {
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07003877 int state;
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003878 synchronized (mUserStates) {
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07003879 state = mUserStates.get(userId, -1);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003880 }
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07003881 // Special case, in the stopping/shutdown state user key can still be unlocked
3882 if (state == UserState.STATE_STOPPING || state == UserState.STATE_SHUTDOWN) {
3883 return StorageManager.isUserKeyUnlocked(userId);
3884 }
3885 return (state == UserState.STATE_RUNNING_UNLOCKING)
3886 || (state == UserState.STATE_RUNNING_UNLOCKED);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003887 }
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08003888
3889 @Override
3890 public boolean isUserUnlocked(int userId) {
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07003891 int state;
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08003892 synchronized (mUserStates) {
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07003893 state = mUserStates.get(userId, -1);
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08003894 }
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07003895 // Special case, in the stopping/shutdown state user key can still be unlocked
3896 if (state == UserState.STATE_STOPPING || state == UserState.STATE_SHUTDOWN) {
3897 return StorageManager.isUserKeyUnlocked(userId);
3898 }
3899 return state == UserState.STATE_RUNNING_UNLOCKED;
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08003900 }
Todd Kennedy0eb97382017-10-03 16:57:22 -07003901
3902 @Override
3903 public boolean isUserInitialized(int userId) {
3904 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
3905 }
3906
3907 @Override
3908 public boolean exists(int userId) {
3909 return getUserInfoNoChecks(userId) != null;
3910 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01003911 }
3912
3913 /* Remove all the users except of the system one. */
3914 private void removeNonSystemUsers() {
3915 ArrayList<UserInfo> usersToRemove = new ArrayList<>();
3916 synchronized (mUsersLock) {
3917 final int userSize = mUsers.size();
3918 for (int i = 0; i < userSize; i++) {
3919 UserInfo ui = mUsers.valueAt(i).info;
3920 if (ui.id != UserHandle.USER_SYSTEM) {
3921 usersToRemove.add(ui);
3922 }
3923 }
3924 }
3925 for (UserInfo ui: usersToRemove) {
3926 removeUser(ui.id);
3927 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003928 }
Todd Kennedy60459ab2015-10-30 11:32:16 -07003929
3930 private class Shell extends ShellCommand {
3931 @Override
3932 public int onCommand(String cmd) {
3933 return onShellCommand(this, cmd);
3934 }
3935
3936 @Override
3937 public void onHelp() {
3938 final PrintWriter pw = getOutPrintWriter();
3939 pw.println("User manager (user) commands:");
3940 pw.println(" help");
3941 pw.println(" Print this help text.");
3942 pw.println("");
3943 pw.println(" list");
3944 pw.println(" Prints all users on the system.");
3945 }
3946 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003947
3948 private static void debug(String message) {
3949 Log.d(LOG_TAG, message +
3950 (DBG_WITH_STACKTRACE ? " called at\n" + Debug.getCallers(10, " ") : ""));
3951 }
Kenny Guy02c89902016-11-15 19:36:38 +00003952
3953 @VisibleForTesting
3954 static int getMaxManagedProfiles() {
3955 // Allow overriding max managed profiles on debuggable builds for testing
3956 // of multiple profiles.
3957 if (!Build.IS_DEBUGGABLE) {
3958 return MAX_MANAGED_PROFILES;
3959 } else {
3960 return SystemProperties.getInt("persist.sys.max_profiles",
3961 MAX_MANAGED_PROFILES);
3962 }
3963 }
3964
3965 @VisibleForTesting
3966 int getFreeProfileBadgeLU(int parentUserId) {
3967 int maxManagedProfiles = getMaxManagedProfiles();
3968 boolean[] usedBadges = new boolean[maxManagedProfiles];
3969 final int userSize = mUsers.size();
3970 for (int i = 0; i < userSize; i++) {
3971 UserInfo ui = mUsers.valueAt(i).info;
3972 // Check which badge indexes are already used by this profile group.
3973 if (ui.isManagedProfile()
3974 && ui.profileGroupId == parentUserId
3975 && !mRemovingUserIds.get(ui.id)
3976 && ui.profileBadge < maxManagedProfiles) {
3977 usedBadges[ui.profileBadge] = true;
3978 }
3979 }
3980 for (int i = 0; i < maxManagedProfiles; i++) {
3981 if (!usedBadges[i]) {
3982 return i;
3983 }
3984 }
3985 return 0;
3986 }
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07003987
3988 /**
3989 * Checks if the given user has a managed profile associated with it.
3990 * @param userId The parent user
3991 * @return
3992 */
3993 boolean hasManagedProfile(int userId) {
3994 synchronized (mUsersLock) {
3995 UserInfo userInfo = getUserInfoLU(userId);
3996 final int userSize = mUsers.size();
3997 for (int i = 0; i < userSize; i++) {
3998 UserInfo profile = mUsers.valueAt(i).info;
3999 if (userId != profile.id && isProfileOf(userInfo, profile)) {
4000 return true;
4001 }
4002 }
4003 return false;
4004 }
4005 }
Tony Makd390ae92017-12-28 13:23:10 +00004006
4007 /**
4008 * Check if the calling package name matches with the calling UID, throw
4009 * {@link SecurityException} if not.
4010 */
4011 private void verifyCallingPackage(String callingPackage, int callingUid) {
4012 int packageUid = mPm.getPackageUid(callingPackage, 0, UserHandle.getUserId(callingUid));
4013 if (packageUid != callingUid) {
4014 throw new SecurityException("Specified package " + callingPackage
4015 + " does not match the calling uid " + callingUid);
4016 }
4017 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07004018}